<commit_before>import fs from 'fs'
import { of, from } from 'most'

import ctmParser from 'usco-ctm-parser'
import objParser from 'usco-obj-parser'

import makeStlStream from 'usco-stl-parser'
import make3mfStream from 'usco-3mf-parser'

import prepareRender from './render'
import { writeContextToFile } from 'usco-image-utils/dist/imgUtils'
import { getNameAndExtension } from 'usco-file-utils'

import create from '@most/create'
import entityPrep from './utils/entityPrep'

import { camera as camerabase } from './utils/camera'
import { computeCameraToFitBounds, cameraOffsetToEntityBoundsCenter } from 'usco-camera-utils'

import * as orbitControls from 'usco-orbit-controls'
import mat4 from 'gl-mat4'

import { getArgs } from './utils/args'

const version = require('../package.json').version

function setProjection (state, input) {
  const projection = mat4.perspective([], state.fov, input.width / input.height, // context.viewportWidth / context.viewportHeight,
    state.near,
    state.far)
  // state = Object.assign({}, state, {projection})
  state.projection = projection
  state.aspect = input.width / input.height
  // state = Object.assign({}, state, update(settings, state)) // not sure
  return state
}

// deal with command line args etc
let inputParams = getArgs()

const defaults = {
  resolution: '640x480',
  cameraPosition: `[${camerabase.position.join(',')}]`,
  input: undefined,
  output: 'output.png'
}
let params = Object.assign({}, defaults, inputParams)

const {resolution, input} = params
const outputPath = params.output
const [width, height] = resolution.split('x').map(e => parseInt(e, 10))
const cameraPosition = params.cameraPosition.replace('[', '').replace(']', '').replace(/' '/g, '').split(',').map(e => parseFloat(e, 10))
const {ext} = getNameAndExtension(input)

if (Object.keys(inputParams).length === 0) {
  console.log(`usco-headless-renderer v${version}
    Missing parameters:
    use it like this : usco-headless-renderer input=<PATH-TO-FILE> output=<PATH-TO-OUTPUT.png> resolution=320x240 cameraPosition=[75, 75, 145]
    `)
  process.exit(1)
}

console.log(`Running renderer with params:
  input:${input}, output:${outputPath}, resolution:${width}x${height}, cameraPosition:${cameraPosition}`)

const parseOptions = {concat: true}
const parsers = {
  'stl': makeStlStream(parseOptions),
  '3mf': make3mfStream(parseOptions),
  'ctm': ctmParser,
  'obj': objParser
}

// create webgl context
const gl = require('gl')(width, height)
// setup regl
const regl = require('regl')({
  gl,
// extensions:['oes_element_index_uint']
}, (width, height))
// setup render function
const render = prepareRender(regl)

const parsedData$ = create((add, end, error) => {
  const parser = parsers[ext]
  if (!parser) {
    error(new Error(`no parser found for ${ext} format`))
  }
  if (ext === 'stl' || ext === '3mf') {
    fs.createReadStream(input)
      .pipe(parsers[ext]) // we get a stream back
      .on('data', function (parsedData) {
        add(parsedData)
      })
  } else {
    let data = fs.readFileSync(input, 'binary')
    const parsedObs$ = parsers[ext](data, {})
    parsedObs$
      .forEach(parsed => add(parsed))
  }
})

entityPrep(parsedData$, regl)
  .flatMapError(error => {
    console.error(error)
    of(undefined)
  })
  .filter(x => x !== undefined)
  .map(x => [x]) // FIXME: temporary hack until data structures are stable
  .forEach(function (entities) {
    // console.log(entities)
    const {bounds, transforms} = entities[0]
    let controlParams = orbitControls.params
    controlParams.limits.minDistance = 0
    camerabase.near = 0.01
    camerabase.position = cameraPosition

    let camera = setProjection(camerabase, {width, height})
    camera = Object.assign({}, camera, cameraOffsetToEntityBoundsCenter({camera, bounds, transforms, axis: 2}))
    camera = Object.assign({}, camera, computeCameraToFitBounds({camera, bounds, transforms}))
    camera = Object.assign({}, camera, orbitControls.update(controlParams, camera))

    render({entities, camera, view: camera.view, background: [1, 1, 1, 1]})
    writeContextToFile(gl, width, height, 4, outputPath)
  })

  /*
  fs.createReadStream(input)
  .pipe(parsers[ext]) // we get a stream back
  .on('data', function (geometry) {
    console.log('done with parsing') // , parsedData)

    render({entities: [], camera: {projection: null}, view: null, background: [1, 1, 1, 1]})
    writeContextToFile(gl, 256, 256, 4, outputPath)
  })*/
<commit_msg>feat(verbosity): added support for verbose flag<commit_after>import fs from 'fs'
import { of, from } from 'most'

import ctmParser from 'usco-ctm-parser'
import objParser from 'usco-obj-parser'

import makeStlStream from 'usco-stl-parser'
import make3mfStream from 'usco-3mf-parser'

import prepareRender from './render'
import { writeContextToFile } from 'usco-image-utils/dist/imgUtils'
import { getNameAndExtension } from 'usco-file-utils'

import create from '@most/create'
import entityPrep from './utils/entityPrep'

import { camera as camerabase } from './utils/camera'
import { computeCameraToFitBounds, cameraOffsetToEntityBoundsCenter } from 'usco-camera-utils'

import * as orbitControls from 'usco-orbit-controls'
import mat4 from 'gl-mat4'

import { getArgs } from './utils/args'

const version = require('../package.json').version

function setProjection (state, input) {
  const projection = mat4.perspective([], state.fov, input.width / input.height, // context.viewportWidth / context.viewportHeight,
    state.near,
    state.far)
  // state = Object.assign({}, state, {projection})
  state.projection = projection
  state.aspect = input.width / input.height
  // state = Object.assign({}, state, update(settings, state)) // not sure
  return state
}

// deal with command line args etc
let inputParams = getArgs()

const defaults = {
  resolution: '640x480',
  cameraPosition: `[${camerabase.position.join(',')}]`,
  input: undefined,
  output: 'output.png',
  verbose: false
}
let params = Object.assign({}, defaults, inputParams)

const {resolution, input, verbose} = params
const outputPath = params.output
const [width, height] = resolution.split('x').map(e => parseInt(e, 10))
const cameraPosition = params.cameraPosition.replace('[', '').replace(']', '').replace(/' '/g, '').split(',').map(e => parseFloat(e, 10))
const {ext} = getNameAndExtension(input)

if (Object.keys(inputParams).length === 0) {
  console.log(`usco-headless-renderer v${version}
    Missing parameters:
    use it like this : usco-headless-renderer input=<PATH-TO-FILE> output=<PATH-TO-OUTPUT.png> resolution=320x240 cameraPosition=[75, 75, 145] verbose=true
    `)
  process.exit(1)
}

if (verbose) {
  console.log(`Running renderer with params:
    input:${input}, output:${outputPath}, resolution:${width}x${height}, cameraPosition:${cameraPosition}`)
}

const parseOptions = {concat: true}
const parsers = {
  'stl': makeStlStream(parseOptions),
  '3mf': make3mfStream(parseOptions),
  'ctm': ctmParser,
  'obj': objParser
}

// create webgl context
const gl = require('gl')(width, height)
// setup regl
const regl = require('regl')({
  gl,
// extensions:['oes_element_index_uint']
}, (width, height))
// setup render function
const render = prepareRender(regl)

const parsedData$ = create((add, end, error) => {
  const parser = parsers[ext]
  if (!parser) {
    error(new Error(`no parser found for ${ext} format`))
  }
  if (ext === 'stl' || ext === '3mf') {
    fs.createReadStream(input)
      .pipe(parsers[ext]) // we get a stream back
      .on('data', function (parsedData) {
        add(parsedData)
      })
  } else {
    let data = fs.readFileSync(input, 'binary')
    const parsedObs$ = parsers[ext](data, {})
    parsedObs$
      .forEach(parsed => add(parsed))
  }
})

entityPrep(parsedData$, regl)
  .flatMapError(error => {
    console.error(error)
    of(undefined)
  })
  .filter(x => x !== undefined)
  .map(x => [x]) // FIXME: temporary hack until data structures are stable
  .forEach(function (entities) {
    // console.log(entities)
    const {bounds, transforms} = entities[0]
    let controlParams = orbitControls.params
    controlParams.limits.minDistance = 0
    camerabase.near = 0.01
    camerabase.position = cameraPosition

    let camera = setProjection(camerabase, {width, height})
    camera = Object.assign({}, camera, cameraOffsetToEntityBoundsCenter({camera, bounds, transforms, axis: 2}))
    camera = Object.assign({}, camera, computeCameraToFitBounds({camera, bounds, transforms}))
    camera = Object.assign({}, camera, orbitControls.update(controlParams, camera))

    render({entities, camera, view: camera.view, background: [1, 1, 1, 1]})
    writeContextToFile(gl, width, height, 4, outputPath)
  })

  /*
  fs.createReadStream(input)
  .pipe(parsers[ext]) // we get a stream back
  .on('data', function (geometry) {
    console.log('done with parsing') // , parsedData)

    render({entities: [], camera: {projection: null}, view: null, background: [1, 1, 1, 1]})
    writeContextToFile(gl, 256, 256, 4, outputPath)
  })*/
<|endoftext|>


<commit_before>'use strict'

import React, { Component, PropTypes } from 'react/addons'
import classnames from 'classnames'

const CSSTransitionGroup = React.addons.CSSTransitionGroup;
const TAB = 9;
const SPACEBAR = 32;
const ALIGNMENTS = ['center', 'right', 'left'];
const MENU_SIZES = ['sm', 'md', 'lg', 'xl'];

class DropdownMenu extends Component {
  constructor(props) {
    super(props);

    this._lastWindowClickEvent = null;
  }

  static propTypes = {
    isOpen: PropTypes.bool.isRequired,
    close: PropTypes.func.isRequired,
    toggle: PropTypes.node.isRequired,
    inverse: PropTypes.bool,
    align: PropTypes.oneOf(ALIGNMENTS),
    animAlign: PropTypes.oneOf(ALIGNMENTS),
    textAlign: PropTypes.oneOf(ALIGNMENTS),
    menuAlign: PropTypes.oneOf(ALIGNMENTS),
    className: PropTypes.string,
    size: PropTypes.oneOf(MENU_SIZES),
    upwards: PropTypes.bool,
    animate: PropTypes.bool,
  }

  static defaultProps = {
    inverse: false,
    align: 'center',
    animAlign: null,
    textAlign: null,
    menuAlign: null,
    className: null,
    size: null,
    upwards: false,
    animate: true,
  }

  componentDidUpdate(prevProps, prevState) {
    const menuItems = React.findDOMNode(this.refs.menuItems);
    if(this.props.isOpen && !prevProps.isOpen) {
      this._lastWindowClickEvent = this.handleClickOutside;

      document.addEventListener('click', this._lastWindowClickEvent);
      menuItems.addEventListener('click', this.props.close);
      menuItems.addEventListener('onkeydown', this.close);
    } else if(!this.props.isOpen && prevProps.isOpen) {
      document.removeEventListener('click', this._lastWindowClickEvent);
      menuItems.removeEventListener('click', this.props.close);
      menuItems.removeEventListener('onkeydown', this.close);

      this._lastWindowClickEvent = null;
    }
  }

  componentWillUnmount() {
    if(this._lastWindowClickEvent) {
      document.removeEventListener('click', this._lastWindowClickEvent);
    }
  }

  close = (e) => {
    const key = e.which || e.keyCode;
    if(key === SPACEBAR) {
      this.props.close();
      e.preventDefault();
    }
  }

  handleClickOutside = (e) => {
    const node = React.findDOMNode(this);
    let target = e.target;

    while(target.parentNode) {
      if(target === node) {
        return;
      }

      target = target.parentNode;
    }

    this.props.close(e);
  }

  handleKeyDown = (e) => {
    const key = e.which || e.keyCode;
    if(key !== TAB) {
      return;
    }

    const items = React.findDOMNode(this).querySelectorAll('button,a');
    const id = e.shiftKey ? 1 : items.length - 1;

    if(e.target == items[id]) {
      this.props.close(e);
    }
  }

  render() {
    const { menuAlign, align, inverse, size, className } = this.props;

    const menuClassName = classnames(
      'dd-menu',
      `dd-menu-${menuAlign || align}`,
      { 'dd-menu-inverse': inverse },
      className,
      size ? ('dd-menu-' + size) : null
    );

    const { textAlign, upwards, animAlign, animate } = this.props;

    const listClassName = 'dd-items-' + (textAlign || align);
    const transitionProps = {
      transitionName: 'grow-from-' + (upwards ? 'up-' : '') + (animAlign || align),
      component: 'div',
      className: classnames('dd-menu-items', { 'dd-items-upwards': upwards }),
      onKeyDown: this.handleKeyDown,
      ref: 'menuItems',
      transitionEnter: animate,
      transitionLeave: animate,
    };

    return (

        {this.props.toggle}
        <CSSTransitionGroup {...transitionProps}>
          {this.props.isOpen &&
{this.props.children}
}
        </CSSTransitionGroup>

    );
  }
}

module.exports = DropdownMenu;

class NestedDropdownMenu extends Component {
  constructor(props) {
    super(props);

    this.state = { isOpen: false };
    this._closeCallback = null;
  }

  static propTypes = {
    toggle: PropTypes.node.isRequired,
    nested: PropTypes.oneOf(['inherit', 'reverse', 'left', 'right']),
    animate: PropTypes.bool,
    direction: PropTypes.oneOf(['left', 'right']),
    upwards: PropTypes.bool,
    delay: PropTypes.number,
  }

  static defaultProps = {
    nested: 'reverse',
    animate: false,
    direction: 'right',
    upwards: false,
    delay: 500,
  }

  open = () => {
    if(this._closeCallback) {
      clearTimeout(this._closeCallback);
      this._closeCallback = null;
    }
    this.setState({ isOpen: true });
  }

  close = () => {
    this._closeCallback = setTimeout(_ => {
      this.setState({ isOpen: false });
    }.bind(this), this.props.delay);
  }

  render() {
    const { toggle, children, nested, animate, direction, upwards } = this.props;
    const { isOpen } = this.state;

    const itemProps = {
      className: classnames('nested-dd-menu', `nested-${nested}`),
      onMouseOver: this.open,
      onMouseLeave: this.close,
      onFocus: this.open,
      onBlur: this.close,
    };

    const prefix = upwards ? 'up-' : '';
    const transitionProps = {
      className: 'dd-item-ignore',
      transitionEnter: animate,
      transitionLeave: animate,
      transitionName: `grow-from-${prefix}${direction}`,
    };

    return (

        {toggle}
        <CSSTransitionGroup {...transitionProps}>
          {isOpen ?
{children}
 : null}
        </CSSTransitionGroup>

    );
  }
}

module.exports.NestedDropdownMenu = NestedDropdownMenu;
<commit_msg>Create closeOnClickInside and closeOnClickOutside props<commit_after>'use strict'

import React, { Component, PropTypes } from 'react/addons'
import classnames from 'classnames'

const CSSTransitionGroup = React.addons.CSSTransitionGroup;
const TAB = 9;
const SPACEBAR = 32;
const ALIGNMENTS = ['center', 'right', 'left'];
const MENU_SIZES = ['sm', 'md', 'lg', 'xl'];

class DropdownMenu extends Component {
  constructor(props) {
    super(props);

    this._lastWindowClickEvent = null;
  }

  static propTypes = {
    isOpen: PropTypes.bool.isRequired,
    close: PropTypes.func.isRequired,
    toggle: PropTypes.node.isRequired,
    inverse: PropTypes.bool,
    align: PropTypes.oneOf(ALIGNMENTS),
    animAlign: PropTypes.oneOf(ALIGNMENTS),
    textAlign: PropTypes.oneOf(ALIGNMENTS),
    menuAlign: PropTypes.oneOf(ALIGNMENTS),
    className: PropTypes.string,
    size: PropTypes.oneOf(MENU_SIZES),
    upwards: PropTypes.bool,
    animate: PropTypes.bool,
    closeOnInsideClick: PropTypes.bool,
    closeOnOutsideClick: PropTypes.bool
  }

  static defaultProps = {
    inverse: false,
    align: 'center',
    animAlign: null,
    textAlign: null,
    menuAlign: null,
    className: null,
    size: null,
    upwards: false,
    animate: true,
    closeOnInsideClick: true,
    closeOnOutsideClick: true
  }

  componentDidUpdate(prevProps, prevState) {
    const menuItems = React.findDOMNode(this.refs.menuItems);
    if(this.props.isOpen && !prevProps.isOpen) {
      this._lastWindowClickEvent = this.handleClickOutside;
      document.addEventListener('click', this._lastWindowClickEvent);
      if (this.props.closeOnInsideClick) {
        menuItems.addEventListener('click', this.props.close);
      }
      menuItems.addEventListener('onkeydown', this.close);
    } else if(!this.props.isOpen && prevProps.isOpen) {
      document.removeEventListener('click', this._lastWindowClickEvent);
      if (this.props.closeOnOutsideClick) {
        menuItems.removeEventListener('click', this.props.close);
      }
      menuItems.removeEventListener('onkeydown', this.close);

      this._lastWindowClickEvent = null;
    }
  }

  componentWillUnmount() {
    if(this._lastWindowClickEvent) {
      document.removeEventListener('click', this._lastWindowClickEvent);
    }
  }

  close = (e) => {
    const key = e.which || e.keyCode;
    if(key === SPACEBAR) {
      this.props.close();
      e.preventDefault();
    }
  }

  handleClickOutside = (e) => {
    if (this.props.closeOnOutsideClick) {
      const node = React.findDOMNode(this);
      let target = e.target;

      while(target.parentNode) {
        if(target === node) {
          return;
        }

        target = target.parentNode;
      }

      this.props.close(e);
    }
  }

  handleKeyDown = (e) => {
    const key = e.which || e.keyCode;
    if(key !== TAB) {
      return;
    }

    const items = React.findDOMNode(this).querySelectorAll('button,a');
    const id = e.shiftKey ? 1 : items.length - 1;

    if(e.target == items[id]) {
      this.props.close(e);
    }
  }

  render() {
    const { menuAlign, align, inverse, size, className } = this.props;

    const menuClassName = classnames(
      'dd-menu',
      `dd-menu-${menuAlign || align}`,
      { 'dd-menu-inverse': inverse },
      className,
      size ? ('dd-menu-' + size) : null
    );

    const { textAlign, upwards, animAlign, animate } = this.props;

    const listClassName = 'dd-items-' + (textAlign || align);
    const transitionProps = {
      transitionName: 'grow-from-' + (upwards ? 'up-' : '') + (animAlign || align),
      component: 'div',
      className: classnames('dd-menu-items', { 'dd-items-upwards': upwards }),
      onKeyDown: this.handleKeyDown,
      ref: 'menuItems',
      transitionEnter: animate,
      transitionLeave: animate,
    };

    return (

        {this.props.toggle}
        <CSSTransitionGroup {...transitionProps}>
          {this.props.isOpen &&
{this.props.children}
}
        </CSSTransitionGroup>

    );
  }
}

module.exports = DropdownMenu;

class NestedDropdownMenu extends Component {
  constructor(props) {
    super(props);

    this.state = { isOpen: false };
    this._closeCallback = null;
  }

  static propTypes = {
    toggle: PropTypes.node.isRequired,
    nested: PropTypes.oneOf(['inherit', 'reverse', 'left', 'right']),
    animate: PropTypes.bool,
    direction: PropTypes.oneOf(['left', 'right']),
    upwards: PropTypes.bool,
    delay: PropTypes.number,
  }

  static defaultProps = {
    nested: 'reverse',
    animate: false,
    direction: 'right',
    upwards: false,
    delay: 500,
  }

  open = () => {
    if(this._closeCallback) {
      clearTimeout(this._closeCallback);
      this._closeCallback = null;
    }
    this.setState({ isOpen: true });
  }

  close = () => {
    this._closeCallback = setTimeout(_ => {
      this.setState({ isOpen: false });
    }.bind(this), this.props.delay);
  }

  render() {
    const { toggle, children, nested, animate, direction, upwards } = this.props;
    const { isOpen } = this.state;

    const itemProps = {
      className: classnames('nested-dd-menu', `nested-${nested}`),
      onMouseOver: this.open,
      onMouseLeave: this.close,
      onFocus: this.open,
      onBlur: this.close,
    };

    const prefix = upwards ? 'up-' : '';
    const transitionProps = {
      className: 'dd-item-ignore',
      transitionEnter: animate,
      transitionLeave: animate,
      transitionName: `grow-from-${prefix}${direction}`,
    };

    return (

        {toggle}
        <CSSTransitionGroup {...transitionProps}>
          {isOpen ?
{children}
 : null}
        </CSSTransitionGroup>

    );
  }
}

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


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

class HttpsRedirect extends React.Component {

  isLocalHost(hostname) {
    return !!(hostname === 'localhost' ||
              hostname === '[::1]' ||
              hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/));
  }

  render() {
    if (
      typeof window !== 'undefined' &&
      window.location &&
      window.location.protocol === 'http:' &&
      !this.isLocalHost(window.location.hostname)
    ) {
      window.location.href = window.location.href.replace(/^http(?!s)/, 'https');
    }

    return (
      <div>
        { this.props.children }
      </div>
    );
  }
}

HttpsRedirect.propTypes = {
  children: PropTypes.node,
};

export default HttpsRedirect;
<commit_msg>remove wrapping div<commit_after>import React from 'react';
import PropTypes from 'prop-types';

class HttpsRedirect extends React.Component {
  isLocalHost(hostname) {
    return !!(
      hostname === 'localhost' ||
      hostname === '[::1]' ||
      hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
    );
  }

  render() {
    if (
      typeof window !== 'undefined' &&
      window.location &&
      window.location.protocol === 'http:' &&
      !this.isLocalHost(window.location.hostname)
    ) {
      window.location.href = window.location.href.replace(
        /^http(?!s)/,
        'https'
      );
    }

    return this.props.children;
  }
}

HttpsRedirect.propTypes = {
  children: PropTypes.node
};

export default HttpsRedirect;
<|endoftext|>


<commit_before>// Import DC and dependencies

d3 = require("d3");
crossfilter = require("crossfilter");
module.exports = require("./dc");
<commit_msg>Delete index.js<commit_after><|endoftext|>


<commit_before>import { logoBase64, svgLogo } from './sources';

class Github {
  constructor(options, request) {
    this.options = options || {};
    if (!this.options.user && !this.options.org) {
      throw new Error('options must have `user` or `org` param');
    }
    this.request = request;
    this.options.isUser = this.isUser();
    this.options.name = this.options.isUser
      ? this.options.user
      : this.options.org;
  }

  getBase() {
    return {
      name: 'Github',
      home: `'https://github.com/'${this.options.name}`,
      logo: {
        svg: svgLogo,
        base64: logoBase64,
      },
    };
  }

  isUser() {
    return !!this.options.user;
  }

  async getUserProfile() {
    const options = this.options;
    const url = `https://api.github.com/users/${options.name}`;
    const headers = {
      'User-Agent': 'representation-source-github',
    };
    if (options.token && options.token.length) {
      headers.Authorization = `token ${options.token}`;
    }
    return this.request({
      url,
      json: true,
      headers,
    });
  }

  async load() {
    const result = this.getBase();
    const profile = await this.getUserProfile();
    result.stats = [
      {
        title: 'repos',
        count: profile.public_repos,
      },
      {
        title: 'gists',
        count: profile.public_gists,
      },
      {
        title: 'followers',
        count: profile.followers,
      },
    ];
    return result;
  }
}

export default Github;
<commit_msg>fix on github url<commit_after>import { logoBase64, svgLogo } from './sources';

class Github {
  constructor(options, request) {
    this.options = options || {};
    if (!this.options.user && !this.options.org) {
      throw new Error('options must have `user` or `org` param');
    }
    this.request = request;
    this.options.isUser = this.isUser();
    this.options.name = this.options.isUser
      ? this.options.user
      : this.options.org;
  }

  getBase() {
    return {
      name: 'Github',
      home: `https://github.com/${this.options.name}`,
      logo: {
        svg: svgLogo,
        base64: logoBase64,
      },
    };
  }

  isUser() {
    return !!this.options.user;
  }

  async getUserProfile() {
    const options = this.options;
    const url = `https://api.github.com/users/${options.name}`;
    const headers = {
      'User-Agent': 'representation-source-github',
    };
    if (options.token && options.token.length) {
      headers.Authorization = `token ${options.token}`;
    }
    return this.request({
      url,
      json: true,
      headers,
    });
  }

  async load() {
    const result = this.getBase();
    const profile = await this.getUserProfile();
    result.stats = [
      {
        title: 'repos',
        count: profile.public_repos,
      },
      {
        title: 'gists',
        count: profile.public_gists,
      },
      {
        title: 'followers',
        count: profile.followers,
      },
    ];
    return result;
  }
}

export default Github;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import classNames from 'classnames';
import mixin from './mixin';
import InputHandler from './InputHandler';

function noop() {
}

function preventDefault(e) {
  e.preventDefault();
}

const InputNumber = React.createClass({
  propTypes: {
    onChange: PropTypes.func,
    onKeyDown: PropTypes.func,
    prefixCls: PropTypes.string,
    disabled: PropTypes.bool,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    readOnly: PropTypes.bool,
    max: PropTypes.number,
    min: PropTypes.number,
    step: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
    ]),
  },

  mixins: [mixin],

  getDefaultProps() {
    return {
      prefixCls: 'rc-input-number',
    };
  },

  componentDidMount() {
    this.componentDidUpdate();
  },

  componentDidUpdate() {
    if (this.state.focused && document.activeElement !== this.refs.input) {
      this.refs.input.focus();
    }
  },

  onKeyDown(e, ...args) {
    if (e.keyCode === 38) {
      this.up(e);
    } else if (e.keyCode === 40) {
      this.down(e);
    }
    this.props.onKeyDown(e, ...args);
  },

  getValueFromEvent(e) {
    return e.target.value;
  },

  focus() {
    this.refs.input.focus();
  },

  render() {
    const props = { ...this.props };
    const { prefixCls, disabled, readOnly } = props;
    const classes = classNames({
      [prefixCls]: true,
      [props.className]: !!props.className,
      [`${prefixCls}-disabled`]: disabled,
      [`${prefixCls}-focused`]: this.state.focused,
    });
    let upDisabledClass = '';
    let downDisabledClass = '';
    const value = this.state.value;
    if (!isNaN(value)) {
      const val = Number(value);
      if (val >= props.max) {
        upDisabledClass = `${prefixCls}-handler-up-disabled`;
      }
      if (val <= props.min) {
        downDisabledClass = `${prefixCls}-handler-down-disabled`;
      }
    } else {
      upDisabledClass = `${prefixCls}-handler-up-disabled`;
      downDisabledClass = `${prefixCls}-handler-down-disabled`;
    }

    const editable = !props.readOnly && !props.disabled;

    // focus state, show input value
    // unfocus state, show valid value
    let inputDisplayValue;
    if (this.state.focused) {
      inputDisplayValue = this.state.inputValue;
    } else {
      inputDisplayValue = this.state.value;
    }

    if (inputDisplayValue === undefined) {
      inputDisplayValue = '';
    }

    // Remove React warning.
    // Warning: Input elements must be either controlled
    // or uncontrolled (specify either the value prop, or
    // the defaultValue prop, but not both).
    delete props.defaultValue;
    // https://fb.me/react-unknown-prop
    delete props.prefixCls;

    // ref for test
    return (

        <div className={`${prefixCls}-handler-wrap`}>
          <InputHandler
            ref="up"
            disabled={!!upDisabledClass || disabled || readOnly}
            prefixCls={prefixCls}
            unselectable="unselectable"
            onTouchStart={(editable && !upDisabledClass) ? this.up : noop}
            onTouchEnd={this.stop}
            onMouseDown={(editable && !upDisabledClass) ? this.up : noop}
            onMouseUp={this.stop}
            onMouseLeave={this.stop}
            className={`${prefixCls}-handler ${prefixCls}-handler-up ${upDisabledClass}`}
          >
            <span
              unselectable="unselectable"
              className={`${prefixCls}-handler-up-inner`}
              onClick={preventDefault}
            />
          </InputHandler>
          <InputHandler
            ref="down"
            disabled={!!downDisabledClass || disabled || readOnly}
            prefixCls={prefixCls}
            unselectable="unselectable"
            onTouchStart={(editable && !downDisabledClass) ? this.down : noop}
            onTouchEnd={this.stop}
            onMouseDown={(editable && !downDisabledClass) ? this.down : noop}
            onMouseUp={this.stop}
            onMouseLeave={this.stop}
            className={`${prefixCls}-handler ${prefixCls}-handler-down ${downDisabledClass}`}
          >
            <span
              unselectable="unselectable"
              className={`${prefixCls}-handler-down-inner`}
              onClick={preventDefault}
            />
          </InputHandler>

        <div className={`${prefixCls}-input-wrap`}>
          <input
            {...props}
            style={null}
            className={`${prefixCls}-input`}
            autoComplete="off"
            onFocus={this.onFocus}
            onBlur={this.onBlur}
            onKeyDown={this.onKeyDown}
            autoFocus={props.autoFocus}
            readOnly={props.readOnly}
            disabled={props.disabled}
            max={props.max}
            min={props.min}
            name={props.name}
            onChange={this.onChange}
            ref="input"
            value={inputDisplayValue}
          />

    );
  },
});

export default InputNumber;
<commit_msg>fix: should stop inc/dec after key up<commit_after>import React, { PropTypes } from 'react';
import classNames from 'classnames';
import mixin from './mixin';
import InputHandler from './InputHandler';

function noop() {
}

function preventDefault(e) {
  e.preventDefault();
}

const InputNumber = React.createClass({
  propTypes: {
    onChange: PropTypes.func,
    onKeyDown: PropTypes.func,
    prefixCls: PropTypes.string,
    disabled: PropTypes.bool,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    readOnly: PropTypes.bool,
    max: PropTypes.number,
    min: PropTypes.number,
    step: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
    ]),
  },

  mixins: [mixin],

  getDefaultProps() {
    return {
      prefixCls: 'rc-input-number',
    };
  },

  componentDidMount() {
    this.componentDidUpdate();
  },

  componentDidUpdate() {
    if (this.state.focused && document.activeElement !== this.refs.input) {
      this.refs.input.focus();
    }
  },

  onKeyDown(e, ...args) {
    if (e.keyCode === 38) {
      this.up(e);
    } else if (e.keyCode === 40) {
      this.down(e);
    }
    this.props.onKeyDown(e, ...args);
  },

  getValueFromEvent(e) {
    return e.target.value;
  },

  focus() {
    this.refs.input.focus();
  },

  render() {
    const props = { ...this.props };
    const { prefixCls, disabled, readOnly } = props;
    const classes = classNames({
      [prefixCls]: true,
      [props.className]: !!props.className,
      [`${prefixCls}-disabled`]: disabled,
      [`${prefixCls}-focused`]: this.state.focused,
    });
    let upDisabledClass = '';
    let downDisabledClass = '';
    const value = this.state.value;
    if (!isNaN(value)) {
      const val = Number(value);
      if (val >= props.max) {
        upDisabledClass = `${prefixCls}-handler-up-disabled`;
      }
      if (val <= props.min) {
        downDisabledClass = `${prefixCls}-handler-down-disabled`;
      }
    } else {
      upDisabledClass = `${prefixCls}-handler-up-disabled`;
      downDisabledClass = `${prefixCls}-handler-down-disabled`;
    }

    const editable = !props.readOnly && !props.disabled;

    // focus state, show input value
    // unfocus state, show valid value
    let inputDisplayValue;
    if (this.state.focused) {
      inputDisplayValue = this.state.inputValue;
    } else {
      inputDisplayValue = this.state.value;
    }

    if (inputDisplayValue === undefined) {
      inputDisplayValue = '';
    }

    // Remove React warning.
    // Warning: Input elements must be either controlled
    // or uncontrolled (specify either the value prop, or
    // the defaultValue prop, but not both).
    delete props.defaultValue;
    // https://fb.me/react-unknown-prop
    delete props.prefixCls;

    // ref for test
    return (

        <div className={`${prefixCls}-handler-wrap`}>
          <InputHandler
            ref="up"
            disabled={!!upDisabledClass || disabled || readOnly}
            prefixCls={prefixCls}
            unselectable="unselectable"
            onTouchStart={(editable && !upDisabledClass) ? this.up : noop}
            onTouchEnd={this.stop}
            onMouseDown={(editable && !upDisabledClass) ? this.up : noop}
            onMouseUp={this.stop}
            onMouseLeave={this.stop}
            className={`${prefixCls}-handler ${prefixCls}-handler-up ${upDisabledClass}`}
          >
            <span
              unselectable="unselectable"
              className={`${prefixCls}-handler-up-inner`}
              onClick={preventDefault}
            />
          </InputHandler>
          <InputHandler
            ref="down"
            disabled={!!downDisabledClass || disabled || readOnly}
            prefixCls={prefixCls}
            unselectable="unselectable"
            onTouchStart={(editable && !downDisabledClass) ? this.down : noop}
            onTouchEnd={this.stop}
            onMouseDown={(editable && !downDisabledClass) ? this.down : noop}
            onMouseUp={this.stop}
            onMouseLeave={this.stop}
            className={`${prefixCls}-handler ${prefixCls}-handler-down ${downDisabledClass}`}
          >
            <span
              unselectable="unselectable"
              className={`${prefixCls}-handler-down-inner`}
              onClick={preventDefault}
            />
          </InputHandler>

        <div className={`${prefixCls}-input-wrap`}>
          <input
            {...props}
            style={null}
            className={`${prefixCls}-input`}
            autoComplete="off"
            onFocus={this.onFocus}
            onBlur={this.onBlur}
            onKeyDown={this.onKeyDown}
            onKeyUp={this.stop}
            autoFocus={props.autoFocus}
            readOnly={props.readOnly}
            disabled={props.disabled}
            max={props.max}
            min={props.min}
            name={props.name}
            onChange={this.onChange}
            ref="input"
            value={inputDisplayValue}
          />

    );
  },
});

export default InputNumber;
<|endoftext|>


<commit_before>import capitalize from 'capitalize';
import connect from './helpers/connect';
import connectAudioNodes from './helpers/connectAudioNodes';
import createVirtualAudioNode from './helpers/createVirtualAudioNode';
import updateAudioNodeAndVirtualAudioGraph from './helpers/updateAudioNodeAndVirtualAudioGraph';
import disconnect from './helpers/disconnect';

const startTimePath = obj => obj.params && obj.params.startTime;
const stopTimePath = obj => obj.params && obj.params.stopTime;

export default class VirtualAudioGraph {
  constructor ({audioContext = new AudioContext(),
                output = audioContext.destination} = {}) {
    this.audioContext = audioContext;
    this.output = output;
    this.virtualNodes = {};
    this.customNodes = {};
  }

  get currentTime () {
    return this.audioContext.currentTime;
  }

  defineNode (customNodeParamsFactory, name) {
    if (this.audioContext[`create${capitalize(name)}`]) {
      throw new Error(`${name} is a standard audio node name and cannot be overwritten`);
    }

    this.customNodes[name] = customNodeParamsFactory;
    return this;
  }

  getAudioNodeById (id) {
    return this.virtualNodes[id].audioNode;
  }

  update (virtualGraphParams) {
    const virtualGraphParamsKeys = Object.keys(virtualGraphParams);

    Object.keys(this.virtualNodes).forEach(id => {
      if (virtualGraphParamsKeys.indexOf(id) === -1) {
        disconnect(this.virtualNodes[id]);
        delete this.virtualNodes[id];
      }
    });

    virtualGraphParamsKeys
      .forEach(key => {
        if (key === 'output') {
          throw new Error(`'output' is not a valid id`);
        }
        const virtualAudioNodeParams = virtualGraphParams[key];
        const [node, output] = virtualAudioNodeParams;
        if (output == null && node !== 'mediaStreamDestination') {
          throw new Error(`output not specified for node key ${key}`);
        }
        const virtualAudioNode = this.virtualNodes[key];
        if (virtualAudioNode == null) {
          this.virtualNodes[key] = createVirtualAudioNode.call(this, virtualAudioNodeParams);
          return;
        }
        if (startTimePath(virtualAudioNodeParams) !== startTimePath(virtualAudioNode) ||
          stopTimePath(virtualAudioNodeParams) !== stopTimePath(virtualAudioNode)) {
          disconnect(virtualAudioNode);
          delete this.virtualNodes[key];
        }
        updateAudioNodeAndVirtualAudioGraph.call(this, virtualAudioNode, virtualAudioNodeParams, key);
      });

    connectAudioNodes(this.virtualNodes,
                      virtualNode => connect(virtualNode, this.output));

    return this;
  }
}
<commit_msg>fix start and stop time path fns<commit_after>import capitalize from 'capitalize';
import connect from './helpers/connect';
import connectAudioNodes from './helpers/connectAudioNodes';
import createVirtualAudioNode from './helpers/createVirtualAudioNode';
import updateAudioNodeAndVirtualAudioGraph from './helpers/updateAudioNodeAndVirtualAudioGraph';
import disconnect from './helpers/disconnect';

const startTimePath = params => params[2] && params[2].startTime;
const stopTimePath = params => params[2] && params[2].stopTime;

export default class VirtualAudioGraph {
  constructor ({audioContext = new AudioContext(),
                output = audioContext.destination} = {}) {
    this.audioContext = audioContext;
    this.output = output;
    this.virtualNodes = {};
    this.customNodes = {};
  }

  get currentTime () {
    return this.audioContext.currentTime;
  }

  defineNode (customNodeParamsFactory, name) {
    if (this.audioContext[`create${capitalize(name)}`]) {
      throw new Error(`${name} is a standard audio node name and cannot be overwritten`);
    }

    this.customNodes[name] = customNodeParamsFactory;
    return this;
  }

  getAudioNodeById (id) {
    return this.virtualNodes[id].audioNode;
  }

  update (virtualGraphParams) {
    const virtualGraphParamsKeys = Object.keys(virtualGraphParams);

    Object.keys(this.virtualNodes).forEach(id => {
      if (virtualGraphParamsKeys.indexOf(id) === -1) {
        disconnect(this.virtualNodes[id]);
        delete this.virtualNodes[id];
      }
    });

    virtualGraphParamsKeys
      .forEach(key => {
        if (key === 'output') {
          throw new Error(`'output' is not a valid id`);
        }
        const virtualAudioNodeParams = virtualGraphParams[key];
        const [node, output] = virtualAudioNodeParams;
        if (output == null && node !== 'mediaStreamDestination') {
          throw new Error(`output not specified for node key ${key}`);
        }
        const virtualAudioNode = this.virtualNodes[key];
        if (virtualAudioNode == null) {
          this.virtualNodes[key] = createVirtualAudioNode.call(this, virtualAudioNodeParams);
          return;
        }
        if (startTimePath(virtualAudioNodeParams) !== startTimePath(virtualAudioNode) ||
          stopTimePath(virtualAudioNodeParams) !== stopTimePath(virtualAudioNode)) {
          disconnect(virtualAudioNode);
          delete this.virtualNodes[key];
        }
        updateAudioNodeAndVirtualAudioGraph.call(this, virtualAudioNode, virtualAudioNodeParams, key);
      });

    connectAudioNodes(this.virtualNodes,
                      virtualNode => connect(virtualNode, this.output));

    return this;
  }
}
<|endoftext|>


<commit_before>
import Siema from './main'
import SiemaSlide from './siema-slide'

if (typeof window !== 'undefined') {
  window.Siema = Siema
}

export {
  Siema,
  SiemaSlide
}
<commit_msg>add SiemaSlide to window<commit_after>
import Siema from './main'
import SiemaSlide from './siema-slide'

if (typeof window !== 'undefined') {
  window.Siema = Siema
  window.SiemanSlide = SiemaSlide
}

export {
  Siema,
  SiemaSlide
}
<|endoftext|>


<commit_before>const CLIPBOARD_INTERVAL_IN_MILLISECONDS = 500;
const URL_CHARS_LIMIT = 2000;

const { PrefsTarget } = require('sdk/preferences/event-target');
const { setInterval, clearInterval } = require('sdk/timers');
const { viewFor } = require('sdk/view/core');
const clipboard = require('sdk/clipboard');
const newTabUrlJsm = require('resource:///modules/NewTabURL.jsm').NewTabURL;
const preferencesService = require('sdk/preferences/service');
const prefsTarget = PrefsTarget({ branchName: 'browser.startup.'});
const self = require('sdk/self');
const simplePrefs = require('sdk/simple-prefs');
const tabs = require('sdk/tabs');
const tabutils = require('sdk/tabs/utils');
const windows = require('sdk/windows');

const newtaboverride = {
  lastClipboardUrl : false,
  timer : false,

  init : function () {
    newtaboverride.onPrefChange();
  },

  onPrefChange : function () {
    const type = simplePrefs.prefs['type'];
    let newTabUrl;

    switch (type) {
      case 'about:newtab':
        newTabUrl = type;
        break;
      case 'clipboard':
        newTabUrl = 'about:blank';
        // unfortunately there is no "clipboard changed" event…
        newtaboverride.timer = setInterval(newtaboverride.clipboardAction, CLIPBOARD_INTERVAL_IN_MILLISECONDS);
        break;
      case 'homepage':
        newTabUrl = preferencesService.getLocalized('browser.startup.homepage', 'about:blank').split('|')[0];
        break;
      default:
        newTabUrl = 'about:newtab';
    }

    if (type !== 'clipboard') {
      clearInterval(newtaboverride.timer);
      newtaboverride.lastClipboardUrl = false;
    }

    newTabUrlJsm.override(newTabUrl);

    const focus_website = simplePrefs.prefs['focus_website'];
    if (focus_website) {
      tabs.on('open', newtaboverride.focusListener);
    } else {
      tabs.removeListener('open', newtaboverride.focusListener);
    }

    const clear_locationbar = simplePrefs.prefs['clear_locationbar'];
    if (clear_locationbar) {
      tabs.on('open', newtaboverride.clearLocationBarListener);
    } else {
      tabs.removeListener('open', newtaboverride.clearLocationBarListener);
    }
  },

  focusListener: function (tab) {
    let tab_opened = true;
    tab.on('ready', function () {
      if (tab_opened) {
        let xultab = viewFor(tab);
        let browser = tabutils.getBrowserForTab(xultab);
        browser.focus();
        tab_opened = false;
      }
    });
  },

  clearLocationBarListener: function (tab) {
    let tab_opened = true;
    tab.on('ready', function () {
      if (tab_opened) {
        let xultab = viewFor(tab);
        let window = tabutils.getOwnerWindow(xultab);
        window.document.getElementById('urlbar').value = '';
        tab_opened = false;
      }
    });
  },

  clipboardAction : function () {
    const clipboardContent = clipboard.get();

    if (clipboard.currentFlavors.indexOf('text') === -1) {
      return;
    }

    if (clipboardContent.length > URL_CHARS_LIMIT || !newtaboverride.isValidUri(clipboardContent)) {
      return;
    }

    if (!newtaboverride.lastClipboardUrl || clipboardContent !== newtaboverride.lastClipboardUrl) {
      newTabUrlJsm.override(clipboardContent);
      newtaboverride.lastClipboardUrl = clipboardContent;
    }
  },

  /**
   * @see http://stackoverflow.com/a/9284473
   */
  isValidUri : function (string) {
    const website = /^(?:(?:https?):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
    const aboutpage = /^about:(about|accounts|addons|blank|buildconfig|cache|checkerboard|config|crashes|credits|debugging|downloads|healthreport|home|license|logo|memory|mozilla|networking|newtab|performance|plugins|preferences|privatebrowsing|profiles|rights|robots|searchreset|serviceworkers|support|sync-log|telemetry|webrtc)?$/i;

    return website.test(string) || aboutpage.test(string);
  }
};

const main = () => {
  newtaboverride.init();

  simplePrefs.on('', newtaboverride.onPrefChange);
  prefsTarget.on('homepage', newtaboverride.onPrefChange);
};

const unload = (reason) => {
  if (reason === 'uninstall' || reason === 'disable') {
    clearInterval(newtaboverride.timer);
    newtaboverride.lastClipboardUrl = false;
    newTabUrlJsm.reset();
  }
};

exports.main = main;
exports.onUnload = unload;
<commit_msg>removed no longer used line from SDK implementation<commit_after>const CLIPBOARD_INTERVAL_IN_MILLISECONDS = 500;
const URL_CHARS_LIMIT = 2000;

const { PrefsTarget } = require('sdk/preferences/event-target');
const { setInterval, clearInterval } = require('sdk/timers');
const { viewFor } = require('sdk/view/core');
const clipboard = require('sdk/clipboard');
const newTabUrlJsm = require('resource:///modules/NewTabURL.jsm').NewTabURL;
const preferencesService = require('sdk/preferences/service');
const prefsTarget = PrefsTarget({ branchName: 'browser.startup.'});
const simplePrefs = require('sdk/simple-prefs');
const tabs = require('sdk/tabs');
const tabutils = require('sdk/tabs/utils');
const windows = require('sdk/windows');

const newtaboverride = {
  lastClipboardUrl : false,
  timer : false,

  init : function () {
    newtaboverride.onPrefChange();
  },

  onPrefChange : function () {
    const type = simplePrefs.prefs['type'];
    let newTabUrl;

    switch (type) {
      case 'about:newtab':
        newTabUrl = type;
        break;
      case 'clipboard':
        newTabUrl = 'about:blank';
        // unfortunately there is no "clipboard changed" event…
        newtaboverride.timer = setInterval(newtaboverride.clipboardAction, CLIPBOARD_INTERVAL_IN_MILLISECONDS);
        break;
      case 'homepage':
        newTabUrl = preferencesService.getLocalized('browser.startup.homepage', 'about:blank').split('|')[0];
        break;
      default:
        newTabUrl = 'about:newtab';
    }

    if (type !== 'clipboard') {
      clearInterval(newtaboverride.timer);
      newtaboverride.lastClipboardUrl = false;
    }

    newTabUrlJsm.override(newTabUrl);

    const focus_website = simplePrefs.prefs['focus_website'];
    if (focus_website) {
      tabs.on('open', newtaboverride.focusListener);
    } else {
      tabs.removeListener('open', newtaboverride.focusListener);
    }

    const clear_locationbar = simplePrefs.prefs['clear_locationbar'];
    if (clear_locationbar) {
      tabs.on('open', newtaboverride.clearLocationBarListener);
    } else {
      tabs.removeListener('open', newtaboverride.clearLocationBarListener);
    }
  },

  focusListener: function (tab) {
    let tab_opened = true;
    tab.on('ready', function () {
      if (tab_opened) {
        let xultab = viewFor(tab);
        let browser = tabutils.getBrowserForTab(xultab);
        browser.focus();
        tab_opened = false;
      }
    });
  },

  clearLocationBarListener: function (tab) {
    let tab_opened = true;
    tab.on('ready', function () {
      if (tab_opened) {
        let xultab = viewFor(tab);
        let window = tabutils.getOwnerWindow(xultab);
        window.document.getElementById('urlbar').value = '';
        tab_opened = false;
      }
    });
  },

  clipboardAction : function () {
    const clipboardContent = clipboard.get();

    if (clipboard.currentFlavors.indexOf('text') === -1) {
      return;
    }

    if (clipboardContent.length > URL_CHARS_LIMIT || !newtaboverride.isValidUri(clipboardContent)) {
      return;
    }

    if (!newtaboverride.lastClipboardUrl || clipboardContent !== newtaboverride.lastClipboardUrl) {
      newTabUrlJsm.override(clipboardContent);
      newtaboverride.lastClipboardUrl = clipboardContent;
    }
  },

  /**
   * @see http://stackoverflow.com/a/9284473
   */
  isValidUri : function (string) {
    const website = /^(?:(?:https?):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
    const aboutpage = /^about:(about|accounts|addons|blank|buildconfig|cache|checkerboard|config|crashes|credits|debugging|downloads|healthreport|home|license|logo|memory|mozilla|networking|newtab|performance|plugins|preferences|privatebrowsing|profiles|rights|robots|searchreset|serviceworkers|support|sync-log|telemetry|webrtc)?$/i;

    return website.test(string) || aboutpage.test(string);
  }
};

const main = () => {
  newtaboverride.init();

  simplePrefs.on('', newtaboverride.onPrefChange);
  prefsTarget.on('homepage', newtaboverride.onPrefChange);
};

const unload = (reason) => {
  if (reason === 'uninstall' || reason === 'disable') {
    clearInterval(newtaboverride.timer);
    newtaboverride.lastClipboardUrl = false;
    newTabUrlJsm.reset();
  }
};

exports.main = main;
exports.onUnload = unload;
<|endoftext|>


<commit_before>"use strict";

import Server from './server';
import Resource from './Resource';
import Func from './Function';

const server = function(db, prefix) {
  return new Server(db, prefix);
};

server.Resource = function(name, model) {
  return new Resource(name, model);
};

server.Function = function() {
  return new Func();
};

export default server;
<commit_msg>export express.<commit_after>"use strict";

import express from 'express';
import Server from './server';
import Resource from './Resource';
import Func from './Function';

const server = function(db, prefix) {
  return new Server(db, prefix);
};

server.Resource = function(name, model) {
  return new Resource(name, model);
};

server.Function = function() {
  return new Func();
};

server._express = express;

export default server;
<|endoftext|>


<commit_before>var sys = require('sys')
  , lib = require('./lib.js')
  ;

function is_int(val) {
  return (!isNaN(val)) && (parseFloat(val) === parseInt(val));
}

/* XXX This used to be used however now objects are used to create special types. Keeping for posterity.
// Return the "meat" of a regex, or null if it is not a regex.
function regex_of(val) {
  return lib.typeOf(val) === 'regexp' ? val.toString().slice(1, -1) : null;
}
*/

// Use object creation because I don't like object literal syntax to place functions in a namespace.
var Encoder = function() {
  var self = this;

  this.encode = function(term) {
    var encoder = this[lib.typeOf(term)];
    if(!encoder)
      throw new Error("Do not know how to encode " + lib.typeOf(term) + ': ' + sys.inspect(term));
    return encoder.apply(self, [term]);
  }

  this.number = function(x) {
    return is_int(x) ? this.int(x) : this.float(x);
  }

  this.int = function(x) {
    if(x >= 0 && x < 256)
      return [lib.tags.SMALL_INTEGER, x];
    else if(lib.MIN_INTEGER <= x && x <= lib.MAX_INTEGER)
      return [lib.tags.INTEGER, lib.uint32(x)];
    else
      throw new Error('Unknown integer: ' + x);
  }

  this.array = function(x) {
    // Simple array encoding, without worrying about tagging.
    var result = []
      , encoded = [];

    for(var a = 0; a < x.length; a++) {
      var val = x[a];
      if(!val)
        // TODO: Warning: new Error("Bad array: " + sys.inspect(x));
        continue;
      encoded.push(self.encode(val));
    }

    if(encoded.length) {
      result.push( lib.tags.LIST
                 , lib.uint32(encoded.length)
                 , encoded );
    }

    result.push(lib.tags.NIL);
    return result;
  }

  this.object = function(x) {
    if(Object.keys(x).length !== 1)
      throw new Error("Don't know how to process: " + sys.inspect(x));

    var tag = Object.keys(x)[0]
    var val = x[tag];
    var valType = lib.typeOf(val);

    if((tag === 'binary' || tag === 'b') && valType === 'string')
      // Encode the given string as a binary.
      return self.encode(new Buffer(val, 'utf8'));

    if((tag === 'atom' || tag === 'a') && valType === 'string')
      // Encode the string as an atom.
      return self.atom(val);

    if((tag === 'tuple' || tag === 't') && valType === 'array')
      // Encode the array as a tuple.
      return self.tuple(val);

    throw new Error("Unknown tag " + tag.toString() + " for value: " + sys.inspect(val));
  }

  this.atom = function(x) {
    var bytes = new Buffer(x, 'utf8');
    var result = [ lib.tags.ATOM
                 , lib.uint16(bytes.length) ];
    for(var a = 0; a < bytes.length; a++)
      result.push(bytes[a]);
    return result;
  }

  this.tuple = function(x) {
    var result = [];
    if(x.length < 256)
      result.push(lib.tags.SMALL_TUPLE, x.length);
    else
      result.push(lib.tags.LARGE_TUPLE, lib.uint32(x.length));

    result.push(x.map(function(e) { return self.encode(e) }));
    return result;
  }

  this.buffer = function(x) {
    var result = [lib.tags.BINARY];
    result.push(lib.uint32(x.length));
    for(var a = 0; a < x.length; a++)
      result.push(x[a]);
    return result;
  }

  this.string = function(x) {
    var result = [];
    result.push(lib.tags.STRING);

    var bytes = new Buffer(x, 'utf8');
    if(bytes.length != x.length) {
      // TODO: Some kind of warning that this should probably be a binary since it is not only low-ASCII.
    }

    result.push(lib.uint16(bytes.length));
    for(var a = 0; a < bytes.length; a++)
      result.push(bytes[a]);

    return result;
  }

  this.boolean = function(x) {
    return self.atom(x ? "true" : "false");
  }
}

var encoder = new Encoder;

exports.term_to_binary = function(term) {
  var bytes = [lib.VERSION_MAGIC, encoder.encode(term)];
  //console.log('bytes: %j', bytes);
  return new Buffer(lib.flatten(bytes));
}

// Provide convenience to convert to Erlang opt lists: [{verbose, true}, quiet, etc]
// Array elements must be either:
// 1. String, from 1 to 255 characters of only lower-case alphanumerics -> atom
// 2. A 2-array, first element are strings like #1. If the second element is
//    a string like #1, it is converted, otherwise left alone -> {two, tuple}
//
// Booleans are converted to tuples too.
exports.optlist_to_term = optlist_to_term = function(opts) {
  var args = Array.prototype.slice.apply(arguments);
  if(args.length > 1)
    return optlist_to_term(args);

  if(typeOf(opts) !== 'array')
    throw new Error("Cannot convert to OptList: " + sys.inspect(opts));

  var looks_like_atom = /^[a-z][a-zA-Z0-9@\._]{0,254}$/;

  function to_atom(el, opts) {
    var type = typeOf(el);

    if(type === 'boolean')
      return el;

    if(type === 'string') {
      if(looks_like_atom.test(el))
        return {'atom': el};
      else if(opts && opts.identity)
        return el;
      throw new Error("Invalid atom: " + el);
    }

    if(opts && opts.identity)
      return el;

    throw new Error("Cannot convert to atom: " + sys.inspect(el));
  }

  function to_2_tuple(el) {
    return {'tuple': [ to_atom(el[0])
                     , to_atom(el[1], {identity:true}) ] };
  }

  function element_to_opt(el) {
    var type = typeOf(el);
    if(type === 'string' || type === 'boolean') {
      return to_atom(el);
    } else if(type === 'array' && el.length === 2) {
      return to_2_tuple(el);
    } else if(type === 'object' && Object.keys(el).length === 1) {
      var key = Object.keys(el)[0];
      return to_2_tuple([key, el[key]]);
    } else {
      throw new Error("Invalid optlist element: " + sys.inspect(el));
    }
  }

  return opts.map(function(el) { return element_to_opt(el) });
}

exports.optlist_to_binary = function() {
  return exports.term_to_binary(exports.optlist_to_term.apply(this, arguments));
}
<commit_msg>Update to the util module name<commit_after>var sys = require('util')
  , lib = require('./lib.js')
  ;

function is_int(val) {
  return (!isNaN(val)) && (parseFloat(val) === parseInt(val));
}

/* XXX This used to be used however now objects are used to create special types. Keeping for posterity.
// Return the "meat" of a regex, or null if it is not a regex.
function regex_of(val) {
  return lib.typeOf(val) === 'regexp' ? val.toString().slice(1, -1) : null;
}
*/

// Use object creation because I don't like object literal syntax to place functions in a namespace.
var Encoder = function() {
  var self = this;

  this.encode = function(term) {
    var encoder = this[lib.typeOf(term)];
    if(!encoder)
      throw new Error("Do not know how to encode " + lib.typeOf(term) + ': ' + sys.inspect(term));
    return encoder.apply(self, [term]);
  }

  this.number = function(x) {
    return is_int(x) ? this.int(x) : this.float(x);
  }

  this.int = function(x) {
    if(x >= 0 && x < 256)
      return [lib.tags.SMALL_INTEGER, x];
    else if(lib.MIN_INTEGER <= x && x <= lib.MAX_INTEGER)
      return [lib.tags.INTEGER, lib.uint32(x)];
    else
      throw new Error('Unknown integer: ' + x);
  }

  this.array = function(x) {
    // Simple array encoding, without worrying about tagging.
    var result = []
      , encoded = [];

    for(var a = 0; a < x.length; a++) {
      var val = x[a];
      if(!val)
        // TODO: Warning: new Error("Bad array: " + sys.inspect(x));
        continue;
      encoded.push(self.encode(val));
    }

    if(encoded.length) {
      result.push( lib.tags.LIST
                 , lib.uint32(encoded.length)
                 , encoded );
    }

    result.push(lib.tags.NIL);
    return result;
  }

  this.object = function(x) {
    if(Object.keys(x).length !== 1)
      throw new Error("Don't know how to process: " + sys.inspect(x));

    var tag = Object.keys(x)[0]
    var val = x[tag];
    var valType = lib.typeOf(val);

    if((tag === 'binary' || tag === 'b') && valType === 'string')
      // Encode the given string as a binary.
      return self.encode(new Buffer(val, 'utf8'));

    if((tag === 'atom' || tag === 'a') && valType === 'string')
      // Encode the string as an atom.
      return self.atom(val);

    if((tag === 'tuple' || tag === 't') && valType === 'array')
      // Encode the array as a tuple.
      return self.tuple(val);

    throw new Error("Unknown tag " + tag.toString() + " for value: " + sys.inspect(val));
  }

  this.atom = function(x) {
    var bytes = new Buffer(x, 'utf8');
    var result = [ lib.tags.ATOM
                 , lib.uint16(bytes.length) ];
    for(var a = 0; a < bytes.length; a++)
      result.push(bytes[a]);
    return result;
  }

  this.tuple = function(x) {
    var result = [];
    if(x.length < 256)
      result.push(lib.tags.SMALL_TUPLE, x.length);
    else
      result.push(lib.tags.LARGE_TUPLE, lib.uint32(x.length));

    result.push(x.map(function(e) { return self.encode(e) }));
    return result;
  }

  this.buffer = function(x) {
    var result = [lib.tags.BINARY];
    result.push(lib.uint32(x.length));
    for(var a = 0; a < x.length; a++)
      result.push(x[a]);
    return result;
  }

  this.string = function(x) {
    var result = [];
    result.push(lib.tags.STRING);

    var bytes = new Buffer(x, 'utf8');
    if(bytes.length != x.length) {
      // TODO: Some kind of warning that this should probably be a binary since it is not only low-ASCII.
    }

    result.push(lib.uint16(bytes.length));
    for(var a = 0; a < bytes.length; a++)
      result.push(bytes[a]);

    return result;
  }

  this.boolean = function(x) {
    return self.atom(x ? "true" : "false");
  }
}

var encoder = new Encoder;

exports.term_to_binary = function(term) {
  var bytes = [lib.VERSION_MAGIC, encoder.encode(term)];
  //console.log('bytes: %j', bytes);
  return new Buffer(lib.flatten(bytes));
}

// Provide convenience to convert to Erlang opt lists: [{verbose, true}, quiet, etc]
// Array elements must be either:
// 1. String, from 1 to 255 characters of only lower-case alphanumerics -> atom
// 2. A 2-array, first element are strings like #1. If the second element is
//    a string like #1, it is converted, otherwise left alone -> {two, tuple}
//
// Booleans are converted to tuples too.
exports.optlist_to_term = optlist_to_term = function(opts) {
  var args = Array.prototype.slice.apply(arguments);
  if(args.length > 1)
    return optlist_to_term(args);

  if(typeOf(opts) !== 'array')
    throw new Error("Cannot convert to OptList: " + sys.inspect(opts));

  var looks_like_atom = /^[a-z][a-zA-Z0-9@\._]{0,254}$/;

  function to_atom(el, opts) {
    var type = typeOf(el);

    if(type === 'boolean')
      return el;

    if(type === 'string') {
      if(looks_like_atom.test(el))
        return {'atom': el};
      else if(opts && opts.identity)
        return el;
      throw new Error("Invalid atom: " + el);
    }

    if(opts && opts.identity)
      return el;

    throw new Error("Cannot convert to atom: " + sys.inspect(el));
  }

  function to_2_tuple(el) {
    return {'tuple': [ to_atom(el[0])
                     , to_atom(el[1], {identity:true}) ] };
  }

  function element_to_opt(el) {
    var type = typeOf(el);
    if(type === 'string' || type === 'boolean') {
      return to_atom(el);
    } else if(type === 'array' && el.length === 2) {
      return to_2_tuple(el);
    } else if(type === 'object' && Object.keys(el).length === 1) {
      var key = Object.keys(el)[0];
      return to_2_tuple([key, el[key]]);
    } else {
      throw new Error("Invalid optlist element: " + sys.inspect(el));
    }
  }

  return opts.map(function(el) { return element_to_opt(el) });
}

exports.optlist_to_binary = function() {
  return exports.term_to_binary(exports.optlist_to_term.apply(this, arguments));
}
<|endoftext|>


<commit_before>const AWS = require('aws-sdk');
const uid2 = require('uid2');
const SqsConsumer = require('sqs-consumer');
const findOrCreateQueue = require('./findOrCreateQueue')

function SQSTransportServer(config, sqs) {
  let consumer;

  let _SQSTransportServer = function(fn) {
    this.fn = fn;
  };

  _SQSTransportServer.prototype.listen = function(done) {
    let that = this;
    findOrCreateQueue(sqs, config.queueName, function(err, queueUrl) {
      consumer = SqsConsumer.create({
        queueUrl: queueUrl,
        handleMessage: function (message, done) {
          let response = JSON.parse(message.Body)
          let { id, name, data } = response
          that.fn(name, data, done)
        }
      });

      consumer.on('error', function (err) {
        console.log(err.message);
      });

      consumer.start();
      done();
    })
  };

  _SQSTransportServer.prototype.stop = function(done) {
    consumer.stop();
    done();
  };

  return _SQSTransportServer;

}

function SQSTransportClient(config, queue) {

  function _SQSTransportClient() {
    this.fns = {};
  };

  _SQSTransportClient.prototype.connect = function(done) {
    findOrCreateQueue(queue, config.queueName, function (err, queueUrl) {
      config.queueUrl = queueUrl;
      done(err)
    });
  }

  _SQSTransportClient.prototype.disconnect = function(done) {
    done();
  };

  _SQSTransportClient.prototype.call = function(name, data, callback) {
    let id = uid2(10);

    let request = JSON.stringify({
      name,
      data,
      id
    });

    let params = {
      MessageBody: request,
      QueueUrl: config.queueUrl
    };

    queue.sendMessage(params, function(err, response) {
      return callback(err, data)
    });
  }

  return _SQSTransportClient;

}

function SQSTransport(config) {
  AWS.config.update({region: config.region});

  if (config.accessKeyId && config.secretAccessKey) {
    AWS.config.update({accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey});
  }

  let queue = new AWS.SQS();

  this.Server = SQSTransportServer(config, queue);
  this.Client = new SQSTransportClient(config, queue);
}

export default SQSTransport;
<commit_msg>Make SQS Consumer use SQS config<commit_after>const AWS = require('aws-sdk');
const uid2 = require('uid2');
const SqsConsumer = require('sqs-consumer');
const findOrCreateQueue = require('./findOrCreateQueue')

function SQSTransportServer(config, sqs) {
  let consumer;

  let _SQSTransportServer = function(fn) {
    this.fn = fn;
  };

  _SQSTransportServer.prototype.listen = function(done) {
    let that = this;
    findOrCreateQueue(sqs, config.queueName, function(err, queueUrl) {
      consumer = SqsConsumer.create({
        sqs: sqs,
        queueUrl: queueUrl,
        handleMessage: function (message, done) {
          let response = JSON.parse(message.Body)
          let { id, name, data } = response
          that.fn(name, data, done)
        }
      });

      consumer.on('error', function (err) {
        console.log(err.message);
      });

      consumer.start();
      done();
    })
  };

  _SQSTransportServer.prototype.stop = function(done) {
    consumer.stop();
    done();
  };

  return _SQSTransportServer;

}

function SQSTransportClient(config, queue) {

  function _SQSTransportClient() {
    this.fns = {};
  };

  _SQSTransportClient.prototype.connect = function(done) {
    findOrCreateQueue(queue, config.queueName, function (err, queueUrl) {
      config.queueUrl = queueUrl;
      done(err)
    });
  }

  _SQSTransportClient.prototype.disconnect = function(done) {
    done();
  };

  _SQSTransportClient.prototype.call = function(name, data, callback) {
    let id = uid2(10);

    let request = JSON.stringify({
      name,
      data,
      id
    });

    let params = {
      MessageBody: request,
      QueueUrl: config.queueUrl
    };

    queue.sendMessage(params, function(err, response) {
      return callback(err, data)
    });
  }

  return _SQSTransportClient;

}

function SQSTransport(config) {
  AWS.config.update({region: config.region});

  if (config.accessKeyId && config.secretAccessKey) {
    AWS.config.update({accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey});
  }

  let queue = new AWS.SQS();

  this.Server = SQSTransportServer(config, queue);
  this.Client = new SQSTransportClient(config, queue);
}

export default SQSTransport;
<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign, no-shadow */

const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const Raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, captureUncaught = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = Raven.config(...args);
    if (captureUncaught) {
      this._client.install();
    }
  }
  _write(data, encoding, cb) {
    // Normalize event tags - if its a string then wrap in an array, default to an empty array
    let { tags = [] } = data;
    tags = (typeof tags === 'string') ? [tags] : tags;

    const additionalData = {
      level: ((tags = []) => {
        if (hoek.contain(tags, ['fatal'], { part: true })) {
          return 'fatal';
        } else if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(tags),
      tags: tags.filter(
        (tag) => ['fatal', 'error', 'warning', 'info', 'debug'].includes(tag) === false,
      ).reduce((acc, curr) => {
        acc[curr] = true;
        return acc;
      }, {}),
      extra: {
        event: data.event,
      },
    };

    this._client.captureMessage(data.data, additionalData, () => cb());
  }
}

module.exports = GoodSentry;
<commit_msg>fix: node v4 compat<commit_after>/* eslint-disable no-param-reassign, no-shadow */

const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const Raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, captureUncaught = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = Raven.config(...args);
    if (captureUncaught) {
      this._client.install();
    }
  }
  _write(data, encoding, cb) {
    // Normalize event tags - if its a string then wrap in an array, default to an empty array
    let { tags = [] } = data;
    tags = (typeof tags === 'string') ? [tags] : tags;

    const additionalData = {
      level: ((tags = []) => {
        if (hoek.contain(tags, ['fatal'], { part: true })) {
          return 'fatal';
        } else if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(tags),
      tags: tags.filter(
        (tag) => ['fatal', 'error', 'warning', 'info', 'debug'].indexOf(tag) === -1,
      ).reduce((acc, curr) => {
        acc[curr] = true;
        return acc;
      }, {}),
      extra: {
        event: data.event,
      },
    };

    this._client.captureMessage(data.data, additionalData, () => cb());
  }
}

module.exports = GoodSentry;
<|endoftext|>


<commit_before>const chalk = require('chalk');
const argv = require('minimist')(process.argv.slice(2));

var conf = {};
conf.APP_NAME = 'depot';

const logger = require('./logger')(conf);
var commands = require('./commands');

function printUsage(message) {
  if (message) {
    console.error(chalk.red(conf.APP_NAME) + ':', message);
  }

  console.log('Usage: ' + conf.APP_NAME + ' <command>');
  console.log('Where <command> is one of: ');

  // List command names
  var command;
  for (var commandName in commands) {
    command = commands[commandName];
    console.log('  ' + chalk.yellow(commandName) + ' - ' + command.summary);
  }

  console.log();
  console.log(conf.APP_NAME + ' help <term>\tsearch for help on <term>')
}

// Display help message when not enough info given
var commandNameParam = argv._[0];
var isHelp = commandNameParam === 'help';
var subcommandNameParam = isHelp ? argv._[1] : null;
if ((argv._.length < 1) || (isHelp && !subcommandNameParam)) {
  printUsage();
  process.exit(1);
}

// Help command given with parameter
if (isHelp) {
  var helpCommand = commands[subcommandNameParam];
  if (!helpCommand) {
    printUsage('command not found: ' + subcommandNameParam);
    process.exit(2);
  }
  console.log(chalk.yellow(subcommandNameParam) + ' - ' + helpCommand.summary);
  if (helpCommand.params && helpCommand.params.length) {
    console.log('Parameters:');
    helpCommand.params.forEach(function(param) {
      console.log('  * ' + param.name + ' - ' + param.description);
    });
  }
  if (helpCommand.description) {
    console.log(helpCommand.description);
  }
// Normal command given
} else {
  // Invalid command given
  var runCommand = commands[commandNameParam];
  if (!isHelp && !runCommand) {
    printUsage('command not found: ' + commandNameParam);
    process.exit(2);
  }

  var commandObj = runCommand.create({
    config: conf,
    logger: logger
  });
  commandObj.run();
}
<commit_msg>Passing arguments to command<commit_after>const chalk = require('chalk');
const argv = require('minimist')(process.argv.slice(2));

var conf = {};
conf.APP_NAME = 'depot';

const logger = require('./logger')(conf);
var commands = require('./commands');

function printUsage(message) {
  if (message) {
    console.error(chalk.red(conf.APP_NAME) + ':', message);
  }

  console.log('Usage: ' + conf.APP_NAME + ' <command>');
  console.log('Where <command> is one of: ');

  // List command names
  var command;
  for (var commandName in commands) {
    command = commands[commandName];
    console.log('  ' + chalk.yellow(commandName) + ' - ' + command.summary);
  }

  console.log();
  console.log(conf.APP_NAME + ' help <term>\tsearch for help on <term>')
}

// Display help message when not enough info given
var commandNameParam = argv._[0];
var isHelp = commandNameParam === 'help';
var subcommandNameParam = isHelp ? argv._[1] : null;
if ((argv._.length < 1) || (isHelp && !subcommandNameParam)) {
  printUsage();
  process.exit(1);
}

// Help command given with parameter
if (isHelp) {
  var helpCommand = commands[subcommandNameParam];
  if (!helpCommand) {
    printUsage('command not found: ' + subcommandNameParam);
    process.exit(2);
  }
  console.log(chalk.yellow(subcommandNameParam) + ' - ' + helpCommand.summary);
  if (helpCommand.params && helpCommand.params.length) {
    console.log('Parameters:');
    helpCommand.params.forEach(function(param) {
      console.log('  * ' + param.name + ' - ' + param.description);
    });
  }
  if (helpCommand.description) {
    console.log(helpCommand.description);
  }
// Normal command given
} else {
  // Invalid command given
  var runCommand = commands[commandNameParam];
  if (!isHelp && !runCommand) {
    printUsage('command not found: ' + commandNameParam);
    process.exit(2);
  }

  var commandObj = runCommand.create({
    config: conf,
    logger: logger,
    params: argv
  });
  commandObj.run();
}
<|endoftext|>


<commit_before>/* global document */
import React from 'react'
import PropTypes from 'prop-types'

const defaultProps = {
  preventDefaultTouchmoveEvent: false,
  delta: 10,
  rotationAngle: 0,
  trackMouse: false,
  trackTouch: true
}
const initialState = {
  xy: [0, 0],
  swiping: false,
  lastEventData: undefined,
  start: undefined
}
export const LEFT = 'Left'
export const RIGHT = 'Right'
export const UP = 'Up'
export const DOWN = 'Down'
const touchStart = 'touchstart'
const touchMove = 'touchmove'
const touchEnd = 'touchend'
const mouseMove = 'mousemove'
const mouseUp = 'mouseup'

function getDirection(absX, absY, deltaX, deltaY) {
  if (absX > absY) {
    if (deltaX > 0) {
      return LEFT
    }
    return RIGHT
  } else if (deltaY > 0) {
    return UP
  }
  return DOWN
}

function rotateXYByAngle(pos, angle) {
  if (angle === 0) return pos
  const angleInRadians = (Math.PI / 180) * angle
  const x = pos[0] * Math.cos(angleInRadians) + pos[1] * Math.sin(angleInRadians)
  const y = pos[1] * Math.cos(angleInRadians) - pos[0] * Math.sin(angleInRadians)
  return [x, y]
}

function getHandlers(set, trackMouse) {
  const onStart = event => {
    // if more than a single touch don't track, for now...
    if (event.touches && event.touches.length > 1) return

    set.current((state, props) => {
      // setup mouse listeners on document to track swipe since swipe can leave container
      if (props.trackMouse) {
        document.addEventListener(mouseMove, onMove)
        document.addEventListener(mouseUp, onUp)
      }
      const { clientX, clientY } = event.touches ? event.touches[0] : event
      const xy = rotateXYByAngle([clientX, clientY], props.rotationAngle)
      return { ...state, ...initialState, xy, start: event.timeStamp || 0 }
    })
  }

  const onMove = event => {
    set.current((state, props) => {
      if (!state.xy[0] || !state.xy[1] || (event.touches && event.touches.length > 1)) {
        return state
      }
      const { clientX, clientY } = event.touches ? event.touches[0] : event
      const [x, y] = rotateXYByAngle([clientX, clientY], props.rotationAngle)
      const deltaX = state.xy[0] - x
      const deltaY = state.xy[1] - y
      const absX = Math.abs(deltaX)
      const absY = Math.abs(deltaY)
      const time = (event.timeStamp || 0) - state.start
      const velocity = Math.sqrt(absX * absX + absY * absY) / (time || 1)

      // if swipe is under delta and we have not started to track a swipe: skip update
      if (absX < props.delta && absY < props.delta && !state.swiping) return state

      const dir = getDirection(absX, absY, deltaX, deltaY)
      const eventData = { event, absX, absY, deltaX, deltaY, velocity, dir }

      props.onSwiping && props.onSwiping(eventData)

      // track if a swipe is cancelable(handler for swiping or swiped(dir) exists)
      // so we can call preventDefault if needed
      let cancelablePageSwipe = false
      if (props.onSwiping || props.onSwiped || props[`onSwiped${dir}`]) {
        cancelablePageSwipe = true
      }

      if (cancelablePageSwipe && props.preventDefaultTouchmoveEvent && props.trackTouch)
        event.preventDefault()

      return { ...state, lastEventData: eventData, swiping: true }
    })
  }

  const onEnd = event => {
    set.current((state, props) => {
      if (state.swiping) {
        const eventData = { ...state.lastEventData, event }

        props.onSwiped && props.onSwiped(eventData)

        props[`onSwiped${eventData.dir}`] && props[`onSwiped${eventData.dir}`](eventData)
      }
      return { ...state, ...initialState }
    })
  }

  const cleanUpMouse = () => {
    // safe to just call removeEventListener
    document.removeEventListener(mouseMove, onMove)
    document.removeEventListener(mouseUp, onUp)
  }

  const onUp = e => {
    cleanUpMouse()
    onEnd(e)
  }

  const attachTouch = el => {
    if (el && el.addEventListener) {
      // attach touch event listeners and handlers
      const tls = [[touchStart, onStart], [touchMove, onMove], [touchEnd, onEnd]]
      tls.forEach(([e, h]) => el.addEventListener(e, h))
      // return properly scoped cleanup method for removing listeners
      return () => tls.forEach(([e, h]) => el.removeEventListener(e, h))
    }
  }

  const onRef = el => {
    // "inline" ref functions are called twice on render, once with null then again with DOM element
    // ignore null here
    if (el === null) return
    set.current((state, props) => {
      // if the same DOM el as previous just return state
      if (state.el === el) return state

      let addState = {}
      // if new DOM el clean up old DOM and reset cleanUpTouch
      if (state.el && state.el !== el && state.cleanUpTouch) {
        state.cleanUpTouch()
        addState.cleanUpTouch = null
      }
      // only attach if we want to track touch
      if (props.trackTouch && el) {
        addState.cleanUpTouch = attachTouch(el)
      }

      // store event attached DOM el for comparison, clean up, and re-attachment
      return { ...state, el, ...addState }
    })
  }

  // update state, and handlers
  set.current((state, props) => {
    let addState = {}
    // clean up touch handlers if no longer tracking touches
    if (!props.trackTouch && state.cleanUpTouch) {
      state.cleanUpTouch()
      addState.cleanUpTouch = null
    } else if (props.trackTouch && !state.cleanUpTouch) {
      // attach/re-attach touch handlers
      if (state.el) {
        addState.cleanUpTouch = attachTouch(state.el)
      }
    }
    return { ...state, ...addState }
  })

  // set ref callback to attach touch event listeners
  const output = { ref: onRef }

  // if track mouse attach mouse down listener
  if (trackMouse) {
    output.onMouseDown = onStart
  }

  return output
}

export function useSwipeable(props) {
  const transientState = React.useRef({ ...initialState, type: 'hook' })
  const set = React.useRef()
  set.current = cb =>
    (transientState.current = cb(transientState.current, { ...defaultProps, ...props }))
  return getHandlers(set, props.trackMouse)
}

export class Swipeable extends React.PureComponent {
  static propTypes = {
    onSwiped: PropTypes.func,
    onSwiping: PropTypes.func,
    onSwipedUp: PropTypes.func,
    onSwipedRight: PropTypes.func,
    onSwipedDown: PropTypes.func,
    onSwipedLeft: PropTypes.func,
    delta: PropTypes.number,
    preventDefaultTouchmoveEvent: PropTypes.bool,
    nodeName: PropTypes.string,
    trackMouse: PropTypes.bool,
    trackTouch: PropTypes.bool,
    innerRef: PropTypes.func,
    rotationAngle: PropTypes.number
  }

  static defaultProps = defaultProps

  constructor(props) {
    super(props)
    this._state = { ...initialState, type: 'class' }
    this._set = { current: this._current }
  }

  _current = cb => {
    this._state = cb(this._state, this.props)
  }

  render() {
    const { className, style, nodeName = 'div', innerRef, children, trackMouse } = this.props
    const handlers = getHandlers(this._set, trackMouse)
    const ref = innerRef ? el => (innerRef(el), handlers.ref(el)) : handlers.ref
    return React.createElement(nodeName, { ...handlers, className, style, ref }, children)
  }
}
<commit_msg>use handlerProps for getHandlers<commit_after>/* global document */
import React from 'react'
import PropTypes from 'prop-types'

const defaultProps = {
  preventDefaultTouchmoveEvent: false,
  delta: 10,
  rotationAngle: 0,
  trackMouse: false,
  trackTouch: true
}
const initialState = {
  xy: [0, 0],
  swiping: false,
  lastEventData: undefined,
  start: undefined
}
export const LEFT = 'Left'
export const RIGHT = 'Right'
export const UP = 'Up'
export const DOWN = 'Down'
const touchStart = 'touchstart'
const touchMove = 'touchmove'
const touchEnd = 'touchend'
const mouseMove = 'mousemove'
const mouseUp = 'mouseup'

function getDirection(absX, absY, deltaX, deltaY) {
  if (absX > absY) {
    if (deltaX > 0) {
      return LEFT
    }
    return RIGHT
  } else if (deltaY > 0) {
    return UP
  }
  return DOWN
}

function rotateXYByAngle(pos, angle) {
  if (angle === 0) return pos
  const angleInRadians = (Math.PI / 180) * angle
  const x = pos[0] * Math.cos(angleInRadians) + pos[1] * Math.sin(angleInRadians)
  const y = pos[1] * Math.cos(angleInRadians) - pos[0] * Math.sin(angleInRadians)
  return [x, y]
}

function getHandlers(set, handlerProps) {
  const onStart = event => {
    // if more than a single touch don't track, for now...
    if (event.touches && event.touches.length > 1) return

    set.current((state, props) => {
      // setup mouse listeners on document to track swipe since swipe can leave container
      if (props.trackMouse) {
        document.addEventListener(mouseMove, onMove)
        document.addEventListener(mouseUp, onUp)
      }
      const { clientX, clientY } = event.touches ? event.touches[0] : event
      const xy = rotateXYByAngle([clientX, clientY], props.rotationAngle)
      return { ...state, ...initialState, xy, start: event.timeStamp || 0 }
    })
  }

  const onMove = event => {
    set.current((state, props) => {
      if (!state.xy[0] || !state.xy[1] || (event.touches && event.touches.length > 1)) {
        return state
      }
      const { clientX, clientY } = event.touches ? event.touches[0] : event
      const [x, y] = rotateXYByAngle([clientX, clientY], props.rotationAngle)
      const deltaX = state.xy[0] - x
      const deltaY = state.xy[1] - y
      const absX = Math.abs(deltaX)
      const absY = Math.abs(deltaY)
      const time = (event.timeStamp || 0) - state.start
      const velocity = Math.sqrt(absX * absX + absY * absY) / (time || 1)

      // if swipe is under delta and we have not started to track a swipe: skip update
      if (absX < props.delta && absY < props.delta && !state.swiping) return state

      const dir = getDirection(absX, absY, deltaX, deltaY)
      const eventData = { event, absX, absY, deltaX, deltaY, velocity, dir }

      props.onSwiping && props.onSwiping(eventData)

      // track if a swipe is cancelable(handler for swiping or swiped(dir) exists)
      // so we can call preventDefault if needed
      let cancelablePageSwipe = false
      if (props.onSwiping || props.onSwiped || props[`onSwiped${dir}`]) {
        cancelablePageSwipe = true
      }

      if (cancelablePageSwipe && props.preventDefaultTouchmoveEvent && props.trackTouch)
        event.preventDefault()

      return { ...state, lastEventData: eventData, swiping: true }
    })
  }

  const onEnd = event => {
    set.current((state, props) => {
      if (state.swiping) {
        const eventData = { ...state.lastEventData, event }

        props.onSwiped && props.onSwiped(eventData)

        props[`onSwiped${eventData.dir}`] && props[`onSwiped${eventData.dir}`](eventData)
      }
      return { ...state, ...initialState }
    })
  }

  const cleanUpMouse = () => {
    // safe to just call removeEventListener
    document.removeEventListener(mouseMove, onMove)
    document.removeEventListener(mouseUp, onUp)
  }

  const onUp = e => {
    cleanUpMouse()
    onEnd(e)
  }

  const attachTouch = el => {
    if (el && el.addEventListener) {
      // attach touch event listeners and handlers
      const tls = [[touchStart, onStart], [touchMove, onMove], [touchEnd, onEnd]]
      tls.forEach(([e, h]) => el.addEventListener(e, h))
      // return properly scoped cleanup method for removing listeners
      return () => tls.forEach(([e, h]) => el.removeEventListener(e, h))
    }
  }

  const onRef = el => {
    // "inline" ref functions are called twice on render, once with null then again with DOM element
    // ignore null here
    if (el === null) return
    set.current((state, props) => {
      // if the same DOM el as previous just return state
      if (state.el === el) return state

      let addState = {}
      // if new DOM el clean up old DOM and reset cleanUpTouch
      if (state.el && state.el !== el && state.cleanUpTouch) {
        state.cleanUpTouch()
        addState.cleanUpTouch = null
      }
      // only attach if we want to track touch
      if (props.trackTouch && el) {
        addState.cleanUpTouch = attachTouch(el)
      }

      // store event attached DOM el for comparison, clean up, and re-attachment
      return { ...state, el, ...addState }
    })
  }

  // update state, and handlers
  set.current((state, props) => {
    let addState = {}
    // clean up touch handlers if no longer tracking touches
    if (!props.trackTouch && state.cleanUpTouch) {
      state.cleanUpTouch()
      addState.cleanUpTouch = null
    } else if (props.trackTouch && !state.cleanUpTouch) {
      // attach/re-attach touch handlers
      if (state.el) {
        addState.cleanUpTouch = attachTouch(state.el)
      }
    }
    return { ...state, ...addState }
  })

  // set ref callback to attach touch event listeners
  const output = { ref: onRef }

  // if track mouse attach mouse down listener
  if (handlerProps.trackMouse) {
    output.onMouseDown = onStart
  }

  return output
}

export function useSwipeable(props) {
  const transientState = React.useRef({ ...initialState, type: 'hook' })
  const set = React.useRef()
  set.current = cb =>
    (transientState.current = cb(transientState.current, { ...defaultProps, ...props }))
  return getHandlers(set, { trackMouse: props.trackMouse })
}

export class Swipeable extends React.PureComponent {
  static propTypes = {
    onSwiped: PropTypes.func,
    onSwiping: PropTypes.func,
    onSwipedUp: PropTypes.func,
    onSwipedRight: PropTypes.func,
    onSwipedDown: PropTypes.func,
    onSwipedLeft: PropTypes.func,
    delta: PropTypes.number,
    preventDefaultTouchmoveEvent: PropTypes.bool,
    nodeName: PropTypes.string,
    trackMouse: PropTypes.bool,
    trackTouch: PropTypes.bool,
    innerRef: PropTypes.func,
    rotationAngle: PropTypes.number
  }

  static defaultProps = defaultProps

  constructor(props) {
    super(props)
    this._state = { ...initialState, type: 'class' }
    this._set = { current: this._current }
  }

  _current = cb => {
    this._state = cb(this._state, this.props)
  }

  render() {
    const { className, style, nodeName = 'div', innerRef, children, trackMouse } = this.props
    const handlers = getHandlers(this._set, { trackMouse })
    const ref = innerRef ? el => (innerRef(el), handlers.ref(el)) : handlers.ref
    return React.createElement(nodeName, { ...handlers, className, style, ref }, children)
  }
}
<|endoftext|>


<commit_before>jBone.fn.find = function(selector) {
    var results = [];

    this.forEach(function(el) {
        try {
            [].forEach.call(el.querySelectorAll(selector), function(finded) {
                results.push(finded);
            });
        } catch(e) {
            // can't results
        }
    });

    return jBone(results);
};

jBone.fn.get = function(index) {
    return this[index];
};

jBone.fn.eq = function(index) {
    return jBone(this[index]);
};

jBone.fn.parent = function() {
    var results = [], parent;

    this.forEach(function(el) {
        if (!~results.indexOf(parent = el.parentElement) && parent) {
            results.push(parent);
        }
    });

    return jBone(results);
};

jBone.fn.toArray = function() {
    return slice.call(this);
};

jBone.fn.is = function() {
    var args = arguments;

    return this.some(function(el) {
        return el.tagName.toLowerCase() === args[0];
    });
};

jBone.fn.has = function() {
    var args = arguments;

    return this.some(function(el) {
        return el.querySelectorAll(args[0]).length;
    });
};
<commit_msg>Typos fixed<commit_after>jBone.fn.find = function(selector) {
    var results = [];

    this.forEach(function(el) {
        try {
            [].forEach.call(el.querySelectorAll(selector), function(found) {
                results.push(found);
            });
        } catch(e) {
            // results not found
        }
    });

    return jBone(results);
};

jBone.fn.get = function(index) {
    return this[index];
};

jBone.fn.eq = function(index) {
    return jBone(this[index]);
};

jBone.fn.parent = function() {
    var results = [], parent;

    this.forEach(function(el) {
        if (!~results.indexOf(parent = el.parentElement) && parent) {
            results.push(parent);
        }
    });

    return jBone(results);
};

jBone.fn.toArray = function() {
    return slice.call(this);
};

jBone.fn.is = function() {
    var args = arguments;

    return this.some(function(el) {
        return el.tagName.toLowerCase() === args[0];
    });
};

jBone.fn.has = function() {
    var args = arguments;

    return this.some(function(el) {
        return el.querySelectorAll(args[0]).length;
    });
};
<|endoftext|>


<commit_before>class LocalStorageAdapter {
    get(_storageName) {
        return new Promise( _resolve => {
            _resolve(JSON.parse(window.localStorage.getItem(_storageName)));
        });
    }

    set(_storageName, _data) {
        window.localStorage.setItem(_storageName, JSON.stringify(_data));
    }
}

class Repository {

    constructor(config) {
        this.config = config;
        this.syncInterval = null;

        this.storage = new LocalStorageAdapter();
    }

    _normalizeData(_response) {
        const obj = {};

        Object.keys(this.config.dataModel).forEach(
            key => obj[key] = _response[this.config.dataModel[key]]
        );

        return obj;
    }

    /**
     * Checks if repository the data is up to date or not.
     *
     * @return {Boolean}
     */
    _isDataUpToDate(_localStore) {
        const isDataMissing =
            _localStore === null || Object.keys(_localStore.data).length === 0;

        if (isDataMissing) {
            return false;
        }

        const { lastFetched } = _localStore;

        const isLimitExceeded =
            (new Date().valueOf() - lastFetched) > this.config.cacheLimit;

        return ! isLimitExceeded;
    }

    _storeData(_data) {
        this.storage.set(this.config.name, {
            lastFetched: new Date().valueOf(),
            data: _data
        });
    }

    /**
     * Access the repository data.
     *
     * @return {Promise}
     */
    getData(){
        const localData = this.storage.get(this.config.name);

        return new Promise(_resolve => {
            localData.then(_localData => {
                if (this._isDataUpToDate(_localData)) {
                    _resolve(_localData.data);
                } else {
                    this.config.request()
                        .then(this._normalizeData.bind(this))
                        .then(response => {
                            this._storeData(response);

                            return response;
                        })
                        .then(_resolve);
                }
            });
        });
    }

    initSyncer() {
        this.storage.get(this.config.name).then(_localData => {
            if (this._isDataUpToDate(_localData)) {
                const { lastFetched } = _localData;
                const diff = new Date().valueOf() - lastFetched;

                this.syncInterval = setInterval( () => this.getData(), diff);
            } else {
                this.getData().then(r => {
                    this.syncInterval = setInterval(
                        () => this.getData(), this.config.cacheLimit
                    );

                    return r;
                });
            }
        });
    }

    destroySyncer() {
        this.syncInterval = null;
    }
};

/**
 * Uses Node, AMD or browser globals to create a module. This example creates
 * a global even when AMD is used. This is useful if you have some scripts
 * that are loaded by an AMD loader, but they still want access to globals.
 *
 * {@link https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js}
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], function () {
            return (root.returnExportsGlobal = factory());
        });
    } else if (typeof module === 'object' && module.exports) {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals
        root.returnExportsGlobal = factory();
    }
}(this, function () {
    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return Repository;
}));
<commit_msg>Fix: sync interval logic<commit_after>class LocalStorageAdapter {
    get(_storageName) {
        return new Promise( _resolve => {
            _resolve(JSON.parse(window.localStorage.getItem(_storageName)));
        });
    }

    set(_storageName, _data) {
        window.localStorage.setItem(_storageName, JSON.stringify(_data));
    }
}

class Repository {

    constructor(config) {
        this.config = config;
        this.syncInterval = null;

        this.storage = new LocalStorageAdapter();
    }

    _normalizeData(_response) {
        const obj = {};

        Object.keys(this.config.dataModel).forEach(
            key => obj[key] = _response[this.config.dataModel[key]]
        );

        return obj;
    }

    /**
     * Checks if repository the data is up to date or not.
     *
     * @return {Boolean}
     */
    _isDataUpToDate(_localStore) {
        const isDataMissing =
            _localStore === null || Object.keys(_localStore.data).length === 0;

        if (isDataMissing) {
            return false;
        }

        const { lastFetched } = _localStore;

        const isLimitExceeded =
            (new Date().valueOf() - lastFetched) > this.config.cacheLimit;

        return ! isLimitExceeded;
    }

    _storeData(_data) {
        this.storage.set(this.config.name, {
            lastFetched: new Date().valueOf(),
            data: _data
        });
    }

    /**
     * Access the repository data.
     *
     * @return {Promise}
     */
    getData(){
        const localData = this.storage.get(this.config.name);

        return new Promise(_resolve => {
            localData.then(_localData => {
                if (this._isDataUpToDate(_localData)) {
                    _resolve(_localData.data);
                } else {
                    this.config.request()
                        .then(this._normalizeData.bind(this))
                        .then(response => {
                            this._storeData(response);

                            return response;
                        })
                        .then(_resolve);
                }
            });
        });
    }

    _initSyncInterval(_interval) {
        this.syncInterval = setInterval(
            () => this.getData(), _interval
        );
    }

    initSyncer() {
        this.storage.get(this.config.name).then(_localData => {
            if (this._isDataUpToDate(_localData)) {
                const { lastFetched } = _localData;
                const diff = new Date().valueOf() - lastFetched;

                this.syncInterval = this._initSyncInterval(diff);

                setTimeout( () => {
                    this.syncInterval = this._initSyncInterval(this.config.cacheLimit);
                }, diff);
            } else {
                this.getData().then(r => {
                    this.syncInterval = this._initSyncInterval(this.config.cacheLimit)

                    return r;
                });
            }
        });
    }

    destroySyncer() {
        this.syncInterval = null;
    }
};

/**
 * Uses Node, AMD or browser globals to create a module. This example creates
 * a global even when AMD is used. This is useful if you have some scripts
 * that are loaded by an AMD loader, but they still want access to globals.
 *
 * {@link https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js}
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], function () {
            return (root.returnExportsGlobal = factory());
        });
    } else if (typeof module === 'object' && module.exports) {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals
        root.returnExportsGlobal = factory();
    }
}(this, function () {
    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return Repository;
}));
<|endoftext|>