<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.

    if (playerMove == "paper" && computerMove == "rock") {
        winner = "player"
        console.log("Player Wins!");}
    else if (playerMove == "paper" && computerMove == "scissors") {
        winner = "computer"
        console.log("Computer Wins");}
    else if (playerMove == "paper" && computerMove == "paper") {
        winner = "tie"
        console.log("It's a tie!");}
    else if (playerMove == "rock" && computerMove == "paper"){
        winner = "player"
        console.log("Player Wins!");}
    else if (playerMove == "rock" && computerMove == "scissors"){
        winner = "computer"
        console.log("Computer Wins");}
    else if (playerMove == "rock" && computerMove == "rock"){
        winner = "tie"
        console.log("It's a tie!");}
    else if (playerMove == "scissors" && computerMove == "paper"){
        winner = "player"
        console.log("Player Wins!");}
    else if (playerMove == "scissors" && computerMove == "rock"){
        winner = "computer"
        console.log("Computer Wins");}
    else if (playerMove == "scissors" && computerMove == "scissors"){
        winner = "tie"
        console.log("It's a tie!");}
    else getInput()

    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>refractored to remove the tie<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.

    if (playerMove == "paper" && computerMove == "rock") {
        winner = "player"
        console.log("Player Wins!");}

    else if (playerMove == "paper" && computerMove == "scissors") {
        winner = "computer"
        console.log("Computer Wins");}

    else if (playerMove == "rock" && computerMove == "paper"){
        winner = "player"
        console.log("Player Wins!");}

    else if (playerMove == "rock" && computerMove == "scissors"){
        winner = "computer"
        console.log("Computer Wins");}

    else if (playerMove == "scissors" && computerMove == "paper"){
        winner = "player"
        console.log("Player Wins!");}

    else if (playerMove == "scissors" && computerMove == "rock"){
        winner = "computer"
        console.log("Computer Wins");}

    else {
        winner = "tie"
        console.log("It's a tie!");}

    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>WDI Fundamentals Unit 4 - http://fundamentals.generalassemb.ly/04_chapter/09_assessment.html<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove === 'rock') && (computerMove === 'paper')) {
    winner = 'computer';
    }
    else if ((playerMove === 'rock') && (computerMove === 'scissors')) {
    winner = 'player';
    }
    else if ((playerMove === 'paper') && (computerMove === 'rock')) {
    winner = 'player';
    }
    else if ((playerMove === 'paper') && (computerMove === 'scissors')) {
    winner = 'computer';
    }
    else if ((playerMove === 'scissors') && (computerMove === 'rock')) {
    winner = 'computer';
    }
    else if ((playerMove === 'scissors') && (computerMove === 'paper')) {
    winner = 'player';
    }
    else if ((playerMove === 'rock') && (computerMove === 'rock')) {
    winner = 'tie';
    }
    else if ((playerMove === 'paper') && (computerMove === 'paper')) {
    winner = 'tie';
    }
    else if ((playerMove === 'scissors') && (computerMove === 'scissors')) {
    winner = 'tie';
    }
    else {
            winner = 'no winner, wrong value has been inputted, the only values playerMove and computerMove can have are rock, paper, and scissors';
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * A RenderState represents the state information for a Node needed to determine how descendants are rendered.
 * It extracts all the information necessary from ancestors in a compact form so we can create an effective tree of
 * these.
 *
 * API for RenderState:
 * {
 *   isBackbone: Boolean
 *   isTransformed: Boolean
 *   isInstanceCanvasCache: Boolean
 *   isSharedCanvasCachePlaceholder: Boolean
 *   isSharedCanvasCacheSelf: Boolean
 *   selfRenderer: Renderer
 *   groupRenderer: Renderer
 *   sharedCacheRenderer: Renderer
 *   getStateForDescendant: function( trail ) : RenderState
 * }
 *
 * NOTE: Trails for transforms are not provided. Instead, inspecting isTransformed and what type of cache should
 * uniquely determine the transformBaseTrail and transformTrail necessary for rendering (and in an efficient way).
 * Not included here for performance (state doesn't need them)
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var PoolableMixin = require( 'PHET_CORE/PoolableMixin' );
  var scenery = require( 'SCENERY/scenery' );
  require( 'SCENERY/display/Renderer' );
  require( 'SCENERY/util/Trail' );

  var emptyObject = {};

  /*
   * @param {Node} node                    The node whose instance will have this state (inspect the hints / properties
   *                                       on this node)
   * @param {number} preferredRenderers    Either 0 (no preference), or a Renderer order bitmask (see Renderer.js)
   * @param {number} svgRenderer           SVG renderer settings to use
   * @param {number} canvasRenderer        Canvas renderer settings to use
   * @param {boolean} isUnderCanvasCache   Whether we are under any sort of Canvas cache (not including if this node is
   *                                       canvas cached)
   * @param {boolean} isShared             Whether this is the shared instance tree for a single-cache, instead of a
   *                                       reference to it
   * @param {boolean} isDisplayRoot
   *
   * Potential ways the state can change:
   * - any input changes, specifically including:
   * - node's renderer summary (what types of renderers are allowed below)
   * - node.hints | node.opacity
   */
  var RenderState = scenery.RenderState = function RenderState( node, preferredRenderers, svgRenderer, canvasRenderer, isUnderCanvasCache, isShared, isDisplayRoot ) {
    this.initialize( node, preferredRenderers, svgRenderer, canvasRenderer, isUnderCanvasCache, isShared, isDisplayRoot );
  };
  inherit( Object, RenderState, {
    initialize: function( node, preferredRenderers, svgRenderer, canvasRenderer, isUnderCanvasCache, isShared, isDisplayRoot ) {
      // this should be accurate right now, the pass to update these should have been completed earlier
      var combinedBitmask = node._rendererSummary.bitmask;

      this.preferredRenderers = preferredRenderers;
      this.svgRenderer = svgRenderer;
      this.canvasRenderer = canvasRenderer;
      this.isUnderCanvasCache = isUnderCanvasCache;
      this.isDisplayRoot = isDisplayRoot;

      this.isBackbone = false;
      this.isTransformed = false;
      this.isInstanceCanvasCache = false;
      this.isSharedCanvasCachePlaceholder = false;
      this.isSharedCanvasCacheSelf = false;

      //OHTWO TODO PERFORMANCE: These probably should be 0 (e.g. no renderer), so they are falsy, but that way remain
      // fixednum when set to actual renderers
      this.selfRenderer = null;
      this.groupRenderer = null;
      this.sharedCacheRenderer = null;

      var hints = node._hints || emptyObject;

      //OHTWO TODO: force the same layer/block for these. temporarily we are creating a backbone, but we should be able
      //            to create a composite and have these handled inside layers
      var hasTransparency = node._opacity !== 1 || hints.usesOpacity;
      var hasClip = node._clipArea !== null;

      if ( hints.renderer ) {
        this.preferredRenderers = scenery.Renderer.pushOrderBitmask( this.preferredRenderers, hints.renderer );
      }

      // check if we need a backbone or cache
      // if we are under a canvas cache, we will NEVER have a backbone
      // splits are accomplished just by having a backbone
      if ( isDisplayRoot || ( !isUnderCanvasCache && ( hasTransparency || hasClip || hints.requireElement || hints.cssTransform || hints.split ) ) ) {
        this.isBackbone = true;
        this.isTransformed = isDisplayRoot || !!hints.cssTransform; // for now, only trigger CSS transform if we have the specific hint
        this.groupRenderer = scenery.Renderer.bitmaskDOM | ( hints.forceAcceleration ? scenery.Renderer.bitmaskForceAcceleration : 0 ); // probably won't be used
      }
      else if ( hasTransparency || hasClip || hints.canvasCache ) {
        // everything underneath needs to be renderable with Canvas, otherwise we cannot cache
        assert && assert( ( combinedBitmask & scenery.Renderer.bitmaskCanvas ) !== 0, 'hints.canvasCache provided, but not all node contents can be rendered with Canvas under ' + node.constructor.name );

        if ( hints.singleCache ) {
          // TODO: scale options - fixed size, match highest resolution (adaptive), or mipmapped
          if ( isShared ) {
            this.isUnderCanvasCache = true;
            this.isSharedCanvasCacheSelf = true;

            //OHTWO TODO: Also consider SVG output
            this.sharedCacheRenderer = scenery.Renderer.bitmaskCanvas;
          }
          else {
            // everything underneath needs to guarantee that its bounds are valid
            //OHTWO TODO: We'll probably remove this if we go with the "safe bounds" approach
            assert && assert( ( combinedBitmask & scenery.bitmaskBoundsValid ) !== 0, 'hints.singleCache provided, but not all node contents have valid bounds under ' + node.constructor.name );

            this.isSharedCanvasCachePlaceholder = true;
          }
        }
        else {
          this.isInstanceCanvasCache = true;
          this.isUnderCanvasCache = true;
          this.groupRenderer = scenery.Renderer.bitmaskCanvas; // disallowing SVG here, so we don't have to break up our SVG group structure
        }
      }

      if ( node.isPainted() ) {
        this.setSelfRenderer( node );
      }

      return this;
    },

    setSelfRenderer: function( node ) {
      if ( this.isUnderCanvasCache ) {
        this.selfRenderer = this.canvasRenderer;
      }
      else {
        var success = false;

        // try preferred order if specified
        if ( this.preferredRenderers ) {
          success = this.trySelfRenderer( node, scenery.Renderer.bitmaskOrderFirst( this.preferredRenderers ), 0 ) ||
                    this.trySelfRenderer( node, scenery.Renderer.bitmaskOrderSecond( this.preferredRenderers ), 0 ) ||
                    this.trySelfRenderer( node, scenery.Renderer.bitmaskOrderThird( this.preferredRenderers ), 0 ) ||
                    this.trySelfRenderer( node, scenery.Renderer.bitmaskOrderFourth( this.preferredRenderers ), 0 );
        }

        // fall back to a default order
        success = success ||
                  this.trySelfRenderer( node, scenery.Renderer.bitmaskSVG, this.svgRenderer ) ||
                  this.trySelfRenderer( node, scenery.Renderer.bitmaskCanvas, this.canvasRenderer ) ||
                  this.trySelfRenderer( node, scenery.Renderer.bitmaskDOM, 0 ) ||
                  this.trySelfRenderer( node, scenery.Renderer.bitmaskWebGL, 0 );

        assert && assert( success, 'setSelfRenderer failure?' );
      }
    },

    // returns success of setting this.selfRenderer. renderer is expected to be a 1-bit bitmask, with rendererSpecifics
    // either 0 (autodetect) or a full renderer bitmask
    trySelfRenderer: function( node, renderer, rendererSpecifics ) {
      // if provided renderer === 0, we won't be compatible
      var compatible = !!( node._rendererBitmask & renderer );
      if ( compatible ) {
        if ( !rendererSpecifics ) {
          if ( scenery.Renderer.isCanvas( renderer ) ) {
            rendererSpecifics = this.canvasRenderer;
          }
          else if ( scenery.Renderer.isSVG( renderer ) ) {
            rendererSpecifics = this.svgRenderer;
          }
          else if ( scenery.Renderer.isDOM( renderer ) ) {
            // TODO: decide if CSS transform is to be applied here!
            rendererSpecifics = scenery.Renderer.bitmaskDOM;
          }
          else if ( scenery.Renderer.isWebGL( renderer ) ) {
            // TODO: details?
            rendererSpecifics = scenery.Renderer.bitmaskWebGL;
          }
        }
        assert && assert( rendererSpecifics,
          'Should have renderer specifics by now, otherwise we did not recognize the renderer' );
        this.selfRenderer = rendererSpecifics;
      }
      return compatible;
    },

    getStateForDescendant: function( node ) {
      return RenderState.createFromPool(
        node,

        // default renderer when available
        this.preferredRenderers,

        // default SVG renderer settings
        this.svgRenderer,

        // default Canvas renderer settings
        this.canvasRenderer,

        // isUnderCanvasCache
        (this.isUnderCanvasCache || this.isInstanceCanvasCache || this.isSharedCanvasCacheSelf),

        // isShared. No direct descendant is shared, since we create those specially with a new state
        // from createSharedCacheState
        false,

        // isDisplayRoot
        false
      );
    },

    /*
     * Whether we can just update the state on an Instance when changing from this state => otherState.
     * This is generally not possible if there is a change in whether the instance should be a transform root
     * (e.g. backbone/single-cache), so we will have to recreate the instance and its subtree if that is the case.
     */
    isInstanceCompatibleWith: function( otherState ) {
      return this.isTransformed === otherState.isTransformed && //OHTWO TODO: allow mutating based on this change
             this.isSharedCanvasCachePlaceholder === otherState.isSharedCanvasCachePlaceholder; //OHTWO TODO: allow mutating based on this change
    },

    toString: function() {
      var result = 'S[ ' +
                   ( this.isDisplayRoot ? 'displayRoot ' : '' ) +
                   ( this.isBackbone ? 'backbone ' : '' ) +
                   ( this.isInstanceCanvasCache ? 'instanceCache ' : '' ) +
                   ( this.isSharedCanvasCachePlaceholder ? 'sharedCachePlaceholder ' : '' ) +
                   ( this.isSharedCanvasCacheSelf ? 'sharedCacheSelf ' : '' ) +
                   ( this.isTransformed ? 'TR ' : '' ) +
                   ( this.selfRenderer ? this.selfRenderer.toString( 16 ) : '-' ) + ',' +
                   ( this.groupRenderer ? this.groupRenderer.toString( 16 ) : '-' ) + ',' +
                   ( this.sharedCacheRenderer ? this.sharedCacheRenderer.toString( 16 ) : '-' ) + ' ';
      return result + ']';
    }
  } );

  RenderState.createRootState = function( node ) {
    var baseState = RenderState.createFromPool(
      node,                           // trail
      0,                              // no preferred renderers
      scenery.Renderer.bitmaskSVG,    // default SVG renderer settings
      scenery.Renderer.bitmaskCanvas, // default Canvas renderer settings
      false,                          // isUnderCanvasCache
      false,                          // isShared
      true                            // isDisplayRoot
    );
    return baseState;
  };

  RenderState.createSharedCacheState = function( node ) {
    var baseState = RenderState.createFromPool(
      node,                             // trail
      0,                                // no preferred renderers (not really necessary, Canvas will be forced anyways)
      null,                             // no SVG renderer settings needed
      scenery.Renderer.bitmaskCanvas,   // default Canvas renderer settings
      true,                             // isUnderCanvasCache
      true,                             // isShared (since we are creating the shared one, not the individual instances referencing it)
      false                             // isDisplayRoot
    );
    return baseState;
  };

  /* jshint -W064 */
  PoolableMixin( RenderState, {
    constructorDuplicateFactory: function( pool ) {
      return function( node, preferredRenderers, svgRenderer, canvasRenderer, isUnderCanvasCache, isShared, isDisplayRoot ) {
        if ( pool.length ) {
          sceneryLog && sceneryLog.RenderState && sceneryLog.RenderState( 'new from pool' );
          return pool.pop().initialize( node, preferredRenderers, svgRenderer, canvasRenderer, isUnderCanvasCache, isShared, isDisplayRoot );
        }
        else {
          sceneryLog && sceneryLog.RenderState && sceneryLog.RenderState( 'new from constructor' );
          return new RenderState( node, preferredRenderers, svgRenderer, canvasRenderer, isUnderCanvasCache, isShared, isDisplayRoot );
        }
      };
    }
  } );

  return RenderState;
} );
<commit_msg>RenderState cleanup (removal of svgRenderer, canvasRenderer)<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * A RenderState represents the state information for a Node needed to determine how descendants are rendered.
 * It extracts all the information necessary from ancestors in a compact form so we can create an effective tree of
 * these.
 *
 * API for RenderState:
 * {
 *   isBackbone: Boolean
 *   isTransformed: Boolean
 *   isInstanceCanvasCache: Boolean
 *   isSharedCanvasCachePlaceholder: Boolean
 *   isSharedCanvasCacheSelf: Boolean
 *   selfRenderer: Renderer
 *   groupRenderer: Renderer
 *   sharedCacheRenderer: Renderer
 *   getStateForDescendant: function( trail ) : RenderState
 * }
 *
 * NOTE: Trails for transforms are not provided. Instead, inspecting isTransformed and what type of cache should
 * uniquely determine the transformBaseTrail and transformTrail necessary for rendering (and in an efficient way).
 * Not included here for performance (state doesn't need them)
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var PoolableMixin = require( 'PHET_CORE/PoolableMixin' );
  var scenery = require( 'SCENERY/scenery' );
  var Renderer = require( 'SCENERY/display/Renderer' ); // TODO: remove namespacing?
  require( 'SCENERY/util/Trail' );

  var emptyObject = {};

  // var defaultPreferredRenderers = Renderer.bitmaskFromRenderers( Renderer.bitmaskWebGL, Renderer.bitmaskSVG, Renderer.bitmaskCanvas, Renderer.bitmaskDOM );
  // var defaultCanvasPreferredRenderers = Renderer.bitmaskFromRenderers( Renderer.bitmaskCanvas );

  /*
   * @param {Node} node                    The node whose instance will have this state (inspect the hints / properties
   *                                       on this node)
   * @param {number} preferredRenderers    Either 0 (no preference), or a Renderer order bitmask (see Renderer.js)
   * @param {boolean} isUnderCanvasCache   Whether we are under any sort of Canvas cache (not including if this node is
   *                                       canvas cached)
   * @param {boolean} isShared             Whether this is the shared instance tree for a single-cache, instead of a
   *                                       reference to it
   * @param {boolean} isDisplayRoot
   *
   * Potential ways the state can change:
   * - any input changes, specifically including:
   * - node's renderer summary (what types of renderers are allowed below)
   * - node.hints | node.opacity
   */
  var RenderState = scenery.RenderState = function RenderState( node, preferredRenderers, isUnderCanvasCache, isShared, isDisplayRoot ) {
    this.initialize( node, preferredRenderers, isUnderCanvasCache, isShared, isDisplayRoot );
  };
  inherit( Object, RenderState, {
    initialize: function( node, preferredRenderers, isUnderCanvasCache, isShared, isDisplayRoot ) {
      // this should be accurate right now, the pass to update these should have been completed earlier
      var combinedBitmask = node._rendererSummary.bitmask;

      this.preferredRenderers = preferredRenderers;
      this.isUnderCanvasCache = isUnderCanvasCache;
      this.isDisplayRoot = isDisplayRoot;

      this.isBackbone = false;
      this.isTransformed = false;
      this.isInstanceCanvasCache = false;
      this.isSharedCanvasCachePlaceholder = false;
      this.isSharedCanvasCacheSelf = false;

      //OHTWO TODO PERFORMANCE: These probably should be 0 (e.g. no renderer), so they are falsy, but that way remain
      // fixednum when set to actual renderers
      this.selfRenderer = null;
      this.groupRenderer = null;
      this.sharedCacheRenderer = null;

      var hints = node._hints || emptyObject;

      //OHTWO TODO: force the same layer/block for these. temporarily we are creating a backbone, but we should be able
      //            to create a composite and have these handled inside layers
      var hasTransparency = node._opacity !== 1 || hints.usesOpacity;
      var hasClip = node._clipArea !== null;

      if ( hints.renderer ) {
        this.preferredRenderers = scenery.Renderer.pushOrderBitmask( this.preferredRenderers, hints.renderer );
      }

      // check if we need a backbone or cache
      // if we are under a canvas cache, we will NEVER have a backbone
      // splits are accomplished just by having a backbone
      if ( isDisplayRoot || ( !isUnderCanvasCache && ( hasTransparency || hasClip || hints.requireElement || hints.cssTransform || hints.split ) ) ) {
        this.isBackbone = true;
        this.isTransformed = isDisplayRoot || !!hints.cssTransform; // for now, only trigger CSS transform if we have the specific hint
        this.groupRenderer = scenery.Renderer.bitmaskDOM | ( hints.forceAcceleration ? scenery.Renderer.bitmaskForceAcceleration : 0 ); // probably won't be used
      }
      else if ( hasTransparency || hasClip || hints.canvasCache ) {
        // everything underneath needs to be renderable with Canvas, otherwise we cannot cache
        assert && assert( ( combinedBitmask & scenery.Renderer.bitmaskCanvas ) !== 0, 'hints.canvasCache provided, but not all node contents can be rendered with Canvas under ' + node.constructor.name );

        if ( hints.singleCache ) {
          // TODO: scale options - fixed size, match highest resolution (adaptive), or mipmapped
          if ( isShared ) {
            this.isUnderCanvasCache = true;
            this.isSharedCanvasCacheSelf = true;

            //OHTWO TODO: Also consider SVG output
            this.sharedCacheRenderer = scenery.Renderer.bitmaskCanvas;
          }
          else {
            // everything underneath needs to guarantee that its bounds are valid
            //OHTWO TODO: We'll probably remove this if we go with the "safe bounds" approach
            assert && assert( ( combinedBitmask & scenery.bitmaskBoundsValid ) !== 0, 'hints.singleCache provided, but not all node contents have valid bounds under ' + node.constructor.name );

            this.isSharedCanvasCachePlaceholder = true;
          }
        }
        else {
          this.isInstanceCanvasCache = true;
          this.isUnderCanvasCache = true;
          this.groupRenderer = scenery.Renderer.bitmaskCanvas; // disallowing SVG here, so we don't have to break up our SVG group structure
        }
      }

      if ( node.isPainted() ) {
        this.setSelfRenderer( node );
      }

      return this;
    },

    setSelfRenderer: function( node ) {
      if ( this.isUnderCanvasCache ) {
        this.selfRenderer = Renderer.bitmaskCanvas;
      }
      else {
        var nodeBitmask = node._rendererBitmask;

        //OHTWO TODO: How specifically to handle hi-resolution varieties? Not in the renderer?
        // use the preferred rendering order if specified, otherwise use the default
        this.selfRenderer = ( nodeBitmask & Renderer.bitmaskOrderFirst( this.preferredRenderers ) ) ||
                            ( nodeBitmask & Renderer.bitmaskOrderSecond( this.preferredRenderers ) ) ||
                            ( nodeBitmask & Renderer.bitmaskOrderThird( this.preferredRenderers ) ) ||
                            ( nodeBitmask & Renderer.bitmaskOrderFourth( this.preferredRenderers ) ) ||
                            ( nodeBitmask & Renderer.bitmaskSVG ) ||
                            ( nodeBitmask & Renderer.bitmaskCanvas ) ||
                            ( nodeBitmask & Renderer.bitmaskDOM ) ||
                            ( nodeBitmask & Renderer.bitmaskWebGL ) ||
                            0;

        assert && assert( this.selfRenderer, 'setSelfRenderer failure?' );
      }
    },

    getStateForDescendant: function( node ) {
      return RenderState.createFromPool(
        node,

        // default renderer when available
        this.preferredRenderers,

        // isUnderCanvasCache
        (this.isUnderCanvasCache || this.isInstanceCanvasCache || this.isSharedCanvasCacheSelf),

        // isShared. No direct descendant is shared, since we create those specially with a new state
        // from createSharedCacheState
        false,

        // isDisplayRoot
        false
      );
    },

    /*
     * Whether we can just update the state on an Instance when changing from this state => otherState.
     * This is generally not possible if there is a change in whether the instance should be a transform root
     * (e.g. backbone/single-cache), so we will have to recreate the instance and its subtree if that is the case.
     */
    isInstanceCompatibleWith: function( otherState ) {
      return this.isTransformed === otherState.isTransformed && //OHTWO TODO: allow mutating based on this change
             this.isSharedCanvasCachePlaceholder === otherState.isSharedCanvasCachePlaceholder; //OHTWO TODO: allow mutating based on this change
    },

    toString: function() {
      var result = 'S[ ' +
                   ( this.isDisplayRoot ? 'displayRoot ' : '' ) +
                   ( this.isBackbone ? 'backbone ' : '' ) +
                   ( this.isInstanceCanvasCache ? 'instanceCache ' : '' ) +
                   ( this.isSharedCanvasCachePlaceholder ? 'sharedCachePlaceholder ' : '' ) +
                   ( this.isSharedCanvasCacheSelf ? 'sharedCacheSelf ' : '' ) +
                   ( this.isTransformed ? 'TR ' : '' ) +
                   ( this.selfRenderer ? this.selfRenderer.toString( 16 ) : '-' ) + ',' +
                   ( this.groupRenderer ? this.groupRenderer.toString( 16 ) : '-' ) + ',' +
                   ( this.sharedCacheRenderer ? this.sharedCacheRenderer.toString( 16 ) : '-' ) + ' ';
      return result + ']';
    }
  } );

  RenderState.createRootState = function( node ) {
    var baseState = RenderState.createFromPool(
      node,                           // trail
      0,                              // no preferred renderers
      false,                          // isUnderCanvasCache
      false,                          // isShared
      true                            // isDisplayRoot
    );
    return baseState;
  };

  RenderState.createSharedCacheState = function( node ) {
    var baseState = RenderState.createFromPool(
      node,                             // trail
      0,                                // no preferred renderers (not really necessary, Canvas will be forced anyways)
      true,                             // isUnderCanvasCache
      true,                             // isShared (since we are creating the shared one, not the individual instances referencing it)
      false                             // isDisplayRoot
    );
    return baseState;
  };

  /* jshint -W064 */
  PoolableMixin( RenderState, {
    constructorDuplicateFactory: function( pool ) {
      return function( node, preferredRenderers, isUnderCanvasCache, isShared, isDisplayRoot ) {
        if ( pool.length ) {
          sceneryLog && sceneryLog.RenderState && sceneryLog.RenderState( 'new from pool' );
          return pool.pop().initialize( node, preferredRenderers, isUnderCanvasCache, isShared, isDisplayRoot );
        }
        else {
          sceneryLog && sceneryLog.RenderState && sceneryLog.RenderState( 'new from constructor' );
          return new RenderState( node, preferredRenderers, isUnderCanvasCache, isShared, isDisplayRoot );
        }
      };
    }
  } );

  return RenderState;
} );
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    shell: {
        deploy_setup: {
            command: 'pip install awscli --upgrade',
            options: {
                stdout: true,
                stderr: true,
                failOnError: true
            }
        }
    },
    ec2: 'env/private/deployment.json'
};
<commit_msg>corrected deployment configuration filename<commit_after>'use strict';

module.exports = {
    shell: {
        deploy_setup: {
            command: 'pip install awscli --upgrade',
            options: {
                stdout: true,
                stderr: true,
                failOnError: true
            }
        }
    },
    ec2: 'env/private/grunt.json'
};
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    var playerMove;
    if (move !== null) {
        playerMove = move;
    }
    else {
        playerMove = getInput();
    }
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return myExp1;
}

function getComputerMove(move) {
    var compMove;
    if (move !== null) {
        compMove = move;
    }
    else {
        compMove = randomPlay();
    }
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    if (playerMove === "rock") {
    	if (computerMove === "paper") {
    		winner = "computer";
    	}
    	else if (computerMove === "scissors") {
    		winner = "player";
    	}
    	else {
    		winner = "tie";
    	}
    }

    else if (playerMove === "paper") {
    	if (computerMove === "scissors") {
    		winner = "computer";
     	}
     	else if (computerMove === "rock") {
     		winner = "player";
     	}
     	else {
     		winner = "tie";
     	}
     }

    else if (playerMove === "scissors") {
    	if (computerMove === "rock") {
    		winner = "computer";
    	}
    	else if (computerMove === "paper") {
    		winner = "player";
    	}
    	else {
    		winner = "tie";
    	}
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;

    if (winner === "player") {
    	playerWins += 1;
    }
    else if (winner === "computer") {
    	computerWins += 1;
    }

	console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
	console.log('The score is currently ' + playerWins + ' to ' + computerWins);

    if (playerWins < 5 && computerWins < 5) {
		return 'Keep playing!';
	}
	else if (playerWins > computerWins) {
		return 'The player has won!';
	}
	else {
		return 'The computer has won!';
	}
}

  // This function should continue to play Rock Paper Scissors until either the
  // player or the computer has won five times.
  // After each 'round', display some text in the console indicating who played
  // what, who won, and what the current scoreboard looks like.
  // For example,
  //  console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
  //  console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    return [playerWins, computerWins];
}

function playTo(x) {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;

    if (winner === "player") {
    	playerWins += 1;
    }
    else if (winner === "computer") {
    	computerWins += 1;
    }

	console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
	console.log('The score is currently ' + playerWins + ' to ' + computerWins);

	if (playerWins < x && computerWins < x) {
		return 'Keep playing!';
	}
	else if (playerWins > computerWins) {
		return 'The player has won!';
	}
	else {
		return 'The computer has won!';
	}
}

<commit_msg>unit 6 hw<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.");
    return prompt();
}

function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove() {
    var playerMove;
    var move;
    if (move) {
        playerMove = move;
    }
    else {
        playerMove = getInput();
    }
    return playerMove;
}

function getComputerMove(move) {
    var computerMove;
    if (move) {
        computerMove = move;
    }
    else {
        computerMove = randomPlay();
    }
    return computerMove;
}

function getWinner(playerMove,computerMove) {
    var winner;
    if (playerMove === "rock") {
        if (computerMove === "paper") {
            winner = "computer";
        }
        else if (computerMove === "scissors") {
            winner = "player";
        }
        else {
            winner = "tie";
        }
    }

    else if (playerMove === "paper") {
        if (computerMove === "scissors") {
            winner = "computer";
        }
        else if (computerMove === "rock") {
            winner = "player";
        }
        else {
            winner = "tie";
        }
     }

    else {
        if (computerMove === "rock") {
            winner = "computer";
        }
        else if (computerMove === "paper") {
            winner = "player";
        }
        else {
            winner = "tie";
        }
    }
    return winner;
}

function playToFive() {
    var playerWins = 0;
    var computerWins = 0;
    var roundNum = 0;
    console.log("Let's play Rock, Paper, Scissors.");

    while (playerWins < 5 && computerWins < 5) {
        var playerMove = getPlayerMove();
        var computerMove = getComputerMove();
        var winner = getWinner(playerMove, computerMove);
        console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);

        if (winner === "tie") {
            roundNum++;
            console.log("Round " + roundNum + " was a tie.");
        }
        else if (winner === "player") {
            playerWins++;
            roundNum++;
            console.log("You won round " + roundNum + "!");
            }
        else {
            computerWins++;
            roundNum++;
            console.log("The computer won round " + roundNum + ".");
        }
        console.log('The score is currently ' + playerWins + ' to ' + computerWins);
    }

    if (playerWins > computerWins) {
        return 'You are the rock paper scissors champion!';
    }
    else {
        return 'The computer is the rock paper scissors champion.';
    }

}

function playTo(x) {
    var playerWins = 0;
    var computerWins = 0;
    var roundNum = 0;
    console.log("Let's play Rock, Paper, Scissors.");

    while (playerWins < x && computerWins < x) {
        var playerMove = getPlayerMove();
        var computerMove = getComputerMove();
        var winner = getWinner(playerMove, computerMove);
        console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);

        if (winner === "tie") {
            roundNum++;
            console.log("Round " + roundNum + " was a tie.");
        }
        else if (winner === "player") {
            playerWins++;
            roundNum++;
            console.log("You won round " + roundNum + "!");
            }
        else {
            computerWins++;
            roundNum++;
            console.log("The computer won round " + roundNum + ".");
        }
        console.log('The score is currently ' + playerWins + ' to ' + computerWins);
    }

    if (playerWins > computerWins) {
        return 'You are the rock paper scissors champion!';
    }
    else {
        return 'The computer is the rock paper scissors champion.';
    }

}<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * Created by jrobinso on 5/27/15.
 */

/**
 * Support functions for the Encode rest api  https://www.encodeproject.org/help/rest-api/
 */

var encode = (function (encode) {

    // var query1 = "https://www.encodeproject.org/search/?" +
    //     "type=experiment&" +
    //     "files.file_format=bed&" +
    //     "format=json&" +
    //     "limit=all&" +
    //     "field=replicates.library.biosample.donor.organism.name&" +
    //     "field=lab.title&field=biosample_term_name&" +
    //     "field=assay_term_name&" +
    //     "field=target.label&" +
    //     "field=files.file_format&" +
    //     "field=files.output_type&" +
    //     "field=files.href&" +
    //     "field=files.replicate.technical_replicate_number&" +
    //     "field=files.replicate.biological_replicate_number";

    const fileFormat = "bigWig";

    // var query3 = "https://www.encodeproject.org/search/?" +
    //     "type=File" +
    //     "&assembly=hg19" +
    //     "&status=released" +
    //     "&file_format=bigWig" +
    //     "&output_type=signal+p-value" +
    //     "&output_type=fold+change+over+control" +
    //     "&award.project=ENCODE&" +
    //     "format=json&" +
    //     "limit=all";

    encode.encodeSearch = function (assembly, continuation) {

        var query2 = "https://www.encodeproject.org/search/?" +
            "type=experiment&" +
            "assembly=" + assembly + "&" +
            "assay_title=ChIP-seq&" +
            //  "files.output_type=peaks&" +
            "files.file_format=" + fileFormat + "&" +
            "format=json&" +
            "field=lab.title&" +
            "field=biosample_term_name&" +
            "field=assay_term_name&" +
            "field=target.label&" +
            "field=files.file_format&" +
            "field=files.output_type&" +
            "field=files.href&" +
            "field=files.replicate.technical_replicate_number&" +
            "field=files.replicate.biological_replicate_number&" +
            "field=files.assembly&" +
            "limit=all";

        console.log('encode search - load json ...');
        igvxhr
            .loadJson(query2, {})
            .then(function (json) {

                var columnFormat,
                    rows;

                console.log('' +
                    '... done');

                console.log('parse/sort json ...');

                rows = [];
                _.each(json["@graph"], function (record) {

                    var cellType,
                        target,
                        filtered,
                        mapped;

                    cellType = record["biosample_term_name"] || '';

                    target = record.target ? record.target.label : '';

                    filtered = _.filter(record.files, function (file) {
                        return fileFormat === file.file_format && assembly === file.assembly;
                    });

                    mapped = _.map(filtered, function (file) {

                        var bioRep = file.replicate ? file.replicate.bioligcal_replicate_number : undefined,
                            techRep = file.replicate ? file.replicate.technical_replicate_number : undefined,
                            name = cellType + " " + target;

                        if (bioRep) {
                            name += " " + bioRep;
                        }

                        if (techRep) {
                            name += (bioRep ? ":" : "0:") + techRep;
                        }

                        return {
                            "Assembly": file.assembly,
                            "ExperimentID": record['@id'],
                            "Cell Type": cellType,
                            "Assay Type": record.assay_term_name,
                            "Target": target,
                            "Lab": record.lab ? record.lab.title : "",
                            "Format": file.file_format,
                            "Output Type": file.output_type,
                            "url": "https://www.encodeproject.org" + file.href,
                            "Bio Rep": bioRep,
                            "Tech Rep": techRep,
                            "Name": name
                        };

                    });

                    Array.prototype.push.apply(rows, mapped);

                });

                rows.sort(function (a, b) {
                    var a1 = a["Assembly"],
                        a2 = b["Assembly"],
                        ct1 = a["Cell Type"],
                        ct2 = b["Cell Type"],
                        t1 = a["Target"],
                        t2 = b["Target"];

                    if (a1 === a2) {
                        if (ct1 === ct2) {
                            if (t1 === t2) {
                                return 0;
                            }
                            else if (t1 < t2) {
                                return -1;
                            }
                            else {
                                return 1;
                            }
                        }
                        else if (ct1 < ct2) {
                            return -1;
                        }
                        else {
                            return 1;
                        }
                    }
                    else {
                        if (a1 < a2) {
                            return -1;
                        }
                        else {
                            return 1;
                        }
                    }
                });

                console.log('... done');

                columnFormat =
                {
                    'Assembly': 8,
                    'Cell Type': 8,
                    'Target': 10,
                    'Assay Type': 10,
                    'Output Type': 10,
                    // 'Bio Rep': 8,
                    // 'Tech Rep': 8,
                    'Lab': 16
                };

                continuation({
                    columns: _.keys(columnFormat),
                    columnWidths: _.values(columnFormat),
                    rows: rows
                });

            });

    };

    return encode;
})
(encode || {});
<commit_msg>Encode -- enable all assay types<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * Created by jrobinso on 5/27/15.
 */

/**
 * Support functions for the Encode rest api  https://www.encodeproject.org/help/rest-api/
 */

var encode = (function (encode) {

    // var query1 = "https://www.encodeproject.org/search/?" +
    //     "type=experiment&" +
    //     "files.file_format=bed&" +
    //     "format=json&" +
    //     "limit=all&" +
    //     "field=replicates.library.biosample.donor.organism.name&" +
    //     "field=lab.title&field=biosample_term_name&" +
    //     "field=assay_term_name&" +
    //     "field=target.label&" +
    //     "field=files.file_format&" +
    //     "field=files.output_type&" +
    //     "field=files.href&" +
    //     "field=files.replicate.technical_replicate_number&" +
    //     "field=files.replicate.biological_replicate_number";

    const fileFormat = "bigWig";

    // var query3 = "https://www.encodeproject.org/search/?" +
    //     "type=File" +
    //     "&assembly=hg19" +
    //     "&status=released" +
    //     "&file_format=bigWig" +
    //     "&output_type=signal+p-value" +
    //     "&output_type=fold+change+over+control" +
    //     "&award.project=ENCODE&" +
    //     "format=json&" +
    //     "limit=all";

    encode.encodeSearch = function (assembly, continuation) {

        var query2 = "https://www.encodeproject.org/search/?" +
            "type=experiment&" +
            "assembly=" + assembly + "&" +
            //"assay_title=ChIP-seq&" +
            //  "files.output_type=peaks&" +
            "files.file_format=" + fileFormat + "&" +
            "format=json&" +
            "field=lab.title&" +
            "field=biosample_term_name&" +
            "field=assay_term_name&" +
            "field=target.label&" +
            "field=files.file_format&" +
            "field=files.output_type&" +
            "field=files.href&" +
            "field=files.replicate.technical_replicate_number&" +
            "field=files.replicate.biological_replicate_number&" +
            "field=files.assembly&" +
            "limit=all";

        console.log('encode search - load json ...');
        igvxhr
            .loadJson(query2, {})
            .then(function (json) {

                var columnFormat,
                    rows;

                console.log('' +
                    '... done');

                console.log('parse/sort json ...');

                rows = [];
                _.each(json["@graph"], function (record) {

                    var cellType,
                        target,
                        filtered,
                        mapped;

                    cellType = record["biosample_term_name"] || '';

                    target = record.target ? record.target.label : '';

                    filtered = _.filter(record.files, function (file) {
                        return fileFormat === file.file_format && assembly === file.assembly;
                    });

                    mapped = _.map(filtered, function (file) {

                        var bioRep = file.replicate ? file.replicate.bioligcal_replicate_number : undefined,
                            techRep = file.replicate ? file.replicate.technical_replicate_number : undefined,
                            name = cellType + " " + target;

                        if (bioRep) {
                            name += " " + bioRep;
                        }

                        if (techRep) {
                            name += (bioRep ? ":" : "0:") + techRep;
                        }

                        return {
                            "Assembly": file.assembly,
                            "ExperimentID": record['@id'],
                            "Cell Type": cellType,
                            "Assay Type": record.assay_term_name,
                            "Target": target,
                            "Lab": record.lab ? record.lab.title : "",
                            "Format": file.file_format,
                            "Output Type": file.output_type,
                            "url": "https://www.encodeproject.org" + file.href,
                            "Bio Rep": bioRep,
                            "Tech Rep": techRep,
                            "Name": name
                        };

                    });

                    Array.prototype.push.apply(rows, mapped);

                });

                rows.sort(function (a, b) {
                    var a1 = a["Assembly"],
                        a2 = b["Assembly"],
                        ct1 = a["Cell Type"],
                        ct2 = b["Cell Type"],
                        t1 = a["Target"],
                        t2 = b["Target"];

                    if (a1 === a2) {
                        if (ct1 === ct2) {
                            if (t1 === t2) {
                                return 0;
                            }
                            else if (t1 < t2) {
                                return -1;
                            }
                            else {
                                return 1;
                            }
                        }
                        else if (ct1 < ct2) {
                            return -1;
                        }
                        else {
                            return 1;
                        }
                    }
                    else {
                        if (a1 < a2) {
                            return -1;
                        }
                        else {
                            return 1;
                        }
                    }
                });

                console.log('... done');

                columnFormat =
                {
                    'Assembly': 8,
                    'Cell Type': 8,
                    'Target': 10,
                    'Assay Type': 10,
                    'Output Type': 10,
                    // 'Bio Rep': 8,
                    // 'Tech Rep': 8,
                    'Lab': 16
                };

                continuation({
                    columns: _.keys(columnFormat),
                    columnWidths: _.values(columnFormat),
                    rows: rows
                });

            });

    };

    return encode;
})
(encode || {});
<|endoftext|>


<commit_before>var fs = require('fs');

var file = function(parent, file){
  this.file   = file;
  this.parent = parent;
  this.getLineCounter = 0;
  this.setLineCounter = 0;
}

// accept callback
// return (error, arr) where arr is an array of objects
file.prototype.get = function(limit, offset, callback){
  var self        = this;
  var error       = null;
  var data        = [];
  // self.readStream = fs.createWriteStream(self.file, { flags : 'r' });

  callback(err, data);
}

// accept arr, callback where arr is an array of objects
// return (error, writes)
file.prototype.set = function(data, limit, offset, callback){
  var self         = this;
  var error        = null;

  if(self.writeStream == null){
    // create the file
    try{
      fs.unlinkSync(self.file);
      fs.unlinkSync(self.file);
    }catch(e){ }
    self.writeStream = fs.createWriteStream(self.file, { flags : 'w' });
    self.writeStream.write("[\r\n");
  }

  if(data.length == 0){
    // close the file
    self.writeStream.write("]\r\n");
    setTimeout(function(){
      self.writeStream.close();
    }, 1000)
  }

  data.forEach(function(elem){
    if(self.setLineCounter > 0){
      self.writeStream.write(",");
    }
    self.writeStream.write(JSON.stringify(elem) + "\r\n");
    self.setLineCounter++;
  });

  callback(error, data.length);
}

exports.file = file;<commit_msg>streaming from file<commit_after>var fs = require('fs');

var file = function(parent, file){
  this.file   = file;
  this.parent = parent;
  this.getLineCounter = 0;
  this.setLineCounter = 0;
}

// accept callback
// return (error, arr) where arr is an array of objects
file.prototype.get = function(limit, offset, callback){
  var self        = this;
  var error       = null;
  var data        = [];
  var counter     = 0;

  if(self.readStream == null){
    self.readStream = fs.createReadStream(self.file, { flags : 'r' });
    self.readStream.setEncoding('utf8');
    self.readStream.pause();
  }

  self.readStream.addListener('data', function(lines){
    self.readStream.pause();
    lines = lines.split("\r\n");
    lines.forEach(function(line){
      try{
        if(line[0] === ','){ line = line.substring(1); }
        data.push( JSON.parse(line) )
      }catch(e){
        //
      }
      if(data.length === limit){
        callback(error, data);
      }else{
        self.readStream.resume();
      }
    });
  });

  self.readStream.addListener('end', function(){
    callback(error, data);
  });

  self.readStream.addListener('error', function(err){
    throw(err)
  });

  self.readStream.resume();
}

// accept arr, callback where arr is an array of objects
// return (error, writes)
file.prototype.set = function(data, limit, offset, callback){
  var self         = this;
  var error        = null;

  if(self.writeStream == null){
    // create the file
    try{
      fs.unlinkSync(self.file);
      fs.unlinkSync(self.file);
    }catch(e){ }
    self.writeStream = fs.createWriteStream(self.file, { flags : 'w' });
    self.writeStream.write("[\r\n");
  }

  if(data.length == 0){
    // close the file
    self.writeStream.write("]\r\n");
    setTimeout(function(){
      self.writeStream.close();
    }, 1000)
  }

  data.forEach(function(elem){
    if(self.setLineCounter > 0){
      self.writeStream.write(",");
    }
    self.writeStream.write(JSON.stringify(elem) + "\r\n");
    self.setLineCounter++;
  });

  callback(error, data.length);
}

exports.file = file;<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // var  Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if playerMove === "rock"{
      if computerMove === "rock"{
      winner = "tie";
      }
      else if computerMove === "paper" {
      winner = "computer";
      }
      else {
      winner = "player":
      }
    }

    if playerMove === "paper"{
      if computerMove === "paper"{
        winner = "tie";
      }
      else if computerMove === "scissors"{
        winner = "computer";
      }
      else {
        winner = "player"
      }
    }

    if playerMove === "scissors"{
      if computerMove === "scissors"{
        winner = "tie";
      }
      else if computerMove === "rock"{
        winner = "computer";
      }
      else {
        winner = "player";
      }
    }

    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}
<commit_msg>fixed some lines of coding for getWinner function<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // var  Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (playerMove === "rock"){
      if (computerMove === "rock"){
      winner = "tie";
      }
      else if (computerMove === "paper") {
      winner = "computer";
      }
      else {
      winner = "player";
      }
    }

    else if(playerMove === "paper"){
      if (computerMove === "paper"){
        winner = "tie";
      }
      else if (computerMove === "scissors"){
        winner = "computer";
      }
      else {
        winner = "player"
      }
    }

    else (playerMove === "scissors"){
      if (computerMove === "scissors"){
        winner = "tie";
      }
      else if (computerMove === "rock"){
        winner = "computer";
      }
      else {
        winner = "player";
      }
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}
<|endoftext|>


<commit_before>/*!
 * FileInput Chinese Translations
 *
 * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
 * any HTML markup tags in the messages must not be converted or translated.
 *
 * @see http://github.com/kartik-v/bootstrap-fileinput
 * @author kangqf <kangqingfei@gmail.com>
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
(function ($) {
    "use strict";

    $.fn.fileinput.locales.zh = {
        fileSingle: '文件',
        filePlural: '多个文件',
        browseLabel: '选择 …',
        removeLabel: '移除',
        removeTitle: '清除选中文件',
        cancelLabel: '取消',
        cancelTitle: '取消进行中的上传',
        uploadLabel: '上传',
        uploadTitle: '上传选中文件',
        msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB. 请重新上传!',
        msgFilesTooLess: '你必须选择最少 {n} {files} 来上传. 请重新上传!',
        msgFilesTooMany: '选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}. 请重新上传!',
        msgFileNotFound: '文件 "{name}" 未找到!',
        msgFileSecured: '安全限制，为了防止读取文件 "{name}".',
        msgFileNotReadable: '文件 "{name}" 不可读.',
        msgFilePreviewAborted: '取消 "{name}" 的预览.',
        msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
        msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
        msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',
        msgValidationError: '文件上传错误',
        msgLoading: '加载第 {index} 文件 共 {files} …',
        msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
        msgSelected: '{n} 个文件选中',
        msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
        dropZoneTitle: '拖拽文件到这里 …'
    };

    $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.zh);
})(window.jQuery);<commit_msg>Update fileinput_locale_zh.js<commit_after>/*!
 * FileInput Chinese Translations
 *
 * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
 * any HTML markup tags in the messages must not be converted or translated.
 *
 * @see http://github.com/kartik-v/bootstrap-fileinput
 * @author kangqf <kangqingfei@gmail.com>
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
(function ($) {
    "use strict";

    $.fn.fileinput.locales.zh = {
        fileSingle: '文件',
        filePlural: '多个文件',
        browseLabel: '选择 …',
        removeLabel: '移除',
        removeTitle: '清除选中文件',
        cancelLabel: '取消',
        cancelTitle: '取消进行中的上传',
        uploadLabel: '上传',
        uploadTitle: '上传选中文件',
        msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB. 请重新上传!',
        msgFilesTooLess: '你必须选择最少 {n} {files} 来上传. 请重新上传!',
        msgFilesTooMany: '选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}. 请重新上传!',
        msgFileNotFound: '文件 "{name}" 未找到!',
        msgFileSecured: '安全限制，为了防止读取文件 "{name}".',
        msgFileNotReadable: '文件 "{name}" 不可读.',
        msgFilePreviewAborted: '取消 "{name}" 的预览.',
        msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
        msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
        msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',
        msgValidationError: '文件上传错误',
        msgLoading: '加载第 {index} 文件 共 {files} …',
        msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
        msgSelected: '{n} 个文件选中',
        msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
        dropZoneTitle: '拖拽文件到这里 …',
        slugCallback: function(text){
            return text ? text.split(/(\\|\/)/g).pop().replace(/[^\w\u4e00-\u9fa5\-.\\\/ ]+/g, '') : '';
        }
    };

    $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.zh);
})(window.jQuery);
<|endoftext|>


<commit_before>import { SYNC_RENDER, DOM_RENDER, NO_RENDER, EMPTY, EMPTY_BASE } from '../constants';
import options from '../options';
import { clone, isFunction } from '../util';
import { hook, deepHook } from '../hooks';
import { enqueueRender } from '../render-queue';
import { getNodeProps } from '.';
import diff from './diff';
import { removeOrphanedChildren, recollectNodeTree } from './diff';
import { createComponent, collectComponent } from './component-recycler';

/** Mark component as dirty and queue up a render.
 *	@param {Component} component
 *	@private
 */
export function triggerComponentRender(component) {
	if (!component._dirty) {
		component._dirty = true;
		enqueueRender(component);
	}
}

/** Set a component's `props` (generally derived from JSX attributes).
 *	@param {Object} props
 *	@param {Object} [opts]
 *	@param {boolean} [opts.renderSync=false]	If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
 *	@param {boolean} [opts.render=true]			If `false`, no render will be triggered.
 */
export function setComponentProps(component, props, opts, context) {
	let d = component._disableRendering;
	component._disableRendering = true;

	opts = opts || EMPTY;

	if (context) {
		if (!component.prevContext) component.prevContext = clone(component.context);
		component.context = context;
	}

	if (component.base) {
		hook(component, 'componentWillReceiveProps', props, component.context);
	}

	if (!component.prevProps) component.prevProps = clone(component.props);
	component.props = props;

	component._disableRendering = d;

	if (opts.render!==false) {
		if (opts.renderSync || options.syncComponentUpdates!==false) {
			renderComponent(component);
		}
		else {
			triggerComponentRender(component);
		}
	}

	hook(props, 'ref', component);
}

/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
 *	@param {Component} component
 *	@param {Object} [opts]
 *	@param {boolean} [opts.build=false]		If `true`, component will build and store a DOM node if not already associated with one.
 *	@private
 */
export function renderComponent(component, opts) {
	if (component._disableRendering) return;

	let skip, rendered,
		props = component.props,
		state = component.state,
		context = component.context,
		previousProps = component.prevProps || props,
		previousState = component.prevState || state,
		previousContext = component.prevContext || context,
		isUpdate = component.base;

	if (isUpdate) {
		component.props = previousProps;
		component.state = previousState;
		component.context = previousContext;
		if (hook(component, 'shouldComponentUpdate', props, state, context)===false) {
			skip = true;
		}
		else {
			hook(component, 'componentWillUpdate', props, state, context);
		}
		component.props = props;
		component.state = state;
		component.context = context;
	}

	component.prevProps = component.prevState = component.prevContext = null;
	component._dirty = false;

	if (!skip) {
		rendered = hook(component, 'render', props, state, context);

		let childComponent = rendered && rendered.nodeName,
			childContext = component.getChildContext ? component.getChildContext() : context,
			toUnmount, base;

		if (isFunction(childComponent) && childComponent.prototype.render) {
			// set up high order component link

			let inst = component._component;
			if (inst && inst.constructor!==childComponent) {
				toUnmount = inst;
				inst = null;
			}

			let childProps = getNodeProps(rendered);

			if (inst) {
				setComponentProps(inst, childProps, SYNC_RENDER, childContext);
			}
			else {
				inst = createComponent(childComponent, childProps, childContext);
				inst._parentComponent = component;
				component._component = inst;
				if (component.base) deepHook(inst, 'componentWillMount');
				setComponentProps(inst, childProps, NO_RENDER, childContext);
				renderComponent(inst, DOM_RENDER);
				if (component.base) deepHook(inst, 'componentDidMount');
			}

			base = inst.base;
		}
		else {
			let cbase = component.base;

			// destroy high order component link
			toUnmount = component._component;
			if (toUnmount) {
				cbase = component._component = null;
			}

			if (component.base || (opts && opts.build)) {
				base = diff(cbase, rendered || EMPTY_BASE, childContext);
			}
		}

		if (component.base && base!==component.base) {
			let p = component.base.parentNode;
			if (p) p.replaceChild(base, component.base);
		}

		if (toUnmount) {
			unmountComponent(toUnmount.base, toUnmount);
		}

		component.base = base;
		if (base) {
			let componentRef = component,
				t = component;
			while ((t=t._parentComponent)) { componentRef = t; }
			base._component = componentRef;
			base._componentConstructor = componentRef.constructor;
		}

		if (isUpdate) {
			hook(component, 'componentDidUpdate', previousProps, previousState, previousContext);
		}
	}

	let cb = component._renderCallbacks, fn;
	if (cb) while ( (fn = cb.pop()) ) fn.call(component);

	return rendered;
}

/** Apply the Component referenced by a VNode to the DOM.
 *	@param {Element} dom	The DOM node to mutate
 *	@param {VNode} vnode	A Component-referencing VNode
 *	@returns {Element} dom	The created/mutated element
 *	@private
 */
export function buildComponentFromVNode(dom, vnode, context) {
	let c = dom && dom._component,
		oldDom = dom;

	let isOwner = c && dom._componentConstructor===vnode.nodeName;
	while (c && !isOwner && (c=c._parentComponent)) {
		isOwner = c.constructor===vnode.nodeName;
	}

	if (isOwner) {
		setComponentProps(c, getNodeProps(vnode), SYNC_RENDER, context);
		dom = c.base;
	}
	else {
		if (c) {
			unmountComponent(dom, c);
			dom = oldDom = null;
		}
		dom = createComponentFromVNode(vnode, dom, context);
		if (oldDom && dom!==oldDom) {
			recollectNodeTree(oldDom);
		}
	}

	return dom;
}

/** Instantiate and render a Component, given a VNode whose nodeName is a constructor.
 *	@param {VNode} vnode
 *	@private
 */
function createComponentFromVNode(vnode, dom, context) {
	let props = getNodeProps(vnode);
	let component = createComponent(vnode.nodeName, props, context);

	if (dom && !component.base) component.base = dom;

	setComponentProps(component, props, NO_RENDER, context);
	renderComponent(component, DOM_RENDER);

	// let node = component.base;
	//if (!node._component) {
	//	node._component = component;
	//	node._componentConstructor = vnode.nodeName;
	//}

	return component.base;
}

/** Remove a component from the DOM and recycle it.
 *	@param {Element} dom			A DOM node from which to unmount the given Component
 *	@param {Component} component	The Component instance to unmount
 *	@private
 */
export function unmountComponent(dom, component, remove) {
	// console.warn('unmounting mismatched component', component);

	hook(component.props, 'ref', null);
	deepHook(component, 'componentWillUnmount');
	if (dom._component===component) {
		delete dom._component;
		delete dom._componentConstructor;
	}
	let base = component.base;
	if (base) {
		if (remove!==false) {
			let p = base.parentNode;
			if (p) p.removeChild(base);
		}
		removeOrphanedChildren(base, base.childNodes, true);
	}
	component._parentComponent = null;
	deepHook(component, 'componentDidUnmount');
	collectComponent(component);
}
<commit_msg>Fix an issue where invoking refs may be skipped during unmount (high order components) - related to issue #87.<commit_after>import { SYNC_RENDER, DOM_RENDER, NO_RENDER, EMPTY, EMPTY_BASE } from '../constants';
import options from '../options';
import { clone, isFunction } from '../util';
import { hook, deepHook } from '../hooks';
import { enqueueRender } from '../render-queue';
import { getNodeProps } from '.';
import diff from './diff';
import { removeOrphanedChildren, recollectNodeTree } from './diff';
import { createComponent, collectComponent } from './component-recycler';

/** Mark component as dirty and queue up a render.
 *	@param {Component} component
 *	@private
 */
export function triggerComponentRender(component) {
	if (!component._dirty) {
		component._dirty = true;
		enqueueRender(component);
	}
}

/** Set a component's `props` (generally derived from JSX attributes).
 *	@param {Object} props
 *	@param {Object} [opts]
 *	@param {boolean} [opts.renderSync=false]	If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
 *	@param {boolean} [opts.render=true]			If `false`, no render will be triggered.
 */
export function setComponentProps(component, props, opts, context) {
	let d = component._disableRendering;
	component._disableRendering = true;

	opts = opts || EMPTY;

	if (context) {
		if (!component.prevContext) component.prevContext = clone(component.context);
		component.context = context;
	}

	if (component.base) {
		hook(component, 'componentWillReceiveProps', props, component.context);
	}

	if (!component.prevProps) component.prevProps = clone(component.props);
	component.props = props;

	component._disableRendering = d;

	if (opts.render!==false) {
		if (opts.renderSync || options.syncComponentUpdates!==false) {
			renderComponent(component);
		}
		else {
			triggerComponentRender(component);
		}
	}

	hook(props, 'ref', component);
}

/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
 *	@param {Component} component
 *	@param {Object} [opts]
 *	@param {boolean} [opts.build=false]		If `true`, component will build and store a DOM node if not already associated with one.
 *	@private
 */
export function renderComponent(component, opts) {
	if (component._disableRendering) return;

	let skip, rendered,
		props = component.props,
		state = component.state,
		context = component.context,
		previousProps = component.prevProps || props,
		previousState = component.prevState || state,
		previousContext = component.prevContext || context,
		isUpdate = component.base;

	if (isUpdate) {
		component.props = previousProps;
		component.state = previousState;
		component.context = previousContext;
		if (hook(component, 'shouldComponentUpdate', props, state, context)===false) {
			skip = true;
		}
		else {
			hook(component, 'componentWillUpdate', props, state, context);
		}
		component.props = props;
		component.state = state;
		component.context = context;
	}

	component.prevProps = component.prevState = component.prevContext = null;
	component._dirty = false;

	if (!skip) {
		rendered = hook(component, 'render', props, state, context);

		let childComponent = rendered && rendered.nodeName,
			childContext = component.getChildContext ? component.getChildContext() : context,
			toUnmount, base;

		if (isFunction(childComponent) && childComponent.prototype.render) {
			// set up high order component link

			let inst = component._component;
			if (inst && inst.constructor!==childComponent) {
				toUnmount = inst;
				inst = null;
			}

			let childProps = getNodeProps(rendered);

			if (inst) {
				setComponentProps(inst, childProps, SYNC_RENDER, childContext);
			}
			else {
				inst = createComponent(childComponent, childProps, childContext);
				inst._parentComponent = component;
				component._component = inst;
				if (component.base) deepHook(inst, 'componentWillMount');
				setComponentProps(inst, childProps, NO_RENDER, childContext);
				renderComponent(inst, DOM_RENDER);
				if (component.base) deepHook(inst, 'componentDidMount');
			}

			base = inst.base;
		}
		else {
			let cbase = component.base;

			// destroy high order component link
			toUnmount = component._component;
			if (toUnmount) {
				cbase = component._component = null;
			}

			if (component.base || (opts && opts.build)) {
				base = diff(cbase, rendered || EMPTY_BASE, childContext);
			}
		}

		if (component.base && base!==component.base) {
			let p = component.base.parentNode;
			if (p) p.replaceChild(base, component.base);
		}

		if (toUnmount) {
			unmountComponent(toUnmount.base, toUnmount);
		}

		component.base = base;
		if (base) {
			let componentRef = component,
				t = component;
			while ((t=t._parentComponent)) { componentRef = t; }
			base._component = componentRef;
			base._componentConstructor = componentRef.constructor;
		}

		if (isUpdate) {
			hook(component, 'componentDidUpdate', previousProps, previousState, previousContext);
		}
	}

	let cb = component._renderCallbacks, fn;
	if (cb) while ( (fn = cb.pop()) ) fn.call(component);

	return rendered;
}

/** Apply the Component referenced by a VNode to the DOM.
 *	@param {Element} dom	The DOM node to mutate
 *	@param {VNode} vnode	A Component-referencing VNode
 *	@returns {Element} dom	The created/mutated element
 *	@private
 */
export function buildComponentFromVNode(dom, vnode, context) {
	let c = dom && dom._component,
		oldDom = dom;

	let isOwner = c && dom._componentConstructor===vnode.nodeName;
	while (c && !isOwner && (c=c._parentComponent)) {
		isOwner = c.constructor===vnode.nodeName;
	}

	if (isOwner) {
		setComponentProps(c, getNodeProps(vnode), SYNC_RENDER, context);
		dom = c.base;
	}
	else {
		if (c) {
			unmountComponent(dom, c);
			dom = oldDom = null;
		}
		dom = createComponentFromVNode(vnode, dom, context);
		if (oldDom && dom!==oldDom) {
			recollectNodeTree(oldDom);
		}
	}

	return dom;
}

/** Instantiate and render a Component, given a VNode whose nodeName is a constructor.
 *	@param {VNode} vnode
 *	@private
 */
function createComponentFromVNode(vnode, dom, context) {
	let props = getNodeProps(vnode);
	let component = createComponent(vnode.nodeName, props, context);

	if (dom && !component.base) component.base = dom;

	setComponentProps(component, props, NO_RENDER, context);
	renderComponent(component, DOM_RENDER);

	// let node = component.base;
	//if (!node._component) {
	//	node._component = component;
	//	node._componentConstructor = vnode.nodeName;
	//}

	return component.base;
}

/** Remove a component from the DOM and recycle it.
 *	@param {Element} dom			A DOM node from which to unmount the given Component
 *	@param {Component} component	The Component instance to unmount
 *	@private
 */
export function unmountComponent(dom, component, remove) {
	// console.warn('unmounting mismatched component', component);

	hook(component.props, 'ref', null);
	hook(component, 'componentWillUnmount');
	if (dom && dom._component===component) {
		delete dom._component;
		delete dom._componentConstructor;
	}

	// recursively tear down & recollect high-order component children:
	let inner = component._component;
	if (inner) {
		unmountComponent(dom, inner, remove);
		// high order components do not own their rendered nodes:
		component.base = component._component = null;
	}

	let base = component.base;
	if (base) {
		if (remove!==false) {
			let p = base.parentNode;
			if (p) p.removeChild(base);
		}
		removeOrphanedChildren(base, base.childNodes, true);
	}

	component._parentComponent = null;
	hook(component, 'componentDidUnmount');
	collectComponent(component);
}
<|endoftext|>


<commit_before>'use strict';

var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;

var BusinessCollection = require('../collections/business-collection');
var MapModel = require('../models/map-model');

module.exports = function() {
	this.mapModel = new MapModel();
	this.collection = new BusinessCollection({
		radius_filter: 500
	});

	var InitView = require('../views/init-view');
	var initView = new InitView({model: this.mapModel, collection: this.collection});
	$('#backbone').html(initView.$el);
};<commit_msg>Set a tight search radius<commit_after>'use strict';

var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;

var BusinessCollection = require('../collections/business-collection');
var MapModel = require('../models/map-model');

module.exports = function() {
	this.mapModel = new MapModel();
	this.collection = new BusinessCollection({
		radius_filter: 100
	});

	var InitView = require('../views/init-view');
	var initView = new InitView({model: this.mapModel, collection: this.collection});
	$('#backbone').html(initView.$el);
};<|endoftext|>


<commit_before>var async = require('async');
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var downloader = require('./downloader');
var tunnelLocation = path.normalize(__dirname + "/../testingbot-tunnel.jar");
var activeTunnel;
var started = false;

function logger(msg) {
	console.log.apply(console, arguments);
}

function download(options, callback)
{
	if (fs.existsSync(tunnelLocation)) {
		return callback(null);
	}

	downloader.get('https://testingbot.com/tunnel/testingbot-tunnel.jar', { fileName: 'testingbot-tunnel', destination: tunnelLocation }, function(err, destination) {
		if (err) {
			return callback(new Error("Could not download the tunnel from TestingBot - please check your connection. " + err.message))
		}

		return callback(null);
	});
}

function run(options, callback)
{
	if (!fs.existsSync(tunnelLocation)) {
		return callback(new Error('Tunnel jar file is not present in ' + tunnelLocation));
	}

	var onReady = function() {
		started = true;
		logger("Tunnel is ready");
		callback(null, activeTunnel);
	};

	var args = [];

	args.push('-jar');
	args.push(tunnelLocation);

	if (options.apiKey) {
		args.push(options.apiKey);
	}

	if (options.apiSecret) {
		args.push(options.apiSecret);
	}

	for (var i in options) {
		if ((i === 'apiKey') || (i === 'apiSecret') || (i === 'verbose')) {
			continue;
		}

		if (options[i]) {
			args.push('--' + i);
			args.push(options[i]);
		} else {
			args.push('--' + i);
		}
	}

	var readyFile = path.normalize(__dirname + "/../testingbot.ready");

	args.push('-ftestingbot.ready');

	var readyFileChecker = setInterval(function() {
		fs.stat(readyFile, function (error, stat) {
			if (!error) {
				clearInterval(readyFileChecker);
				onReady();
			}
		});
	}, 800);

	if (options.verbose) {
		logger("Starting tunnel with options", args);
	}
	activeTunnel = spawn('java', args, {
	   detached: true
	});

	activeTunnel.unref();

	activeTunnel.stderr.on('data', function(data) {
		if (options.verbose && data !== "") {
	      logger(data.toString());
	    }
	});

	activeTunnel.stdout.on("data", function (data) {
	    data = data.toString().trim();
	    if (options.verbose && data !== "") {
	      logger(data.toString());
	    }
	});

	activeTunnel.close = function(closeCallback) {
		if (closeCallback) {
			activeTunnel.on("close", function () {
				closeCallback();
			});
	    }
	    activeTunnel.kill("SIGINT");
	};

	activeTunnel.on("exit", function (code, signal) {
	    logger("Closing TestingBot Tunnel");
	    if (!started) {
	      	callback(new Error("Could not start TestingBot Tunnel. Exit code " + code + " signal: " + signal));
	    }

	    started = false;
	    activeTunnel = null;
	});
}

function killTunnel(callback)
{
	if (!callback) {
		callback = function() {};
	}

	if (!activeTunnel) {
		return callback(new Error('no active tunnel'));
	}

	activeTunnel.kill("SIGINT");
}

function downloadAndRun(options, callback)
{
	if (!options) {
		options = {};
	}

	if (!callback) {
		callback = function() {};
	}

	async.waterfall([
	    async.apply(download, options),
	    async.apply(run, options)
	], callback);
}

process.on("exit", function () {
    logger("Shutting down tunnel");
    killTunnel();
});

module.exports = downloadAndRun;
module.exports.kill = killTunnel;<commit_msg>use tmpdir to save testingbot tunnel ready file<commit_after>var async = require('async');
var fs = require('fs');
var os = require('os');
var path = require('path');
var spawn = require('child_process').spawn;
var downloader = require('./downloader');
var tunnelLocation = path.normalize(__dirname + "/../testingbot-tunnel.jar");
var activeTunnel;
var started = false;

function logger(msg) {
	console.log.apply(console, arguments);
}

function download(options, callback)
{
	if (fs.existsSync(tunnelLocation)) {
		return callback(null);
	}

	downloader.get('https://testingbot.com/tunnel/testingbot-tunnel.jar', { fileName: 'testingbot-tunnel', destination: tunnelLocation }, function(err, destination) {
		if (err) {
			return callback(new Error("Could not download the tunnel from TestingBot - please check your connection. " + err.message))
		}

		return callback(null);
	});
}

function run(options, callback)
{
	if (!fs.existsSync(tunnelLocation)) {
		return callback(new Error('Tunnel jar file is not present in ' + tunnelLocation));
	}

	var onReady = function() {
		started = true;
		logger("Tunnel is ready");
		callback(null, activeTunnel);
	};

	var args = [];

	args.push('-jar');
	args.push(tunnelLocation);

	if (options.apiKey) {
		args.push(options.apiKey);
	}

	if (options.apiSecret) {
		args.push(options.apiSecret);
	}

	for (var i in options) {
		if ((i === 'apiKey') || (i === 'apiSecret') || (i === 'verbose')) {
			continue;
		}

		if (options[i]) {
			args.push('--' + i);
			args.push(options[i]);
		} else {
			args.push('--' + i);
		}
	}

	var readyFile = path.join(os.tmpdir(), "testingbot.ready");

	args.push('-f' + readyFile);

	var readyFileChecker = setInterval(function() {
		fs.stat(readyFile, function (error, stat) {
			if (!error) {
				clearInterval(readyFileChecker);
				onReady();
			}
		});
	}, 800);

	if (options.verbose) {
		logger("Starting tunnel with options", args);
	}
	activeTunnel = spawn('java', args, {
	   detached: true
	});

	activeTunnel.unref();

	activeTunnel.stderr.on('data', function(data) {
		if (options.verbose && data !== "") {
	      logger(data.toString());
	    }
	});

	activeTunnel.stdout.on("data", function (data) {
	    data = data.toString().trim();
	    if (options.verbose && data !== "") {
	      logger(data.toString());
	    }
	});

	activeTunnel.close = function(closeCallback) {
		if (closeCallback) {
			activeTunnel.on("close", function () {
				closeCallback();
			});
	    }
	    activeTunnel.kill("SIGINT");
	};

	activeTunnel.on("exit", function (code, signal) {
	    logger("Closing TestingBot Tunnel");
	    if (!started) {
	      	callback(new Error("Could not start TestingBot Tunnel. Exit code " + code + " signal: " + signal));
	    }

	    started = false;
	    activeTunnel = null;
	});
}

function killTunnel(callback)
{
	if (!callback) {
		callback = function() {};
	}

	if (!activeTunnel) {
		return callback(new Error('no active tunnel'));
	}

	activeTunnel.kill("SIGINT");
}

function downloadAndRun(options, callback)
{
	if (!options) {
		options = {};
	}

	if (!callback) {
		callback = function() {};
	}

	async.waterfall([
	    async.apply(download, options),
	    async.apply(run, options)
	], callback);
}

process.on("exit", function () {
    logger("Shutting down tunnel");
    killTunnel();
});

module.exports = downloadAndRun;
module.exports.kill = killTunnel;<|endoftext|>


<commit_before>export default class ShadowOverlay extends createjs.Container {
  constructor(width, height) {
    super();

    this.shadow = new createjs.Shape();
    this.shadow.graphics.beginFill('rgba(0, 0, 0, 0.6)').drawRect(0, 0, width, height);

    this.shadowText = new createjs.Text('', '25px Arial', '#fff');
    this.shadowText.y = height / 2;
    this.shadowText.x = width / 2;
    this.shadowText.textAlign = 'center';
    this.shadowText.textBaseline = 'middle';

    this.addChild(this.shadow, this.shadowText);
  }
  setText(text) {
    this.shadowText.text = text;
  }
}
<commit_msg>cache overlay<commit_after>export default class ShadowOverlay extends createjs.Container {
  constructor(width, height) {
    super();

    this.shadow = new createjs.Shape();
    this.shadow.graphics.beginFill('rgba(0, 0, 0, 0.6)').drawRect(0, 0, width, height);

    this.shadowText = new createjs.Text('', '25px Arial', '#fff');
    this.shadowText.y = height / 2;
    this.shadowText.x = width / 2;
    this.shadowText.textAlign = 'center';
    this.shadowText.textBaseline = 'middle';

    this.addChild(this.shadow, this.shadowText);
    this.cache(0, 0, width, height);
  }
  setText(text) {
    this.shadowText.text = text;
    this.updateCache();
  }
}
<|endoftext|>