<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import css from './Select.css';
import formStyles from '../sharedStyles/form.css';
import sharedInputStylesHelper from '../sharedStyles/sharedInputStylesHelper';

const propTypes = {
  dataOptions: PropTypes.arrayOf(PropTypes.object),
  meta: PropTypes.object,
  fullWidth: PropTypes.bool,
  input: PropTypes.object,
  placeholder: PropTypes.string,
  value: PropTypes.string,
  error: PropTypes.bool,
  required: PropTypes.bool,
  marginBottom0: PropTypes.bool,
  id: PropTypes.string,
};

const defaultProps = {
  meta: {},
  rounded: true,
};

class Select extends React.Component {
  getRootClass() {
    return classNames(
      css.root,
      formStyles.inputGroup,
      { [`${css.fullWidth}`]: this.props.fullWidth },
    );
  }

  getLabelClass() {
    return classNames(
      formStyles.label,
      { [`${css.required}`]: this.props.required },
    );
  }

  getSelectClass() {
    return classNames(
      css.selectControl,
      // placeholder styling
      {
        [`${css.placeholder}`]: this.props.input ?
          this.props.placeholder && !this.props.input.value :
          this.props.placeholder && !this.props.value,
      }, // end placeholder
      sharedInputStylesHelper(this.props),
    );
  }

  render() {
    const { input, meta: { error, warning, touched }, ...rest } = this.props;
    const { ...selectAttr } = input;
    const {
      label,
      placeholder,
      dataOptions,
      children,
      fullWidth, // eslint-disable-line no-unused-vars
      marginBottom0, // eslint-disable-line no-unused-vars
      ...selectCustom
    } = rest;

    const options = [];

    if (this.props.placeholder) options.push(<option value="" key="x" disabled>{placeholder}</option>);

    if (dataOptions) {
      dataOptions.forEach((option, i) => {
        options.push(<option value={option.value} key={option.id || `option-${i}`}>{option.label}</option>);
      });
    }

    const component = (
      <select className={classNames(formStyles.input, this.getSelectClass())} {...selectAttr} {...selectCustom} >
        {options}
        {children}
      </select>
    );

    const errorElem = touched && error ?

{error}
 : null;

    const warningElem = touched && warning ?

{warning}
 : null;

    return (

        { label ? ({label}) : '' }
        {component}
        {warningElem}
        {errorElem}

    );
  }
}

Select.propTypes = propTypes;
Select.defaultProps = defaultProps;

export default Select;
<commit_msg>Removed duplicate input class from select<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import css from './Select.css';
import formStyles from '../sharedStyles/form.css';
import sharedInputStylesHelper from '../sharedStyles/sharedInputStylesHelper';

const propTypes = {
  dataOptions: PropTypes.arrayOf(PropTypes.object),
  meta: PropTypes.object,
  fullWidth: PropTypes.bool,
  input: PropTypes.object,
  placeholder: PropTypes.string,
  value: PropTypes.string,
  error: PropTypes.bool,
  required: PropTypes.bool,
  marginBottom0: PropTypes.bool,
  id: PropTypes.string,
};

const defaultProps = {
  meta: {},
  rounded: true,
};

class Select extends React.Component {
  getRootClass() {
    return classNames(
      css.root,
      formStyles.inputGroup,
      { [`${css.fullWidth}`]: this.props.fullWidth },
    );
  }

  getLabelClass() {
    return classNames(
      formStyles.label,
      { [`${css.required}`]: this.props.required },
    );
  }

  getSelectClass() {
    return classNames(
      css.selectControl,
      // placeholder styling
      {
        [`${css.placeholder}`]: this.props.input ?
          this.props.placeholder && !this.props.input.value :
          this.props.placeholder && !this.props.value,
      }, // end placeholder
      sharedInputStylesHelper(this.props),
    );
  }

  render() {
    const { input, meta: { error, warning, touched }, ...rest } = this.props;
    const { ...selectAttr } = input;
    const {
      label,
      placeholder,
      dataOptions,
      children,
      fullWidth, // eslint-disable-line no-unused-vars
      marginBottom0, // eslint-disable-line no-unused-vars
      ...selectCustom
    } = rest;

    const options = [];

    if (this.props.placeholder) options.push(<option value="" key="x" disabled>{placeholder}</option>);

    if (dataOptions) {
      dataOptions.forEach((option, i) => {
        options.push(<option value={option.value} key={option.id || `option-${i}`}>{option.label}</option>);
      });
    }

    const component = (
      <select className={this.getSelectClass()} {...selectAttr} {...selectCustom} >
        {options}
        {children}
      </select>
    );

    const errorElem = touched && error ?

{error}
 : null;

    const warningElem = touched && warning ?

{warning}
 : null;

    return (

        { label ? ({label}) : '' }
        {component}
        {warningElem}
        {errorElem}

    );
  }
}

Select.propTypes = propTypes;
Select.defaultProps = defaultProps;

export default Select;
<|endoftext|>


<commit_before>var SwipeCards = (function () {
	'use strict';

	/**
	 * @constant The speed cards will animate to completion with a fast drag
     * @type {number}
	 */
	var ANIMATION_SPEED_FAST = 200;

	/**
	 * @constant The speed cards will animate to completion with a slow drag
     * @type {number}
	 */
	var ANIMATION_SPEED_SLOW = 100;

	/**
	 * @constant The boundary to determine a fast or slow drag 0 (slow) to 3+ (very fast)
     * @type {number}
	 */
	var DRAG_VELOCITY_BOUNDARY = 2;

	/**
	 * @constant Fraction of the viewport to drag past to auto complete a card transition
     * @type {number}
	 */
	var DRAG_WINDOW_FRACTION = 6;

	/**
	 * Hold the hammer.js object
	 * @type {object}
	 */
	var h = {};

	/**
	 * The before, active, and after card DOM elements
	 * @type {object}
	 */
	var cardEls = {};

	/**
	 * The current drag direction from user input
	 * @type {string}
	 */
	var direction = false;

	/**
	 * Easy shortener for handling adding and removing body classes.
	 */
	var bodyClass = document.body.classList;

	/**
	 * Initialize pull to refresh, hammer, and bind touch events.
	 */
	var init = function() {
		_setCardEls();
		_bindTouchEvents();
	};

	/**
	 * Initialize the hammer.js class, and bind drag events.
	 */
	var _bindTouchEvents = function() {
		h = new Hammer( cardEls.active, { preventDefault: true } );

		h.on( 'dragup', _dragUp );
		h.on( 'dragdown', _dragDown );
		h.on( 'dragend', _dragEnd );

		// While drag events are active, make sure touch events are accessible.
		for( var card in cardEls ) {
			cardEls[card].removeEventListener( 'touchstart', _disableTouch );
		}
	};

	/**
	 * Unbind hammer.js drag events.
	 */
	var _unbindTouchEvents = function() {
		h.off( 'dragup', _dragUp );
		h.off( 'dragdown', _dragDown );
		h.off( 'dragend', _dragEnd );

		// While drag events are not active, block all touch events to stop scrolling.
		for( var card in cardEls ) {
			cardEls[card].addEventListener( 'touchstart', _disableTouch, false );
		}
	};

	/**
	 * Select the card elements from the DOM and store them in cardEls for easy access.
	 */
	var _setCardEls = function() {
		cardEls.before = document.getElementsByClassName( 'before' )[0];
		cardEls.active = document.getElementsByClassName( 'active' )[0];
		cardEls.after = document.getElementsByClassName( 'after' )[0];
	};

	/**
	 * On the dragup event, transform the active and after card elements to move
	 * with the drag.
	 */
	var _dragUp = function( e ) {
		var distancePercent = Math.round( ( e.gesture.distance / window.innerHeight ) * 100 );
		var opacity = ( distancePercent < 30 ) ? 30 : distancePercent;

		cardEls.active.style.transform = cardEls.active.style.webkitTransform = 'translate3d( 0, -' + e.gesture.distance + 'px, 0 )';
		cardEls.after.style.transform  = cardEls.after.style.webkitTransform = 'translate3d( 0, ' + ( window.innerHeight - e.gesture.distance ) + 'px, 0 )';
		cardEls.after.style.opacity = '.' + opacity;
	};

	/**
	 * On the dragdown event, transform the active and before card elements
	 * to move with the drag.
	 */
	var _dragDown = function( e ) {
		var distancePercent = Math.round( ( e.gesture.distance / window.innerHeight ) * 100 );
		var opacity = ( distancePercent < 30 ) ? 30 : distancePercent;

		cardEls.active.style.transform = cardEls.active.style.webkitTransform = 'translate3d( 0, ' + e.gesture.distance + 'px, 0 )';
		cardEls.before.style.transform = cardEls.before.style.webkitTransform = 'translate3d( 0, ' + ( -window.innerHeight + e.gesture.distance ) +  'px, 0 )';
		cardEls.before.style.opacity = '.' + opacity;
	};

	/**
	 * On the dragend event, determine if the drag animation should slide
	 * the next card in, or restore the active card.
	 */
	var _dragEnd = function( e ) {
		direction = e.gesture.direction;

		// Disable hammer and any touch events until animation is complete.
		_unbindTouchEvents();

		var animationSpeed = ( e.gesture.velocityY > DRAG_VELOCITY_BOUNDARY ) ? ANIMATION_SPEED_SLOW : ANIMATION_SPEED_FAST;

		cardEls.active.classList.add( 'animate' );

		for( var card in cardEls ) {
			cardEls[card].style.transition = 'all ' + animationSpeed + 'ms ease';
		}

		// Finish the transition after swipe.
		if ( 'up' === direction ) {
			_completeUpTransition( e );
		} else {
			_completeDownTransition( e );
		}

		// When the transition is done shift around the active card.
		cardEls.active.addEventListener( 'transitionend', _shiftActiveCard, false );
	};

	/**
	 * Change the active card class if the transition was a success.
	 */
	var _shiftActiveCard = function( e ) {
		cardEls.active.classList.remove( 'animate' );

		[ 'animate', 'dragup-reset', 'drag-complete', 'dragup-complete', 'dragdown-reset', 'dragdown-complete' ].forEach( function( c ) {
			bodyClass.remove( c );
		} );

		for( var card in cardEls ) {
			cardEls[card].style.transition = '';
			cardEls[card].style.transform = cardEls[card].style.webkitTransform = '';
			cardEls[card].style.opacity = '';
		}

		cardEls.active.removeEventListener( 'transitionend', _shiftActiveCard, false );

		// If the transition to a new card was successful then shift cards
		if ( cardEls.active.classList.contains( 'drag-complete' ) ) {
			_setCardClasses();
		}

		// Reselect card elements and their new classes.
		_setCardEls();

		_bindTouchEvents();
	};

	/**
	 * Set the classes on each card, depending on the completed drag direction.
	 */
	var _setCardClasses = function() {
		var beforeCardClass = cardEls.before.classList;
		var activeCardClass = cardEls.active.classList;
		var afterCardClass = cardEls.after.classList;

		if ( 'up' === direction ) {
			beforeCardClass.remove( 'before' );
			beforeCardClass.add( 'after' );

			activeCardClass.remove( 'active' );
			activeCardClass.remove( 'drag-complete' );
			activeCardClass.add( 'before' );

			afterCardClass.remove( 'after' );
			afterCardClass.add( 'active' );
		} else {
			beforeCardClass.remove( 'before' );
			beforeCardClass.add( 'active' );

			activeCardClass.remove( 'active' );
			activeCardClass.remove( 'drag-complete' );
			activeCardClass.add( 'after' );

			afterCardClass.remove( 'after' );
			afterCardClass.add( 'before' );
		}
	};

	/**
	 * Add the correct class to the body, depending on if the drag was completed or not.
	 */
	var _completeUpTransition = function( e ) {
		if ( e.gesture.distance < window.innerHeight / DRAG_WINDOW_FRACTION ) {
			bodyClass.add( 'dragup-reset' );
		} else {
			bodyClass.add( 'dragup-complete' );
			cardEls.active.classList.add( 'drag-complete' );
		}
	};

	var _completeDownTransition = function( e ) {
		if ( e.gesture.distance < window.innerHeight / DRAG_WINDOW_FRACTION ) {
			bodyClass.add( 'dragdown-reset' );
		} else {
			bodyClass.add( 'dragdown-complete' );
			cardEls.active.classList.add( 'drag-complete' );
		}
	};

	var _disableTouch = function( e ) {
		e.preventDefault();
	};

	return {
		init: init
	}

})();<commit_msg>Add in file license<commit_after>/*! JavaScript Swipe Cards
 * https://github.com/apeatling/javascript-swipe-cards
 *
 * Copyright (c) 2014 Andy Peatling <apeatling@gmail.com>;
 * Licensed under the MIT license */

var SwipeCards = (function () {
	'use strict';

	/**
	 * @constant The speed cards will animate to completion with a fast drag
     * @type {number}
	 */
	var ANIMATION_SPEED_FAST = 200;

	/**
	 * @constant The speed cards will animate to completion with a slow drag
     * @type {number}
	 */
	var ANIMATION_SPEED_SLOW = 100;

	/**
	 * @constant The boundary to determine a fast or slow drag 0 (slow) to 3+ (very fast)
     * @type {number}
	 */
	var DRAG_VELOCITY_BOUNDARY = 2;

	/**
	 * @constant Fraction of the viewport to drag past to auto complete a card transition
     * @type {number}
	 */
	var DRAG_WINDOW_FRACTION = 6;

	/**
	 * Hold the hammer.js object
	 * @type {object}
	 */
	var h = {};

	/**
	 * The before, active, and after card DOM elements
	 * @type {object}
	 */
	var cardEls = {};

	/**
	 * The current drag direction from user input
	 * @type {string}
	 */
	var direction = false;

	/**
	 * Easy shortener for handling adding and removing body classes.
	 */
	var bodyClass = document.body.classList;

	/**
	 * Initialize pull to refresh, hammer, and bind touch events.
	 */
	var init = function() {
		_setCardEls();
		_bindTouchEvents();
	};

	/**
	 * Initialize the hammer.js class, and bind drag events.
	 */
	var _bindTouchEvents = function() {
		h = new Hammer( cardEls.active, { preventDefault: true } );

		h.on( 'dragup', _dragUp );
		h.on( 'dragdown', _dragDown );
		h.on( 'dragend', _dragEnd );

		// While drag events are active, make sure touch events are accessible.
		for( var card in cardEls ) {
			cardEls[card].removeEventListener( 'touchstart', _disableTouch );
		}
	};

	/**
	 * Unbind hammer.js drag events.
	 */
	var _unbindTouchEvents = function() {
		h.off( 'dragup', _dragUp );
		h.off( 'dragdown', _dragDown );
		h.off( 'dragend', _dragEnd );

		// While drag events are not active, block all touch events to stop scrolling.
		for( var card in cardEls ) {
			cardEls[card].addEventListener( 'touchstart', _disableTouch, false );
		}
	};

	/**
	 * Select the card elements from the DOM and store them in cardEls for easy access.
	 */
	var _setCardEls = function() {
		cardEls.before = document.getElementsByClassName( 'before' )[0];
		cardEls.active = document.getElementsByClassName( 'active' )[0];
		cardEls.after = document.getElementsByClassName( 'after' )[0];
	};

	/**
	 * On the dragup event, transform the active and after card elements to move
	 * with the drag.
	 */
	var _dragUp = function( e ) {
		var distancePercent = Math.round( ( e.gesture.distance / window.innerHeight ) * 100 );
		var opacity = ( distancePercent < 30 ) ? 30 : distancePercent;

		cardEls.active.style.transform = cardEls.active.style.webkitTransform = 'translate3d( 0, -' + e.gesture.distance + 'px, 0 )';
		cardEls.after.style.transform  = cardEls.after.style.webkitTransform = 'translate3d( 0, ' + ( window.innerHeight - e.gesture.distance ) + 'px, 0 )';
		cardEls.after.style.opacity = '.' + opacity;
	};

	/**
	 * On the dragdown event, transform the active and before card elements
	 * to move with the drag.
	 */
	var _dragDown = function( e ) {
		var distancePercent = Math.round( ( e.gesture.distance / window.innerHeight ) * 100 );
		var opacity = ( distancePercent < 30 ) ? 30 : distancePercent;

		cardEls.active.style.transform = cardEls.active.style.webkitTransform = 'translate3d( 0, ' + e.gesture.distance + 'px, 0 )';
		cardEls.before.style.transform = cardEls.before.style.webkitTransform = 'translate3d( 0, ' + ( -window.innerHeight + e.gesture.distance ) +  'px, 0 )';
		cardEls.before.style.opacity = '.' + opacity;
	};

	/**
	 * On the dragend event, determine if the drag animation should slide
	 * the next card in, or restore the active card.
	 */
	var _dragEnd = function( e ) {
		direction = e.gesture.direction;

		// Disable hammer and any touch events until animation is complete.
		_unbindTouchEvents();

		var animationSpeed = ( e.gesture.velocityY > DRAG_VELOCITY_BOUNDARY ) ? ANIMATION_SPEED_SLOW : ANIMATION_SPEED_FAST;

		cardEls.active.classList.add( 'animate' );

		for( var card in cardEls ) {
			cardEls[card].style.transition = 'all ' + animationSpeed + 'ms ease';
		}

		// Finish the transition after swipe.
		if ( 'up' === direction ) {
			_completeUpTransition( e );
		} else {
			_completeDownTransition( e );
		}

		// When the transition is done shift around the active card.
		cardEls.active.addEventListener( 'transitionend', _shiftActiveCard, false );
	};

	/**
	 * Change the active card class if the transition was a success.
	 */
	var _shiftActiveCard = function( e ) {
		cardEls.active.classList.remove( 'animate' );

		[ 'animate', 'dragup-reset', 'drag-complete', 'dragup-complete', 'dragdown-reset', 'dragdown-complete' ].forEach( function( c ) {
			bodyClass.remove( c );
		} );

		for( var card in cardEls ) {
			cardEls[card].style.transition = '';
			cardEls[card].style.transform = cardEls[card].style.webkitTransform = '';
			cardEls[card].style.opacity = '';
		}

		cardEls.active.removeEventListener( 'transitionend', _shiftActiveCard, false );

		// If the transition to a new card was successful then shift cards
		if ( cardEls.active.classList.contains( 'drag-complete' ) ) {
			_setCardClasses();
		}

		// Reselect card elements and their new classes.
		_setCardEls();

		_bindTouchEvents();
	};

	/**
	 * Set the classes on each card, depending on the completed drag direction.
	 */
	var _setCardClasses = function() {
		var beforeCardClass = cardEls.before.classList;
		var activeCardClass = cardEls.active.classList;
		var afterCardClass = cardEls.after.classList;

		if ( 'up' === direction ) {
			beforeCardClass.remove( 'before' );
			beforeCardClass.add( 'after' );

			activeCardClass.remove( 'active' );
			activeCardClass.remove( 'drag-complete' );
			activeCardClass.add( 'before' );

			afterCardClass.remove( 'after' );
			afterCardClass.add( 'active' );
		} else {
			beforeCardClass.remove( 'before' );
			beforeCardClass.add( 'active' );

			activeCardClass.remove( 'active' );
			activeCardClass.remove( 'drag-complete' );
			activeCardClass.add( 'after' );

			afterCardClass.remove( 'after' );
			afterCardClass.add( 'before' );
		}
	};

	/**
	 * Add the correct class to the body, depending on if the drag was completed or not.
	 */
	var _completeUpTransition = function( e ) {
		if ( e.gesture.distance < window.innerHeight / DRAG_WINDOW_FRACTION ) {
			bodyClass.add( 'dragup-reset' );
		} else {
			bodyClass.add( 'dragup-complete' );
			cardEls.active.classList.add( 'drag-complete' );
		}
	};

	var _completeDownTransition = function( e ) {
		if ( e.gesture.distance < window.innerHeight / DRAG_WINDOW_FRACTION ) {
			bodyClass.add( 'dragdown-reset' );
		} else {
			bodyClass.add( 'dragdown-complete' );
			cardEls.active.classList.add( 'drag-complete' );
		}
	};

	var _disableTouch = function( e ) {
		e.preventDefault();
	};

	return {
		init: init
	}

})();<|endoftext|>


<commit_before>import NodePatcher from './../../../patchers/NodePatcher.js';
import type { Token, Editor, Node, ParseContext } from './../../../patchers/types.js';

/**
 * Handles `while` loops, e.g.
 *
 *   while a
 *     b
 */
export default class WhilePatcher extends NodePatcher {
  constructor(node: Node, context: ParseContext, editor: Editor, condition: NodePatcher, guard: ?NodePatcher, body: ?NodePatcher) {
    super(node, context, editor);
    this.condition = condition;
    this.guard = guard;
    this.body = body;
  }

  /**
   * ( 'while' | 'until' ) CONDITION ('when' GUARD)? 'then' BODY
   * ( 'while' | 'until' ) CONDITION ('when' GUARD)? NEWLINE INDENT BODY
   * BODY ( 'while' | 'until' ) CONDITION ('when' GUARD)?
   * 'loop' 'then' BODY
   * 'loop' NEWLINE INDENT BODY
   */
  patchAsStatement() {
    // `until a` → `while a`
    //  ^^^^^       ^^^^^
    let whileToken = this.context.tokenAtIndex(this.startTokenIndex);
    let isLoop = this.context.source.slice(...whileToken.range) === 'loop';

    if (isLoop) {
      this.overwrite(...whileToken.range, 'while (true) {');
    } else {
      this.overwrite(...whileToken.range, 'while');

      let conditionNeedsParens = !this.condition.isSurroundedByParentheses();
      if (conditionNeedsParens) {
        // `while a` → `while (a`
        //                    ^
        this.insert(this.condition.before, '(');
      }

      if (this.node.isUntil) {
        this.condition.negate();
      }
      this.condition.patch();

      if (this.guard) {
        let guardNeedsParens = !this.guard.isSurroundedByParentheses();
        let bodyIndent = this.body.getIndent();
        // `while (a when b` → `while (a) {\n  if (b`
        //          ^^^^^^              ^^^^^^^^^^^
        this.overwrite(
          this.condition.after,
          this.guard.before,
          `${conditionNeedsParens ? ')' : ''} {\n${bodyIndent}if ${guardNeedsParens ? '(' : ''}`
        );
        this.guard.patch();

        // `while (a) {\n  if (b` → `while (a) {\n  if (b) {`
        //                                               ^^^
        this.insert(this.guard.after, `${guardNeedsParens ? ')' : ''} {`);
        this.body.indent();
      } else {
        // `while (a` → `while (a) {`
        //                       ^^^
        this.insert(this.condition.after, `${conditionNeedsParens ? ')' : ''} {`);
      }
    }

    this.body.patch({ leftBrace: false, rightBrace: false });

    if (this.guard) {
      // Close the guard's `if` consequent block.
      this.body.appendLineAfter('}');
    }

    // Close the `while` body block.
    this.appendLineAfter('}');
  }

  patchAsExpression() {
    throw this.error(`cannot handle 'while' used as an expression (yet)`);
  }

  /**
   * @private
   */
  getWhenToken(): ?Token {
    if (this.guard) {
      return this.tokenBetweenPatchersMatching(
        this.condition,
        this.guard,
        'WHEN'
      );
    } else {
      return null;
    }
  }
}
<commit_msg>Ensure `while` statements don't end with semicolons.<commit_after>import NodePatcher from './../../../patchers/NodePatcher.js';
import type { Token, Editor, Node, ParseContext } from './../../../patchers/types.js';

/**
 * Handles `while` loops, e.g.
 *
 *   while a
 *     b
 */
export default class WhilePatcher extends NodePatcher {
  constructor(node: Node, context: ParseContext, editor: Editor, condition: NodePatcher, guard: ?NodePatcher, body: ?NodePatcher) {
    super(node, context, editor);
    this.condition = condition;
    this.guard = guard;
    this.body = body;
  }

  /**
   * ( 'while' | 'until' ) CONDITION ('when' GUARD)? 'then' BODY
   * ( 'while' | 'until' ) CONDITION ('when' GUARD)? NEWLINE INDENT BODY
   * BODY ( 'while' | 'until' ) CONDITION ('when' GUARD)?
   * 'loop' 'then' BODY
   * 'loop' NEWLINE INDENT BODY
   */
  patchAsStatement() {
    // `until a` → `while a`
    //  ^^^^^       ^^^^^
    let whileToken = this.context.tokenAtIndex(this.startTokenIndex);
    let isLoop = this.context.source.slice(...whileToken.range) === 'loop';

    if (isLoop) {
      this.overwrite(...whileToken.range, 'while (true) {');
    } else {
      this.overwrite(...whileToken.range, 'while');

      let conditionNeedsParens = !this.condition.isSurroundedByParentheses();
      if (conditionNeedsParens) {
        // `while a` → `while (a`
        //                    ^
        this.insert(this.condition.before, '(');
      }

      if (this.node.isUntil) {
        this.condition.negate();
      }
      this.condition.patch();

      if (this.guard) {
        let guardNeedsParens = !this.guard.isSurroundedByParentheses();
        let bodyIndent = this.body.getIndent();
        // `while (a when b` → `while (a) {\n  if (b`
        //          ^^^^^^              ^^^^^^^^^^^
        this.overwrite(
          this.condition.after,
          this.guard.before,
          `${conditionNeedsParens ? ')' : ''} {\n${bodyIndent}if ${guardNeedsParens ? '(' : ''}`
        );
        this.guard.patch();

        // `while (a) {\n  if (b` → `while (a) {\n  if (b) {`
        //                                               ^^^
        this.insert(this.guard.after, `${guardNeedsParens ? ')' : ''} {`);
        this.body.indent();
      } else {
        // `while (a` → `while (a) {`
        //                       ^^^
        this.insert(this.condition.after, `${conditionNeedsParens ? ')' : ''} {`);
      }
    }

    this.body.patch({ leftBrace: false, rightBrace: false });

    if (this.guard) {
      // Close the guard's `if` consequent block.
      this.body.appendLineAfter('}');
    }

    // Close the `while` body block.
    this.appendLineAfter('}');
  }

  patchAsExpression() {
    throw this.error(`cannot handle 'while' used as an expression (yet)`);
  }

  statementNeedsSemicolon() {
    return false;
  }

  /**
   * @private
   */
  getWhenToken(): ?Token {
    if (this.guard) {
      return this.tokenBetweenPatchersMatching(
        this.condition,
        this.guard,
        'WHEN'
      );
    } else {
      return null;
    }
  }
}
<|endoftext|>


<commit_before>var utils = require('./utils');

/**
 * Main markup syndax parser
 * @param  {string}   data     markup text
 * @param  {Function} callback callback function
 * @return {undefined}         return undefined when error occurs
 */
module.exports = function(data, callback) {

  /**********************************
   * Parse scraping result,         *
   * which is in the format of JSON *
   **********************************/

  try {
    content = JSON.parse(data);
  } catch(e) {
    callback(e);
    return;
  }

  if (!content.query) { callback(new Error('Query Not Found')); return; }

  /**
   * Get JSON data
   */
  var json = content.query.pages;
  var key  = Object.keys(json);

  if (key.indexOf('-1') === 0) {
    callback(new Error('Page Index Not Found'));
    return;
  } else if(!json[key]){
    callback(new Error('Malformed Response Payload'));
    return;
  } else if (json[key].revisions[0]['*'].indexOf('REDIRECT') > -1) {
    callback(new Error(json[key].revisions[0]['*']));
    return;
  }

  /**
   * Get the JSON data that contains infobox section
   */
  var reg    = new RegExp('{{[Ii]nfobox(.|\n)*}}', 'g');
  var text   = reg.exec(json[key].revisions[0]['*']);
  if (!text) { callback(new Error('Infobox Not Found')); return; }
  text = text[0];

  /************************
   * Remove useless marks *
   ************************/

  /*
   * Remove comments
   */
  text = utils.replaceAll('', '', text);
  /*
   * Remove reference
   * TODO: support reference in advanced model
   */
  text = utils.replaceAll('<ref.*(/>|>.*</ref>)', '', text);
  /*
   * Remove all HTML tags like '
', etc.
   */
  text = utils.replaceAll('<[^>]+>', '', text);
  /*
   * Remove footnote
   * TODO; support footnote in advanced model
   */
  text = utils.replaceAll('\{\{refn[^\}\}]*?\}\}', '', text);

  /*
   * Merge order, bulleted, unbulleted, Pagelist
   * list items to one line
   */
  var lists = text.match(/\{\{(order|bulleted|unbulleted|Pagelist)(.*\n)*?\}\}/g);
  if (lists && lists.length) {
    lists.forEach(function(l) {
      text = text.replace(l, l.replace('{{', '').replace('}}', '')
                              .replace(/(order|bulleted|unbulleted)\slist\n\|/g, '')
                              .split('\n|').join(', '));
    });
  }

  /*
   * Parse URL
   */
  lists = text.match(/\{\{(URL)(.*)\}\}/g);
  if (lists && lists.length) {
    lists.forEach(function(l) {
      var tmp = l.replace('{{', '').replace('}}', '').split('|');
      text = (tmp && tmp.length > 0) ? text.replace(l, tmp[tmp.length - 1]) : text;
    });
  }

  /*
   * Parse Start date
   */
  lists = text.match(/\{\{(Start\sdate)(.*)\}\}/g);
  if (lists && lists.length) {
    lists.forEach(function(l) {
      var tmp = l.replace('{{', '').replace('}}', '').split('|');
      /* Pop first element: 'Start date' */
      tmp.shift();
      text = (tmp) ? text.replace(l, tmp.join('/')) : text;
    });
  }

  /*****************************
   * Analyze each line of text *
   *****************************/

  var result = {};
  text.split('\n|').forEach(function(item) {
    /*
     * FIXME: Each item is not always seperated by ' = ',
     *        sometimes it is ' =', '= ', etc.
     *        It's not possible to split them by simply using '=',
     *        because the item might contains several '=',
     *        like: 'students = 300 + 600 = 900'
     */
    var itemArr = item.split(' = ');

    if (itemArr.length === 2 && itemArr[1].trim() !== '') {
      var item_name    = itemArr[0].trim(),
          item_content = itemArr[1].trim().split('\n')[0];

      /*
       * Extract all simple texts inside '[[ ]]'
       * such as [[France]], [[Language French|French]], etc.
       */
      var find = item_content.match(/\[\[.*?\]\]/g);
      if (find) {
        find.forEach(function(substring) {
          var barestring = substring.replace('[[', '').replace(']]', '');
          var arr = barestring.split('|');
          /**
           * TODO: support link.
           * Reference: https://en.wikipedia.org/wiki/Help:Wiki_markup#Links_and_URLs
           */
          item_content = item_content.replace(substring, arr[arr.length - 1]);
        });
      }

      /*
       * Remove font style
       * {{fake clarify}}
       * {{fake citation needed}}
       * {{fake elucidate}}
       * {{fake heading}}
       * {{fake notes and references}}
       * {{dummy ref}}
       * {{dummy backlink}}
       * {{dummy footnote}}
       * {{break}}
       * {{break|5}}
       * {{clear}}
       * {{clear|left}}
       * {{clear|right}}
       * {{plainlist}}
       * {{startflatlist}}
       * {{flatlist}}
       * {{hlist|first item|second item|third item|...}}
       * {{bulleted list |item1 |item2 |...}}
       * {{pagelist}}
       * {{nowrap}}
       * {{italics}}
       * {{smallcaps|small caps}}
       * {{pad|4.0em}}
       */
      while (item_content.indexOf('{{nowrap|') !== -1) {
        item_content = item_content.replace('{{nowrap|', '');
        item_content = item_content.replace('}}', '');
      }

      while (item_content.indexOf('{{small|') !== -1) {
        item_content = item_content.replace('{{small|', '');
        item_content = item_content.replace('}}', '');
      }

      if (item_content.indexOf('{{native') !== -1) {
        find = item_content.match(/\{\{native[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          item_content = item_content.replace(substring, substring.split('|')[2]);
        });
      }

      /* Remove simple vertical list tag */
      if (item_content.indexOf('{{vunblist') !== -1 &&
          item_content.split('{{').length < 3) {

        find = item_content.match(/\{\{vunblist[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          var tmp = substring.split('|');
          tmp.shift();
          item_content = item_content.replace(substring, tmp.join(',').replace('}}', ''));
        });
      }

      /* Remove horizon list tag */
      if (item_content.indexOf('{{hlist') !== -1) {
        find = item_content.match(/\{\{hlist[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          var tmp = substring.split('|');
          tmp.shift();
          item_content = item_content.replace(substring, tmp.join(',').replace('}}', ''));
        });
      }

      /* Remove efn tag */
      if (item_content.indexOf('{{efn') !== -1) {
        find = item_content.match(/\{\{efn[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          item_content = item_content.replace(substring, '');
        });
      }

      item_content = utils.replaceAll('&nbsp', ' ', item_content);
      item_content = utils.replaceAll('\n\}\}', '', item_content);
      result[item_name] = item_content;
    }
  });

  callback(null, JSON.stringify(result));
  return;
};
<commit_msg>Fix '=', ' = ', ' =' and '= ' issue.<commit_after>var utils = require('./utils');

/**
 * Main markup syndax parser
 * @param  {string}   data     markup text
 * @param  {Function} callback callback function
 * @return {undefined}         return undefined when error occurs
 */
module.exports = function(data, callback) {

  /**********************************
   * Parse scraping result,         *
   * which is in the format of JSON *
   **********************************/

  try {
    content = JSON.parse(data);
  } catch(e) {
    callback(e);
    return;
  }

  if (!content.query) { callback(new Error('Query Not Found')); return; }

  /**
   * Get JSON data
   */
  var json = content.query.pages;
  var key  = Object.keys(json);

  if (key.indexOf('-1') === 0) {
    callback(new Error('Page Index Not Found'));
    return;
  } else if(!json[key]){
    callback(new Error('Malformed Response Payload'));
    return;
  } else if (json[key].revisions[0]['*'].indexOf('REDIRECT') > -1) {
    callback(new Error(json[key].revisions[0]['*']));
    return;
  }

  /**
   * Get the JSON data that contains infobox section
   */
  var reg    = new RegExp('{{[Ii]nfobox(.|\n)*}}', 'g');
  var text   = reg.exec(json[key].revisions[0]['*']);
  if (!text) { callback(new Error('Infobox Not Found')); return; }
  text = text[0];

  /************************
   * Remove useless marks *
   ************************/

  /*
   * Remove comments
   */
  text = utils.replaceAll('', '', text);
  /*
   * Remove reference
   * TODO: support reference in advanced model
   */
  text = utils.replaceAll('<ref.*(/>|>.*</ref>)', '', text);
  /*
   * Remove all HTML tags like '
', etc.
   */
  text = utils.replaceAll('<[^>]+>', '', text);
  /*
   * Remove footnote
   * TODO; support footnote in advanced model
   */
  text = utils.replaceAll('\{\{refn[^\}\}]*?\}\}', '', text);

  /*
   * Merge order, bulleted, unbulleted, Pagelist
   * list items to one line
   */
  var lists = text.match(/\{\{(order|bulleted|unbulleted|Pagelist)(.*\n)*?\}\}/g);
  if (lists && lists.length) {
    lists.forEach(function(l) {
      text = text.replace(l, l.replace('{{', '').replace('}}', '')
                              .replace(/(order|bulleted|unbulleted)\slist\n\|/g, '')
                              .split('\n|').join(', '));
    });
  }

  /*
   * Parse URL
   */
  lists = text.match(/\{\{(URL)(.*)\}\}/g);
  if (lists && lists.length) {
    lists.forEach(function(l) {
      var tmp = l.replace('{{', '').replace('}}', '').split('|');
      text = (tmp && tmp.length > 0) ? text.replace(l, tmp[tmp.length - 1]) : text;
    });
  }

  /*
   * Parse Start date
   */
  lists = text.match(/\{\{(Start\sdate)(.*)\}\}/g);
  if (lists && lists.length) {
    lists.forEach(function(l) {
      var tmp = l.replace('{{', '').replace('}}', '').split('|');
      /* Pop first element: 'Start date' */
      tmp.shift();
      text = (tmp) ? text.replace(l, tmp.join('/')) : text;
    });
  }

  /*****************************
   * Analyze each line of text *
   *****************************/

  var result = {};
  text.split('\n|').forEach(function(item) {
    /*
     * FIXME: Each item is not always seperated by ' = ',
     *        sometimes it is ' =', '= ', etc.
     *        It's not possible to split them by simply using '=',
     *        because the item might contains several '=',
     *        like: 'students = 300 + 600 = 900'
     */
    var itemIndex = item.indexOf('=');
    if (itemIndex != -1) {
      var item_name = item.substr(0, itemIndex).trim();
      var item_content = item.substr(itemIndex + 1).trim().split('\n')[0];

      /*
       * Extract all simple texts inside '[[ ]]'
       * such as [[France]], [[Language French|French]], etc.
       */
      var find = item_content.match(/\[\[.*?\]\]/g);
      if (find) {
        find.forEach(function(substring) {
          var barestring = substring.replace('[[', '').replace(']]', '');
          var arr = barestring.split('|');
          /**
           * TODO: support link.
           * Reference: https://en.wikipedia.org/wiki/Help:Wiki_markup#Links_and_URLs
           */
          item_content = item_content.replace(substring, arr[arr.length - 1]);
        });
      }

      /*
       * Remove font style
       * {{fake clarify}}
       * {{fake citation needed}}
       * {{fake elucidate}}
       * {{fake heading}}
       * {{fake notes and references}}
       * {{dummy ref}}
       * {{dummy backlink}}
       * {{dummy footnote}}
       * {{break}}
       * {{break|5}}
       * {{clear}}
       * {{clear|left}}
       * {{clear|right}}
       * {{plainlist}}
       * {{startflatlist}}
       * {{flatlist}}
       * {{hlist|first item|second item|third item|...}}
       * {{bulleted list |item1 |item2 |...}}
       * {{pagelist}}
       * {{nowrap}}
       * {{italics}}
       * {{smallcaps|small caps}}
       * {{pad|4.0em}}
       */
      while (item_content.indexOf('{{nowrap|') !== -1) {
        item_content = item_content.replace('{{nowrap|', '');
        item_content = item_content.replace('}}', '');
      }

      while (item_content.indexOf('{{small|') !== -1) {
        item_content = item_content.replace('{{small|', '');
        item_content = item_content.replace('}}', '');
      }

      if (item_content.indexOf('{{native') !== -1) {
        find = item_content.match(/\{\{native[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          item_content = item_content.replace(substring, substring.split('|')[2]);
        });
      }

      /* Remove simple vertical list tag */
      if (item_content.indexOf('{{vunblist') !== -1 &&
          item_content.split('{{').length < 3) {

        find = item_content.match(/\{\{vunblist[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          var tmp = substring.split('|');
          tmp.shift();
          item_content = item_content.replace(substring, tmp.join(',').replace('}}', ''));
        });
      }

      /* Remove horizon list tag */
      if (item_content.indexOf('{{hlist') !== -1) {
        find = item_content.match(/\{\{hlist[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          var tmp = substring.split('|');
          tmp.shift();
          item_content = item_content.replace(substring, tmp.join(',').replace('}}', ''));
        });
      }

      /* Remove efn tag */
      if (item_content.indexOf('{{efn') !== -1) {
        find = item_content.match(/\{\{efn[^\}\}]*?\}\}/g);
        find && find.forEach(function(substring) {
          item_content = item_content.replace(substring, '');
        });
      }

      item_content = utils.replaceAll('&nbsp', ' ', item_content);
      item_content = utils.replaceAll('\n\}\}', '', item_content);
      result[item_name] = item_content;
    }
  });

  callback(null, JSON.stringify(result));
  return;
};
<|endoftext|>


<commit_before>CONFIG = {
    plex: "javascript:%20var%20s=document.createElement(%22script%22);s.type=%22text/javascript%22;s.src=%22https://my.plexapp.com/queue/bookmarklet_payload?uid=819f10b976818604%22;var%20h=document.getElementsByTagName(%22head%22)%5B0%5D;h.appendChild(s);void(0);",
    pocket: "javascript:(function()%7BISRIL_H='edaa';PKT_D='getpocket.com';ISRIL_SCRIPT=document.createElement('SCRIPT');ISRIL_SCRIPT.type='text/javascript';ISRIL_SCRIPT.src='http://'+PKT_D+'/b/r.js';document.getElementsByTagName('head')%5B0%5D.appendChild(ISRIL_SCRIPT)%7D)();",
    builtwith: "javascript:void(location.href='http://builtwith.com?'+location.href)",
    whois: "javascript:void(location.href='https://who.is/whois/'+location.host)",
    tdfw: "javascript:(function()%7Bjavascript:var%20s%3Ddocument.createElement(%27script%27)%3Bs.setAttribute(%27src%27,%27https://nthitz.github.io/turndownforwhatjs/tdfw.js%27)%3Bdocument.body.appendChild(s)%3B%7D)()%3B"
}
<commit_msg>add semicolon<commit_after>CONFIG = {
    plex: "javascript:%20var%20s=document.createElement(%22script%22);s.type=%22text/javascript%22;s.src=%22https://my.plexapp.com/queue/bookmarklet_payload?uid=819f10b976818604%22;var%20h=document.getElementsByTagName(%22head%22)%5B0%5D;h.appendChild(s);void(0);",
    pocket: "javascript:(function()%7BISRIL_H='edaa';PKT_D='getpocket.com';ISRIL_SCRIPT=document.createElement('SCRIPT');ISRIL_SCRIPT.type='text/javascript';ISRIL_SCRIPT.src='http://'+PKT_D+'/b/r.js';document.getElementsByTagName('head')%5B0%5D.appendChild(ISRIL_SCRIPT)%7D)();",
    builtwith: "javascript:void(location.href='http://builtwith.com?'+location.href)",
    whois: "javascript:void(location.href='https://who.is/whois/'+location.host)",
    tdfw: "javascript:(function()%7Bjavascript:var%20s%3Ddocument.createElement(%27script%27)%3Bs.setAttribute(%27src%27,%27https://nthitz.github.io/turndownforwhatjs/tdfw.js%27)%3Bdocument.body.appendChild(s)%3B%7D)()%3B"
};
<|endoftext|>


<commit_before>var utils        = require("./utils"),
    GrammarError = require("./grammar-error");

module.exports = {
  /*
   * Compiler passes.
   *
   * Each pass is a function that is passed the AST. It can perform checks on it
   * or modify it as needed. If the pass encounters a semantic error, it throws
   * |PEG.GrammarError|.
   */
  passes: {
    check: {
      reportUnusedRules:     require("./compiler/passes/report-unused-rules"),
      reportOverridingRules: require("./compiler/passes/report-overriding-rules"),
      reportMissingRules:    require("./compiler/passes/report-missing-rules"),
      reportLeftRecursion:   require("./compiler/passes/report-left-recursion")
    },
    transform: {
      removeProxyRules:      require("./compiler/passes/remove-proxy-rules")
    },
    generate: {
      generateBytecode:      require("./compiler/passes/generate-bytecode"),
      generateJavascript:    require("./compiler/passes/generate-javascript")
    }
  },

  /*
   * Generates a parser from a specified grammar AST. Throws |PEG.GrammarError|
   * if the AST contains a semantic error. Note that not all errors are detected
   * during the generation and some may protrude to the generated parser and
   * cause its malfunction.
   */
  compile: function(ast, passes) {
    var options = arguments.length > 2 ? utils.clone(arguments[2]) : {},
        stage,
        problems = [],
        errors = 0,
        collector = {
          emitFatalError: function() {
            throw utils.construct(GrammarError, arguments);
          },
          emitError: function() {
            ++errors;
            problems.push(['error'].concat(Array.prototype.slice.call(arguments, 0)));
          },
          emitWarning: function() {
            problems.push(['warning'].concat(Array.prototype.slice.call(arguments, 0)));
          },
          emitInfo: function() {
            problems.push(['info'].concat(Array.prototype.slice.call(arguments, 0)));
          },
        };

    /*
     * Extracted into a function just to silence JSHint complaining about
     * creating functions in a loop.
     */
    function runPass(pass) {
      pass(ast, options);
    }
    function chain(f1, f2) {
      return function() {
        f1.apply(null, arguments);
        f2.apply(null, arguments);
      }
    }

    utils.defaults(options, {
      allowedStartRules:  [ast.rules[0].name],
      cache:              false,
      optimize:           "speed",
      output:             "parser"
    });
    var userCollector = options.collector;
    if (userCollector) {
      for (var f in userCollector) {
        if (userCollector.hasOwnProperty(f) && collector.hasOwnProperty(f)) {
          userCollector[f] = chain(userCollector[f], collector[f]);
        }
      }
    } else {
      options.collector = collector;
    }

    for (stage in passes) {
      if (passes.hasOwnProperty(stage)) {
        // Clear array.
        problems.length = 0;
        errors = 0;
        utils.each(passes[stage], runPass);
        // Collect all errors by stage
        if (errors !== 0) {
          throw new GrammarError("Stage "+stage+" contains errors.", problems);
        }
      }
    }
    switch (options.output) {
      case "parser": return eval(ast.code);
      case "source": return ast.code;
    }
  }
};
<commit_msg>Fix incorrect pass name in compiler.<commit_after>var utils        = require("./utils"),
    GrammarError = require("./grammar-error");

module.exports = {
  /*
   * Compiler passes.
   *
   * Each pass is a function that is passed the AST. It can perform checks on it
   * or modify it as needed. If the pass encounters a semantic error, it throws
   * |PEG.GrammarError|.
   */
  passes: {
    check: {
      reportUnusedRules:    require("./compiler/passes/report-unused-rules"),
      reportRedefinedRules: require("./compiler/passes/report-redefined-rules"),
      reportMissingRules:   require("./compiler/passes/report-missing-rules"),
      reportLeftRecursion:  require("./compiler/passes/report-left-recursion")
    },
    transform: {
      removeProxyRules:     require("./compiler/passes/remove-proxy-rules")
    },
    generate: {
      generateBytecode:     require("./compiler/passes/generate-bytecode"),
      generateJavascript:   require("./compiler/passes/generate-javascript")
    }
  },

  /*
   * Generates a parser from a specified grammar AST. Throws |PEG.GrammarError|
   * if the AST contains a semantic error. Note that not all errors are detected
   * during the generation and some may protrude to the generated parser and
   * cause its malfunction.
   */
  compile: function(ast, passes) {
    var options = arguments.length > 2 ? utils.clone(arguments[2]) : {},
        stage,
        problems = [],
        errors = 0,
        collector = {
          emitFatalError: function() {
            throw utils.construct(GrammarError, arguments);
          },
          emitError: function() {
            ++errors;
            problems.push(['error'].concat(Array.prototype.slice.call(arguments, 0)));
          },
          emitWarning: function() {
            problems.push(['warning'].concat(Array.prototype.slice.call(arguments, 0)));
          },
          emitInfo: function() {
            problems.push(['info'].concat(Array.prototype.slice.call(arguments, 0)));
          },
        };

    /*
     * Extracted into a function just to silence JSHint complaining about
     * creating functions in a loop.
     */
    function runPass(pass) {
      pass(ast, options);
    }
    function chain(f1, f2) {
      return function() {
        f1.apply(null, arguments);
        f2.apply(null, arguments);
      }
    }

    utils.defaults(options, {
      allowedStartRules:  [ast.rules[0].name],
      cache:              false,
      optimize:           "speed",
      output:             "parser"
    });
    var userCollector = options.collector;
    if (userCollector) {
      for (var f in userCollector) {
        if (userCollector.hasOwnProperty(f) && collector.hasOwnProperty(f)) {
          userCollector[f] = chain(userCollector[f], collector[f]);
        }
      }
    } else {
      options.collector = collector;
    }

    for (stage in passes) {
      if (passes.hasOwnProperty(stage)) {
        // Clear array.
        problems.length = 0;
        errors = 0;
        utils.each(passes[stage], runPass);
        // Collect all errors by stage
        if (errors !== 0) {
          throw new GrammarError("Stage "+stage+" contains errors.", problems);
        }
      }
    }
    switch (options.output) {
      case "parser": return eval(ast.code);
      case "source": return ast.code;
    }
  }
};
<|endoftext|>


<commit_before>// ==================================
// Part 1 - incoming messages, look for type
// ==================================
var ibc = {};
var chaincode = {};
var async = require('async');

module.exports.setup = function(sdk, cc){
	ibc = sdk;
	chaincode = cc;
};

module.exports.process_msg = function(ws, data){
	console.log('karachain: process message ',data.type);
	if(data.v === 1){																						//only look at messages for part 1
	    if(data.type == 'createsinger'){
			console.log('karachain: create a song');
			if(data.name && data.color && data.size && data.user){
				chaincode.invoke.init_singer([data.name, data.color, data.size, data.user], cb_invoked);	//create a new singer
			}
		}
		else if(data.type == 'createperformance'){
			console.log('karachain: create performance - singer singing song');
			var qr_png = qr.image('performance', { type: 'png' });
			var songId = "sb1234567";
			if(data.name ){
				chaincode.invoke.create_song([songId, qr_png], cb_invoked);	//create a new song
			}
			chaincode.query.read([songId], cb_query_response);
		}
		else if(data.type == 'createvisitor'){
			console.log('karachain: create visitor');

		}
		else if(data.type == 'createeventmgr'){
			console.log('karachain: create event mgr');

		}
		else if(data.type == 'voteperformance'){
			console.log('karachain: vote performance');

		}
		else if(data.type == 'getmyperformances'){
			console.log('karachain: get my performances');
			chaincode.query.read(['_allsongsindex'], cb_got_index);

		}
		else if(data.type == 'getmyoffers'){
			console.log('karachain: get my offers');

		}
		else if(data.type == 'acceptoffer'){
			console.log('karachain: accept offer');

		}
		else if(data.type == 'transfer'){
			console.log('transfering msg');

		}
		else if(data.type == 'remove'){
			console.log('removing msg');

		}
		else if(data.type == 'chainstats'){
			console.log('chainstats msg');
			ibc.chain_stats(cb_chainstats);
		}
	}

	//got the songs index, lets get each song
	function cb_got_index(e, index){
		if(e != null) console.log('[ws error] did not get song index:', e);
		else{
			try{
				var json = JSON.parse(index);
				var keys = Object.keys(json);
				var concurrency = 1;

				//serialized version
				async.eachLimit(keys, concurrency, function(key, cb) {
					console.log('!', json[key]);
					chaincode.query.read([json[key]], function(e, song) {
						if(e != null) console.log('[ws error] did not get song:', e);
						else {
							if(song) sendMsg({msg: 'songs', e: e, song: JSON.parse(song)});
							cb(null);
						}
					});
				}, function() {
					sendMsg({msg: 'action', e: e, status: 'finished'});
				});
			}
			catch(e){
				console.log('[ws error] could not parse response', e);
			}
		}
	}

	function cb_invoked(e, a){
		console.log('response: ', e, a);
	}
	//cc query callback
	function cb_query_response(e, resonse){
		if(e != null) {
			console.log('[query error] did not get query response:', e);
		}else{
			if (resonse != null){
				console.log('[query resonse] got query response:', response);
			}
		}
	}
	//call back for getting the blockchain stats, lets get the block stats now
	function cb_chainstats(e, chain_stats){
		if(chain_stats && chain_stats.height){
			chain_stats.height = chain_stats.height - 1;								//its 1 higher than actual height
			var list = [];
			for(var i = chain_stats.height; i >= 1; i--){								//create a list of heights we need
				list.push(i);
				if(list.length >= 8) break;
			}
			list.reverse();																//flip it so order is correct in UI
			async.eachLimit(list, 1, function(block_height, cb) {						//iter through each one, and send it
				ibc.block_stats(block_height, function(e, stats){
					if(e == null){
						stats.height = block_height;
						sendMsg({msg: 'chainstats', e: e, chainstats: chain_stats, blockstats: stats});
					}
					cb(null);
				});
			}, function() {
			});
		}
	}
	//send a message, socket might be closed...
	function sendMsg(json){
		if(ws){
			try{
				ws.send(JSON.stringify(json));
			}
			catch(e){
				console.log('[ws error] could not send msg', e);
			}
		}
	}
};<commit_msg>update query callback<commit_after>// ==================================
// Part 1 - incoming messages, look for type
// ==================================
var ibc = {};
var chaincode = {};
var async = require('async');

module.exports.setup = function(sdk, cc){
	ibc = sdk;
	chaincode = cc;
};

module.exports.process_msg = function(ws, data){
	console.log('karachain: process message ',data.type);
	if(data.v === 1){																						//only look at messages for part 1
	    if(data.type == 'createsinger'){
			console.log('karachain: create a song');
			if(data.name && data.color && data.size && data.user){
				chaincode.invoke.init_singer([data.name, data.color, data.size, data.user], cb_invoked);	//create a new singer
			}
		}
		else if(data.type == 'createperformance'){
			console.log('karachain: create performance - singer singing song');
			var qr_png = qr.image('performance', { type: 'png' });
			var songId = "sb1234567";
			if(data.name ){
				chaincode.invoke.create_song([songId, qr_png], cb_invoked);	//create a new song
			}
			console.log('karachain: create performance - reading song back ',sondId);
			chaincode.query.read([songId], cb_query_response);
		}
		else if(data.type == 'createvisitor'){
			console.log('karachain: create visitor');

		}
		else if(data.type == 'createeventmgr'){
			console.log('karachain: create event mgr');

		}
		else if(data.type == 'voteperformance'){
			console.log('karachain: vote performance');

		}
		else if(data.type == 'getmyperformances'){
			console.log('karachain: get my performances');
			chaincode.query.read(['_allsongsindex'], cb_got_index);

		}
		else if(data.type == 'getmyoffers'){
			console.log('karachain: get my offers');

		}
		else if(data.type == 'acceptoffer'){
			console.log('karachain: accept offer');

		}
		else if(data.type == 'transfer'){
			console.log('transfering msg');

		}
		else if(data.type == 'remove'){
			console.log('removing msg');

		}
		else if(data.type == 'chainstats'){
			console.log('chainstats msg');
			ibc.chain_stats(cb_chainstats);
		}
	}

	//got the songs index, lets get each song
	function cb_got_index(e, index){
		if(e != null) console.log('[ws error] did not get song index:', e);
		else{
			try{
				var json = JSON.parse(index);
				var keys = Object.keys(json);
				var concurrency = 1;

				//serialized version
				async.eachLimit(keys, concurrency, function(key, cb) {
					console.log('!', json[key]);
					chaincode.query.read([json[key]], function(e, song) {
						if(e != null) console.log('[ws error] did not get song:', e);
						else {
							if(song) sendMsg({msg: 'songs', e: e, song: JSON.parse(song)});
							cb(null);
						}
					});
				}, function() {
					sendMsg({msg: 'action', e: e, status: 'finished'});
				});
			}
			catch(e){
				console.log('[ws error] could not parse response', e);
			}
		}
	}

	function cb_invoked(e, a){
		console.log('response: ', e, a);
	}
	//cc query callback
	function cb_query_response(e, resonse){
		if(e != null) {
			console.log('[query error] did not get query response:', e);
		}else{
			if (resonse != null){
				console.log('[query resonse] got query response:', response);
			}else{
				console.log('[query resonse] NULL query response:');
			}
		}
	}
	//call back for getting the blockchain stats, lets get the block stats now
	function cb_chainstats(e, chain_stats){
		if(chain_stats && chain_stats.height){
			chain_stats.height = chain_stats.height - 1;								//its 1 higher than actual height
			var list = [];
			for(var i = chain_stats.height; i >= 1; i--){								//create a list of heights we need
				list.push(i);
				if(list.length >= 8) break;
			}
			list.reverse();																//flip it so order is correct in UI
			async.eachLimit(list, 1, function(block_height, cb) {						//iter through each one, and send it
				ibc.block_stats(block_height, function(e, stats){
					if(e == null){
						stats.height = block_height;
						sendMsg({msg: 'chainstats', e: e, chainstats: chain_stats, blockstats: stats});
					}
					cb(null);
				});
			}, function() {
			});
		}
	}
	//send a message, socket might be closed...
	function sendMsg(json){
		if(ws){
			try{
				ws.send(JSON.stringify(json));
			}
			catch(e){
				console.log('[ws error] could not send msg', e);
			}
		}
	}
};<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */
"use strict";

const endpoint = require('kronos-endpoint'),
	Service = require('./Service');

/**
 * Log reciving service
 */
class ServiceLogger extends Service {

	static get name() {
		return "logger";
	}

	get type() {
		return ServiceLogger.name;
	}

	constructor(config, owner) {
		super(config, owner);

		this.addEndpoint(new endpoint.ReceiveEndpoint('log', this)).receive = entry => {
			console.log(JSON.stringify(entry));
			Promise.resolve();
		};
	}

	get autostart() {
		return true;
	}
}

module.exports = ServiceLogger;
<commit_msg>fix: handle stringify excetion in logger<commit_after>/* jslint node: true, esnext: true */

'use strict';

const endpoint = require('kronos-endpoint'),
	Service = require('./Service');

/**
 * Log reciving service
 */
class ServiceLogger extends Service {

	static get name() {
		return 'logger';
	}

	get type() {
		return ServiceLogger.name;
	}

	constructor(config, owner) {
		super(config, owner);

		this.addEndpoint(new endpoint.ReceiveEndpoint('log', this)).receive = entry => {
			try {
				console.log(JSON.stringify(entry));
			} catch (e) {
				console.log(`Unable to log entry with the following keys: ${Object.keys(entry)} ${e}`);
				return Promise.reject(e);
			}
			return Promise.resolve();
		};
	}

	get autostart() {
		return true;
	}
}

module.exports = ServiceLogger;
<|endoftext|>


<commit_before>/**
 * Created by Obscurity on 2017/1/21.
 */

(function ($) {

    'use strict';

    var large = {
        size: "large",
        renderText: false,
        shares: [{
            platform: "qzone",
            icon: "https://qzonestyle.gtimg.cn/ac/qzone_v5/app/app_share/qz_logo.png",
            text: "QQ空间"
        }, {
            platform: "qq"
        }, {
            platform: "wechat",
            icon: "https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_appwx_logo.png",
            text: "微信"
        }, {
            platform: "sinaweibo",
            icon: "https://img.t.sinajs.cn/t4/appstyle/widget/images/shareButton/share_icon_mini.png?id=1375775002754",
            text: "新浪微博"
        }, {
            platform: "douban",
            icon: "https://img3.doubanio.com/pics/fw2douban_s.png",
            text: "豆瓣"
        }]
    };

    var medium = {
        size: "small",
        renderText: false,
        shares: [{
            platform: "qzone",
            icon: "https://qzonestyle.gtimg.cn/ac/qzone_v5/app/app_share/qz_logo.png",
            text: "QQ空间"
        }, {
            platform: "qq"
        }, {
            platform: "wechat",
            icon: "https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_appwx_logo.png",
            text: "微信"
        }, {
            platform: "sinaweibo",
            icon: "https://img.t.sinajs.cn/t4/appstyle/widget/images/shareButton/share_icon_mini.png?id=1375775002754",
            text: "新浪微博"
        }, {
            platform: "douban",
            icon: "https://img3.doubanio.com/pics/fw2douban_s.png",
            text: "豆瓣"
        }]
    };

    var small = {
        size: "small",
        renderText: false,
        shares: [{
            platform: "qzone",
            icon: "https://qzonestyle.gtimg.cn/ac/qzone_v5/app/app_share/qz_logo.png",
            text: "QQ空间"
        }, {
            platform: "qq"
        }, {
            platform: "wechat",
            icon: "https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_appwx_logo.png",
            text: "微信"
        }, {
            platform: "sinaweibo",
            icon: "https://img.t.sinajs.cn/t4/appstyle/widget/images/shareButton/share_icon_mini.png?id=1375775002754",
            text: "新浪微博"
        }, {
            platform: "douban",
            icon: "https://img3.doubanio.com/pics/fw2douban_s.png",
            text: "豆瓣"
        }]
    };

    var sizes = ["small", "medium", "large"];

    var defaults = medium;

    var hShare = function (options) {

        var url = encodeURIComponent(location.href);
        var title = encodeURIComponent(document.title);

        var opts = $.extend({}, defaults, options);

        var _render = function (platform, icon, text, customize, html) {
            if (customize) {
                return html;
            }
            else {
                switch(platform) {
                    case "qzone":
                        return $(_renderQzone(icon, text));
                        break;
                    case "wechat":
                        var wechatEntry = $(_renderWechat(icon, text));
                        wechatEntry.on('click', _renderWechatQECode);
                        return wechatEntry;
                        break;
                    case "sinaweibo":
                        return $(_renderSinaWeibo(icon, text));
                        break;
                    case "renren":
                        return $(_renderRenren(icon, text));
                        break;
                    case "douban":
                        return $(_renderDouban(icon, text));
                        break;
                    default:
                        throw Error("invalid platform");
                }
            }
        };

        var _renderWechatQECode = function () {
            var startX = $(this).offset().left + $(this).width;
            var startY = $(this).offset().top + $(this).height;
            var width = 50, height = 50;
            var containerWidth = 70, containerHeight = 70;
            var padding = (containerHeight - height) / 2;
            var panelStyle = "position: absolute; left: " + startX + "px; top: " + startY + "px; width: " + containerWidth + "; height: " + containerHeight + "px;";
            var imageStyle = "position: absolute; left: " + (startX + padding) +  + "px; top: " + (startY + padding) + "px; width: " + width + "; height: " + height + "px;";
            var panel = $("

");
            console.log(panel);
            panel.on('blur', function () {
                $(this).remove();
            });
            $("body").append(panel);
        };

        var _renderWechat = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "<\/a>";
            }
            else {
                return "<\/a>";
            }
        };

        var _renderQzone = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "<\/a>";
            }
            else {
                return "<\/a>";
            }
        };

        var _renderDouban = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "<a class='hshare hshare-" + size + "'  href=\"javascript:void(function(){var w=window,d=document,e=encodeURIComponent,s1=window.getSelection,s2=d.getSelection,s3=d.selection,s=s1?s1():s2?s2():s3?s3.createRange().text:'',r='https://www.douban.com/recommend/?url='+e(w.location.href)+'&title='+e(d.title)+'&sel='+e(s)+'&v=1',w=450,h=330,x=function(){if(!window.open(r,'douban','toolbar=0,resizable=1,scrollbars=yes,status=1,width='+w+',height='+h+',left='+(screen.width-w)/2+',top='+(screen.height-h)/2))location.href=r+'&r=1'};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})()\">" + text + "";
            }
            else {
                return "<a class='hshare hshare-" + size + "'  href=\"javascript:void(function(){var w=window,d=document,e=encodeURIComponent,s1=window.getSelection,s2=d.getSelection,s3=d.selection,s=s1?s1():s2?s2():s3?s3.createRange().text:'',r='https://www.douban.com/recommend/?url='+e(w.location.href)+'&title='+e(d.title)+'&sel='+e(s)+'&v=1',w=450,h=330,x=function(){if(!window.open(r,'douban','toolbar=0,resizable=1,scrollbars=yes,status=1,width='+w+',height='+h+',left='+(screen.width-w)/2+',top='+(screen.height-h)/2))location.href=r+'&r=1'};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})()\">";
            }
        };

        var _renderRenren = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "";
            }
            else {
                return "";
            }
        };

        var _renderSinaWeibo = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "";
            }
            else {
                return "";
            }
        };

        return this.each(function () {
            var $this = $(this);

            var platforms = opts.shares;

            platforms.forEach(function (plt) {
                var platform = plt.platform || "";
                var icon = plt.icon || "";
                var text = plt.text || "";
                var isCustomized = !!plt.customize;
                var customize = plt.customize || "";
                $this.append($(_render(platform, icon, text, isCustomized, customize)));
            });

        });
    };

    $.fn.extend({
        hshare: hShare
    });

})(jQuery);<commit_msg>增加了一个demo<commit_after>/**
 * Created by Obscurity on 2017/1/21.
 */

(function ($) {

    'use strict';

    var large = {
        size: "large",
        renderText: false,
        shares: [{
            platform: "qzone",
            icon: "https://qzonestyle.gtimg.cn/ac/qzone_v5/app/app_share/qz_logo.png",
            text: "QQ空间"
        }, {
            platform: "qq"
        }, {
            platform: "wechat",
            icon: "https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_appwx_logo.png",
            text: "微信"
        }, {
            platform: "sinaweibo",
            icon: "https://img.t.sinajs.cn/t4/appstyle/widget/images/shareButton/share_icon_mini.png?id=1375775002754",
            text: "新浪微博"
        }, {
            platform: "douban",
            icon: "https://img3.doubanio.com/pics/fw2douban_s.png",
            text: "豆瓣"
        }]
    };

    var medium = {
        size: "small",
        renderText: false,
        shares: [{
            platform: "qzone",
            icon: "https://qzonestyle.gtimg.cn/ac/qzone_v5/app/app_share/qz_logo.png",
            text: "QQ空间"
        }, {
            platform: "qq"
        }, {
            platform: "wechat",
            icon: "https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_appwx_logo.png",
            text: "微信"
        }, {
            platform: "sinaweibo",
            icon: "https://img.t.sinajs.cn/t4/appstyle/widget/images/shareButton/share_icon_mini.png?id=1375775002754",
            text: "新浪微博"
        }, {
            platform: "douban",
            icon: "https://img3.doubanio.com/pics/fw2douban_s.png",
            text: "豆瓣"
        }]
    };

    var small = {
        size: "small",
        renderText: false,
        shares: [{
            platform: "qzone",
            icon: "https://qzonestyle.gtimg.cn/ac/qzone_v5/app/app_share/qz_logo.png",
            text: "QQ空间"
        }, {
            platform: "qq"
        }, {
            platform: "wechat",
            icon: "https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_appwx_logo.png",
            text: "微信"
        }, {
            platform: "sinaweibo",
            icon: "https://img.t.sinajs.cn/t4/appstyle/widget/images/shareButton/share_icon_mini.png?id=1375775002754",
            text: "新浪微博"
        }, {
            platform: "douban",
            icon: "https://img3.doubanio.com/pics/fw2douban_s.png",
            text: "豆瓣"
        }]
    };

    var sizes = ["small", "medium", "large"];

    var defaults = medium;

    var hShare = function (options) {

        var url = encodeURIComponent(location.href);
        var title = encodeURIComponent(document.title);

        var opts = $.extend({}, defaults, options);

        var _render = function (platform, icon, text, customize, html) {
            if (customize) {
                return html;
            }
            else {
                switch(platform) {
                    case "qzone":
                        return $(_renderQzone(icon, text));
                        break;
                    case "wechat":
                        var wechatEntry = $(_renderWechat(icon, text));
                        wechatEntry.on('click', _renderWechatQECode);
                        return wechatEntry;
                        break;
                    case "sinaweibo":
                        return $(_renderSinaWeibo(icon, text));
                        break;
                    case "renren":
                        return $(_renderRenren(icon, text));
                        break;
                    case "douban":
                        return $(_renderDouban(icon, text));
                        break;
                    default:
                        throw Error("invalid platform");
                }
            }
        };

        var _renderWechatQECode = function () {
            var startX = $(this).offset().left + $(this).width();
            var startY = $(this).offset().top + $(this).height();
            var width = 50, height = 50;
            var containerWidth = 70, containerHeight = 70;
            var padding = (containerHeight - height) / 2;
            var panelStyle = "position: absolute; left: " + startX + "px; top: " + startY + "px; width: " + containerWidth + "; height: " + containerHeight + "px;";
            var imageStyle = "position: absolute; left: " + (startX + padding) +  + "px; top: " + (startY + padding) + "px; width: " + width + "; height: " + height + "px;";
            var panel = $("

");
            console.log(panel);
            panel.on('blur', function () {
                $(this).remove();
            });
            $("body").append(panel);
        };

        var _renderWechat = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "<\/a>";
            }
            else {
                return "<\/a>";
            }
        };

        var _renderQzone = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "<\/a>";
            }
            else {
                return "<\/a>";
            }
        };

        var _renderDouban = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "<a class='hshare hshare-" + size + "'  href=\"javascript:void(function(){var w=window,d=document,e=encodeURIComponent,s1=window.getSelection,s2=d.getSelection,s3=d.selection,s=s1?s1():s2?s2():s3?s3.createRange().text:'',r='https://www.douban.com/recommend/?url='+e(w.location.href)+'&title='+e(d.title)+'&sel='+e(s)+'&v=1',w=450,h=330,x=function(){if(!window.open(r,'douban','toolbar=0,resizable=1,scrollbars=yes,status=1,width='+w+',height='+h+',left='+(screen.width-w)/2+',top='+(screen.height-h)/2))location.href=r+'&r=1'};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})()\">" + text + "";
            }
            else {
                return "<a class='hshare hshare-" + size + "'  href=\"javascript:void(function(){var w=window,d=document,e=encodeURIComponent,s1=window.getSelection,s2=d.getSelection,s3=d.selection,s=s1?s1():s2?s2():s3?s3.createRange().text:'',r='https://www.douban.com/recommend/?url='+e(w.location.href)+'&title='+e(d.title)+'&sel='+e(s)+'&v=1',w=450,h=330,x=function(){if(!window.open(r,'douban','toolbar=0,resizable=1,scrollbars=yes,status=1,width='+w+',height='+h+',left='+(screen.width-w)/2+',top='+(screen.height-h)/2))location.href=r+'&r=1'};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})()\">";
            }
        };

        var _renderRenren = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "";
            }
            else {
                return "";
            }
        };

        var _renderSinaWeibo = function (icon, text) {
            var size = sizes.includes(opts.size) ? opts.size : "medium";
            if (opts.renderText) {
                return "" + text + "";
            }
            else {
                return "";
            }
        };

        return this.each(function () {
            var $this = $(this);

            var platforms = opts.shares;

            platforms.forEach(function (plt) {
                var platform = plt.platform || "";
                var icon = plt.icon || "";
                var text = plt.text || "";
                var isCustomized = !!plt.customize;
                var customize = plt.customize || "";
                $this.append($(_render(platform, icon, text, isCustomized, customize)));
            });

        });
    };

    $.fn.extend({
        hshare: hShare
    });

})(jQuery);<|endoftext|>


<commit_before>/**
 * @license
 * Copyright (c) 2015 MediaMath Inc. All rights reserved.
 * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt

*/

(function (scope) {
	scope.ListItem = Polymer({

		is: "strand-list-item",

		behaviors: [
			StrandTraits.Resolvable,
			StrandTraits.DomMutable,
			StrandTraits.Refable
		],

		properties: {
			selected: {
				type: Boolean,
				value: false,
				reflectToAttribute: true,
				notify: true
			},
			highlighted: {
				type: Boolean,
				value: false,
				reflectToAttribute: true,
				notify: true,
			},
			highlight:{
				type:String,
				value:"",
				notify:true,
				observer:"_highlightChanged"
			},
			observeSubtree: {
				value:true
			},
			observeCharacterData: {
				value:true
			},
			title: {
				type:String,
				value:null,
				reflectToAttribute: true
			},
			value: {
				type: String,
				value: false
			}
		},

		listeners:{
			"added":"_updateTitleHandler",
			"removed":"_updateTitleHandler",
			"modified":"_updateTitleHandler",
			"mouseover":"_updateTitleHandler"
		},

		attached: function () {
			this.debounce("update-title",this.updateTitle,0);
		},

		_updateTitleHandler: function() {
			this.debounce("update-title",this.updateTitle,0);
		},

		_highlightChanged: function() {
			if (this.highlight && this.highlight.length > 0) {
				var s = this.innerText;
				Polymer.dom(this).innerHTML = s.replace(new RegExp(this.highlight,"ig"),function(orig) {
					return ''+orig+'';
				},'ig');
			} else if (this.innerText && this.innerText.trim()){
				Polymer.dom(this).innerHTML = this.innerText.trim(); //strip any formatting
			}
		},

		updateTitle: function() {
			var m = StrandLib.Measure;
			var computed = m.textWidth(this, this.textContent);
			var actual = m.getBoundingClientRect(this).width;
			if (computed > actual) {
				var txt = this.textContent.trim();
				if (this.title !== txt)
					this.title = txt;
			} else {
				this.title = null;
			}
		}

	});
})(window.Strand = window.Strand || {});
<commit_msg>Hover over strand-list-item to account for L/R padding<commit_after>/**
 * @license
 * Copyright (c) 2015 MediaMath Inc. All rights reserved.
 * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt

*/

(function (scope) {
	scope.ListItem = Polymer({

		is: "strand-list-item",

		behaviors: [
			StrandTraits.Resolvable,
			StrandTraits.DomMutable,
			StrandTraits.Refable
		],

		properties: {
			selected: {
				type: Boolean,
				value: false,
				reflectToAttribute: true,
				notify: true
			},
			highlighted: {
				type: Boolean,
				value: false,
				reflectToAttribute: true,
				notify: true,
			},
			highlight:{
				type:String,
				value:"",
				notify:true,
				observer:"_highlightChanged"
			},
			observeSubtree: {
				value:true
			},
			observeCharacterData: {
				value:true
			},
			title: {
				type:String,
				value:null,
				reflectToAttribute: true
			},
			value: {
				type: String,
				value: false
			}
		},

		listeners:{
			"added":"_updateTitleHandler",
			"removed":"_updateTitleHandler",
			"modified":"_updateTitleHandler",
			"mouseover":"_updateTitleHandler"
		},

		attached: function () {
			this.debounce("update-title",this.updateTitle,0);
		},

		_updateTitleHandler: function() {
			this.debounce("update-title",this.updateTitle,0);
		},

		_highlightChanged: function() {
			if (this.highlight && this.highlight.length > 0) {
				var s = this.innerText;
				Polymer.dom(this).innerHTML = s.replace(new RegExp(this.highlight,"ig"),function(orig) {
					return ''+orig+'';
				},'ig');
			} else if (this.innerText && this.innerText.trim()){
				Polymer.dom(this).innerHTML = this.innerText.trim(); //strip any formatting
			}
		},

		updateTitle: function() {
			var m = StrandLib.Measure;
			var computed = m.textWidth(this, this.textContent);
			var padding = parseInt(getComputedStyle(this).paddingLeft.split('px')[0]) + parseInt(getComputedStyle(this).paddingRight.split('px')[0]);
			var actual = m.getBoundingClientRect(this).width - padding;
			if (computed > actual) {
				var txt = this.textContent.trim();
				if (this.title !== txt)
					this.title = txt;
			} else {
				this.title = null;
			}
		}

	});
})(window.Strand = window.Strand || {});
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Nicolas Lochet Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

module.exports = function (grammar) {
  'use strict'
  if (!('lexicon' in grammar)) throw new Error('Your grammar needs a lexicon section.')

  return function(gloss) {
    var words = gloss.split(/\s+/)
      , res = words.map(word_parser).join(' ')
    return res
  }

  function word_parser(word) { // word
    var morphemes = word.split('-')
    return morphemes.map(morpheme_parser).join(grammar.split_morpheme?'-':'')
  }

  /**
   * m: morpheme
   */
  function morpheme_parser(m) {
    var s = m.split('.') // sequence
      , h = s.shift() // head
      , e = grammar.lexicon[h] // entry

    if (typeof e !== 'undefined') {
      if ('invariant' in e) return e.invariant
      if ('irregular' in e) {
        var irr = s.reduce(function(p,c) { return (c in p) ? p[c] : ('v' in p) ? p.v : undefined },e.irregular)
        if (irr !== undefined) return irr
      }
      return Object.keys(e)
      .filter(function(_){ return _ !== 'irregular'})
      .reduce(function(p,c){
        var r = grammar.rules[c] // rule
        if (typeof r !== 'undefined') {
          var v = e[c]
          if (s.length === 0) return v
          return s.reduce(function(q,d) {
            if ('t' in q && (d in q.t)) {
              var t = rec_rule(q.t[d],q.v)
              if (typeof t === 'object') q.t = t
              else {
                delete q.t
                q.v = t
              }
              return q
            } else if (!(d in q.r)) {
              throw new Error('rule for '+c+' does not contain '+d)
            }
            var z = rec_rule(q.r[d],q.v)
            if (typeof z === 'object') q.t = z
            else q.v = z
            return q
          },{r: r, v: v}).v
        }
        return p
      },h)
    }
  }

  /**
   * Try to find how to apply a rule recursively
   *
   * t: transformation found in grammar
   * v: value to be transformed
   */
  function rec_rule(t,v) {
    if (typeof t === 'function') return t(v)
    if (typeof t === 'string') return parse_string_rule(t,v)
    if (typeof t === 'object') {
      if (t instanceof Array) {
        return (t.reduce(function(p, c) {
          if (!p.f) {
            var w = rec_rule(c,p.v)
            if (p.v !== w) return {v:w, f:true}
          }
          return p
        },{v:v, f:false})).v
      }
      else return t
    }
    return v
  }

  /**
   * Parse a string defined rule and apply it to a value
   *
   * t: transformation definition as a string
   * v: value to be transformed
   */
  function parse_string_rule(t,v) {
    var patterns = [
      { x: /^-([a-z]*)([A-Z]+)([a-z]*)>-([A-Za-z\(\)]*)$/, s: final_transform },
      { x: /^-([a-z]*)>-([a-z]*)$/, s: final_substitution },
      { x: /^>-([a-z]*)$/, s: function(h,e) { return h.replace(/$/, e[1])} }
    ]
    var i = 0, l = patterns.length
    for(;i<l;i+=1) {
      var p = patterns[i]
        , x = try_pattern(p, t, v)
      if (x !== undefined) return x
    }
    return v
  }

  function try_pattern(p, t, h) {
    var e = p.x.exec(t)
    if (e!==null) {
      return p.s(h,e)
    }
    return undefined
  }

  function final_substitution(h,e) {
    return h.replace(new RegExp(e[1]+'$'), e[2])
  }

  function final_transform(h,e) {
    var p = parse_pattern(e[2], true)
      , rx = new RegExp(e[1]+p+e[3]+'$')
      , x = rx.exec(h)
    if (x !== null) return parse_substitution(e[2], x, e[4])
    return undefined
  }

  function parse_pattern(p, isRoot) {
    var ph = grammar.phonemes
    p = p.trim()
    isRoot = typeof isRoot === 'boolean' && isRoot

    if (!/ /.test(p) && p === p.toLowerCase()) {
      return p
    } else if (p.length == 1) {
      if (p in ph) {
        return (isRoot?'(':'')+parse_pattern(ph[p])+(isRoot?')':'')
      } else {
        return p
      }
    } else if (/ /.test(p)) {
      return p.split(' ').map(parse_pattern).join('|')
    } else {
      var _ =(isRoot?'(':'(?:')
      return _+p.split('').map(parse_pattern).join(')'+_)+')'
    }
    return ''
  }

  function parse_substitution(p, x, s) {
    var k = splitred2map(p)
      , a = null
      , rx = /(([a-z])\(([A-Z])\))|([A-Z])|([a-z]+)/g
      , res = x.input.substring(0,x.index)

    while ((a = rx.exec(s)) !== null) {
      if (a[1] !== undefined) {
        var v = x[k[a[3]]]
        if (!(a[2] in grammar.transformations)) throw new Error(a[2]+' is not a valid transformation rule')
        var t = grammar.transformations[a[2]]
        if (!(v in t)) throw new Error('"'+v+'" does not exists in transformation rule "'+a[2]+'": '+ JSON.stringify(t))
        res += t[v]
      }
      if (a[4] !== undefined) {
        var i = k[a[4]]
        res += x[i]
      }
      if (a[5] !== undefined) {
        res+= a[5]
      }
    }

    return res
  }
  function splitred2map(p) {
    console.log(p)
    return p.split('').reduce(function(p, c, i) { p[c]=i+1; return p },{})
  }

}
<commit_msg>fix bug when transforming double phonological entries written in order<commit_after>/*
 * Copyright 2016 Nicolas Lochet Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

module.exports = function (grammar) {
  'use strict'
  if (!('lexicon' in grammar)) throw new Error('Your grammar needs a lexicon section.')

  return function(gloss) {
    var words = gloss.split(/\s+/)
      , res = words.map(word_parser).join(' ')
    return res
  }

  function word_parser(word) { // word
    var morphemes = word.split('-')
    return morphemes.map(morpheme_parser).join(grammar.split_morpheme?'-':'')
  }

  /**
   * m: morpheme
   */
  function morpheme_parser(m) {
    var s = m.split('.') // sequence
      , h = s.shift() // head
      , e = grammar.lexicon[h] // entry

    if (typeof e !== 'undefined') {
      if ('invariant' in e) return e.invariant
      if ('irregular' in e) {
        var irr = s.reduce(function(p,c) { return (c in p) ? p[c] : ('v' in p) ? p.v : undefined },e.irregular)
        if (irr !== undefined) return irr
      }
      return Object.keys(e)
      .filter(function(_){ return _ !== 'irregular'})
      .reduce(function(p,c){
        var r = grammar.rules[c] // rule
        if (typeof r !== 'undefined') {
          var v = e[c]
          if (s.length === 0) return v
          return s.reduce(function(q,d) {
            if ('t' in q && (d in q.t)) {
              var t = rec_rule(q.t[d],q.v)
              if (typeof t === 'object') q.t = t
              else {
                delete q.t
                q.v = t
              }
              return q
            } else if (!(d in q.r)) {
              throw new Error('rule for '+c+' does not contain '+d)
            }
            var z = rec_rule(q.r[d],q.v)
            if (typeof z === 'object') q.t = z
            else q.v = z
            return q
          },{r: r, v: v}).v
        }
        return p
      },h)
    }
  }

  /**
   * Try to find how to apply a rule recursively
   *
   * t: transformation found in grammar
   * v: value to be transformed
   */
  function rec_rule(t,v) {
    if (typeof t === 'function') return t(v)
    if (typeof t === 'string') return parse_string_rule(t,v)
    if (typeof t === 'object') {
      if (t instanceof Array) {
        return (t.reduce(function(p, c) {
          if (!p.f) {
            var w = rec_rule(c,p.v)
            if (p.v !== w) return {v:w, f:true}
          }
          return p
        },{v:v, f:false})).v
      }
      else return t
    }
    return v
  }

  /**
   * Parse a string defined rule and apply it to a value
   *
   * t: transformation definition as a string
   * v: value to be transformed
   */
  function parse_string_rule(t,v) {
    var patterns = [
      { x: /^-([a-z]*)([A-Z]+)([a-z]*)>-([A-Za-z\(\)]*)$/, s: final_transform },
      { x: /^-([a-z]*)>-([a-z]*)$/, s: final_substitution },
      { x: /^>-([a-z]*)$/, s: function(h,e) { return h.replace(/$/, e[1])} }
    ]
    var i = 0, l = patterns.length
    for(;i<l;i+=1) {
      var p = patterns[i]
        , x = try_pattern(p, t, v)
      if (x !== undefined) return x
    }
    return v
  }

  function try_pattern(p, t, h) {
    var e = p.x.exec(t)
    if (e!==null) {
      return p.s(h,e)
    }
    return undefined
  }

  function final_substitution(h,e) {
    return h.replace(new RegExp(e[1]+'$'), e[2])
  }

  function final_transform(h,e) {
    var p = parse_pattern(e[2], true)
      , rx = new RegExp(e[1]+p+e[3]+'$')
      , x = rx.exec(h)
    if (x !== null) return parse_substitution(e[2], x, e[4])
    return undefined
  }

  function parse_pattern(p, isRoot) {
    var ph = grammar.phonemes
    p = p.trim()
    isRoot = typeof isRoot === 'boolean' && isRoot

    if (!/ /.test(p) && p === p.toLowerCase()) {
      return p
    } else if (p.length == 1) {
      if (p in ph) {
        return (isRoot?'(':'')+parse_pattern(ph[p])+(isRoot?')':'')
      } else {
        return p
      }
    } else if (/ /.test(p)) {
      return p.split(' ').map(parse_pattern).join('|')
    } else {
      var _ =(isRoot?'(':'(?:')
      return _+p.split('').map(parse_pattern).join(')'+_)+')'
    }
    return ''
  }

  function parse_substitution(p, x, s) {
    var rks = splitred2map(p)
      , a = null
      , rx = /(([a-z])\(([A-Z])\))|([A-Z])|([a-z]+)/g
      , res = x.input.substring(0,x.index)

    var cks = {}
    while ((a = rx.exec(s)) !== null) {
      if (a[1] !== undefined) {
        var g = countK(cks,a[3])
          , h = findInK(rks, g)
        //console.log('1>',g, h, x[h])
        var v = x[h]
        if (!(a[2] in grammar.transformations)) throw new Error(a[2]+' is not a valid transformation rule')
        var t = grammar.transformations[a[2]]
        if (!(v in t)) throw new Error('"'+v+'" does not exists in transformation rule "'+a[2]+'": '+ JSON.stringify(t))
        res += t[v]
      }
      if (a[4] !== undefined) {
        var i = countK(cks,a[4])
          , j = findInK(rks, i)
        //console.log('2>',g, i, x[i])
        res += x[j]
      }
      if (a[5] !== undefined) {
        res+= a[5]
      }
    }
    return res
  }

  function splitred2map(p) {
    var ks = {}
    return p.split('').map(function(k) { return countK(ks, k).join('') }).reduce(function(p, c, i) { p[c]=i+1; return p },{})
  }

  function findInK(ks, g) {
    var k = g.join('')
    if (k in ks) {
      return ks[k]
    } else {
      return findInK(ks, [g[0], g[1]-1])
    }
  }

  function countK(ks, k) {
    if (k in ks) { ks[k]+=1 } else { ks[k]=0 }
    return [k, ks[k]]
  }
}
<|endoftext|>