<commit_before>// Copyright 2020, University of Colorado Boulder

// will be replaced by domain name in the future
var domain = 'phettest.colorado.edu';

// common repo fields
var commonSameMasterStatusElements = {};
var commonRows = [];
var outOfDateCommonRows = [];
var showAllCommon = true;
var showOutOfDateCommon = false
var commonCheckingStatus = document.getElementById( 'commonCheckingStatus' );

// sim repo fields
var simSameMasterStatusElements = {};
var simRows = [];
var outOfDateSimRows = [];
var showAllSims = true;
var showOutOfDateSims = false
var simCheckingStatus = document.getElementById( 'simCheckingStatus' );

function updateOutOfDateCommon() {
  outOfDateCommonRows.forEach( function( row ) {
    if ( !showAllCommon ) {
      row.style.display = showOutOfDateCommon ? 'table-row' : 'none';
    }
  } );
}

function updateAllCommon() {
  commonRows.forEach( function( row ) {
    row.style.display = showAllCommon ? 'table-row' : 'none';
  } );
}

var commonFilterRadioOut = document.getElementById( 'commonFilterRadioOut' );
commonFilterRadioOut.addEventListener( 'change', function() {
  commonFilter( true );
} );

var commonFilterRadioAll = document.getElementById( 'commonFilterRadioAll' );
commonFilterRadioAll.addEventListener( 'change', function() {
  commonFilter( false );
} );

function commonFilter( isFiltered ) {

  showOutOfDateCommon = isFiltered;
  showAllCommon = !isFiltered;

  commonCheckingStatus.style.display = isFiltered ? 'block' : 'none';

  updateAllCommon();
  isFiltered && updateOutOfDateCommon();
}

function updateOutOfDateSims() {
  outOfDateSimRows.forEach( function( row ) {
    if ( !showAllSims ) {
      row.style.display = showOutOfDateSims ? 'table-row' : 'none';
    }
  } );
}

function updateAllSims() {
  simRows.forEach( function( row ) {
    row.style.display = showAllSims ? 'table-row' : 'none';
  } );
}

var simFilterRadioOut = document.getElementById( 'simFilterRadioOut' );
simFilterRadioOut.addEventListener( 'change', function() {
  simFilter( true );
} );

var simFilterRadioAll = document.getElementById( 'simFilterRadioAll' );
simFilterRadioAll.addEventListener( 'change', function() {
  simFilter( false );
} );

function simFilter( isFiltered ) {

  showOutOfDateSims = isFiltered;
  showAllSims = !isFiltered;

  simCheckingStatus.style.display = isFiltered ? 'block' : 'none';

  updateAllSims();
  isFiltered && updateOutOfDateSims();
}

function checkSimSameMaster( reposToCheck ) {
  if ( reposToCheck === undefined ) {
    reposToCheck = Object.keys( simSameMasterStatusElements );
  }

  function checkSim( sim ) {
    var statusElement = simSameMasterStatusElements[ sim ].status;
    $( statusElement ).text( '?' );
    statusElement.className = 'masterStatus';
    $.ajax( 'http://' + domain + ':45362/same-as-remote-master?repo=' + sim ).done( function( data ) {
      if ( data.output === 'same' ) {
        $( statusElement ).text( 'up-to-date' );
        statusElement.className = 'masterStatus masterUpToDate'
        outOfDateSimRows = remove( outOfDateSimRows, simSameMasterStatusElements[ sim ].row );
      }
      else if ( data.output === 'different' ) {
        $( statusElement ).text( 'out-of-date' );
        statusElement.className = 'masterStatus masterOutOfDate'
        outOfDateSimRows.push( simSameMasterStatusElements[ sim ].row );
        updateOutOfDateSims();
      }
      else {
        $( statusElement ).text( 'failed' );
        statusElement.className = 'masterStatus masterFailed'
      }
      if ( reposToCheck.length ) {

        checkSim( reposToCheck.shift() );
      }
      else {

        updateSimCheckingStatus( true );
      }
    } ).fail( function() {
      $( statusElement ).text( 'failed' );
      statusElement.className = 'masterStatus masterFailed'
      reposToCheck.length && checkSim( reposToCheck.shift() );
    } );
  }

  checkSim( reposToCheck.shift() );
}

function updateSimCheckingStatus( done ) {

  if ( done ) {
    if ( outOfDateSimRows.length ) {
      $( simCheckingStatus ).text( '' );
    }
    else {
      $( simCheckingStatus ).text( 'No out-of-date simulation repositories!' );
    }
  }
  else {
    $( simCheckingStatus ).text( 'checking...' );
  }
}

function checkCommonSameMaster( reposToCheck ) {
  if ( reposToCheck === undefined ) {
    reposToCheck = Object.keys( commonSameMasterStatusElements );
  }

  function checkCommon( commonRepo ) {
    var statusElement = commonSameMasterStatusElements[ commonRepo ].status;
    $( statusElement ).text( '?' );
    statusElement.className = 'masterStatus';
    $.ajax( 'http://' + domain + ':45362/same-as-remote-master?repo=' + commonRepo ).done( function( data ) {
      if ( data.output === 'same' ) {
        $( statusElement ).text( 'up-to-date' );
        statusElement.className = 'masterStatus masterUpToDate'
        outOfDateCommonRows = remove( outOfDateCommonRows, commonSameMasterStatusElements[ commonRepo ].row );
      }
      else if ( data.output === 'different' ) {
        $( statusElement ).text( 'out-of-date' );
        statusElement.className = 'masterStatus masterOutOfDate'
        outOfDateCommonRows.push( commonSameMasterStatusElements[ commonRepo ].row );
        updateOutOfDateCommon();
      }
      else {
        $( statusElement ).text( 'failed' );
        statusElement.className = 'masterStatus masterFailed'
      }

      if ( reposToCheck.length ) {

        checkCommon( reposToCheck.shift() );
      }
      else {

        updateCommonCheckingStatus( true );
      }
    } ).fail( function() {
      $( statusElement ).text( 'failed' );
      statusElement.className = 'masterStatus masterFailed'
      reposToCheck.length && checkCommon( reposToCheck.shift() );
    } );
  }

  checkCommon( reposToCheck.shift() );
}

function updateCommonCheckingStatus( done ) {

  if ( done ) {
    if ( outOfDateCommonRows.length ) {
      $( commonCheckingStatus ).text( '' );
    }
    else {
      $( commonCheckingStatus ).text( 'No out-of-date common repositories!' );
    }
  }
  else {
    $( commonCheckingStatus ).text( 'checking...' );
  }
}

document.getElementById( 'pullAll' ).addEventListener( 'click', function() {
  var status = document.getElementById( 'pullStatus' );
  $( status ).text( 'pulling...' );
  $.ajax( 'http://' + domain + ':45362/pull-all' ).done( function( data ) {
    $( status ).text( '' );

    checkCommonSameMaster();
    checkSimSameMaster();
  } ).fail( function() {
    $( status ).text( 'pull failed' );
  } );
} );

document.getElementById( 'perennialRefresh' ).addEventListener( 'click', function() {
  var status = document.getElementById( 'perennialStatus' );
  $( status ).text( 'refreshing perennial' );
  $.ajax( 'http://' + domain + ':45362/perennial-refresh' ).done( function( data ) {
    $( status ).text( '' );

    updateCommonRepos();
    updateSims();
    updateCommonCheckingStatus( false );
    updateSimCheckingStatus( false );
  } ).fail( function() {
    $( status ).text( 'perennial refresh failed' );
  } );
} );

function remove( array, element ) {
  return array.filter( e => e !== element );
}

function updateCommonRepos() {
  var commonTable = document.getElementById( 'common' );
  while ( commonTable.childNodes.length ) {
    commonTable.removeChild( commonTable.childNodes[ 0 ] );
  }
  $.ajax( 'http://' + domain + ':45362/sim-list' ).done( function( data ) {
    var sims = data.output;

    $.ajax( 'http://' + domain + ':45362/repo-list' ).done( function( data ) {
      var repos = data.output;
      commonRepos = repos.filter( function( repo ) {
        return !_.includes( sims, repo );
      } );

      _.each( commonRepos, function( commonRepoName ) {
        // row
        var tr = document.createElement( 'tr' );
        commonTable.appendChild( tr );

        function cell( element ) {
          var td = document.createElement( 'td' );
          tr.appendChild( td );
          td.appendChild( element );
        }

        function linkCell( text, url ) {
          var a = document.createElement( 'a' );
          $( a ).text( text );
          a.href = url;
          cell( a );
        }

        function actionCell( text, url ) {
          var button = document.createElement( 'button' );
          var status = document.createElement( 'span' );
          status.className = 'status';
          $( button ).text( text );
          button.addEventListener( 'click', function() {
            $( status ).text( 'running' );
            $.ajax( url ).done( function handle( data ) {
              if ( data.success ) {
                $( status ).text( '' );
              }
              else {
                $( status ).text( 'failed' );
              }
              checkCommonSameMaster( [ commonRepoName ] );
            } ).fail( function() {
              $( status ).text( 'failed' );
            } );
          } );
          cell( button );
          cell( status );
        }

        function sameAsMasterCell( commonRepoName ) {
          var status = document.createElement( 'span' );
          status.className = 'masterStatus';
          $( status ).text( '?' );
          commonSameMasterStatusElements[ commonRepoName ] = { row: tr, status: status };
          cell( status );
        }

        var name = document.createElement( "div" );
        name.textContent = commonRepoName;
        cell( name );
        sameAsMasterCell( commonRepoName );
        actionCell( 'Pull', 'http://' + domain + ':45362/pull?sim=' + commonRepoName );
        linkCell( 'GitHub Issues', 'http://github.com/phetsims/' + commonRepoName + '/issues' );

        commonRows.push( tr );
      } );

      updateAllCommon();
      checkCommonSameMaster();
    } );
  } );
}

function updateSims() {
  var simsTable = document.getElementById( 'sims' );
  while ( simsTable.childNodes.length ) {
    simsTable.removeChild( simsTable.childNodes[ 0 ] );
  }
  $.ajax( 'http://' + domain + ':45362/sim-list' ).done( function( data ) {
    var sims = data.output;

    _.each( sims, function( simName ) {
      // row
      var tr = document.createElement( 'tr' );
      simsTable.appendChild( tr );

      function cell( element ) {
        var td = document.createElement( 'td' );
        tr.appendChild( td );
        td.appendChild( element );
      }

      function linkCell( text, url ) {
        var a = document.createElement( 'a' );
        $( a ).text( text );
        a.href = url;
        cell( a );
      }

      function actionCell( text, url ) {
        var button = document.createElement( 'button' );
        var status = document.createElement( 'span' );
        status.className = 'status';
        $( button ).text( text );
        button.addEventListener( 'click', function() {
          $( status ).text( 'running' );
          $.ajax( url ).done( function handle( data ) {
            if ( data.success ) {
              $( status ).text( '' );
            }
            else {
              $( status ).text( 'failed' );
            }
            checkSimSameMaster( [ simName ] );
          } ).fail( function( xhr ) {
            $( status ).text( 'failed' );
            console.error( xhr );
          } );
        } );
        cell( button );
        cell( status );
      }

      function sameAsMasterCell( simName ) {
        var status = document.createElement( 'span' );
        status.className = 'masterStatus';
        $( status ).text( '?' );
        simSameMasterStatusElements[ simName ] = { row: tr, status: status };
        cell( status );
      }

      linkCell( simName, 'http://' + domain + '/' + simName + '/' + simName + '_en.html?ea&brand=phet' );
      sameAsMasterCell( simName );
      actionCell( 'Pull', 'http://' + domain + ':45362/pull?sim=' + simName );
      actionCell( 'Build', 'http://' + domain + ':45362/build?sim=' + simName );
      linkCell( 'Built Version', 'http://' + domain + '/' + simName + '/build/phet/' + simName + '_en_phet.html' );
      linkCell( 'GitHub Issues', 'http://github.com/phetsims/' + simName + '/issues' );
      linkCell( 'Dev', 'https://phet-dev.colorado.edu/html/' + simName );
      linkCell( 'Production', 'http://phet.colorado.edu/sims/html/' + simName + '/latest/' + simName + '_en.html' );

      simRows.push( tr );
    } );

    updateAllSims();
    checkSimSameMaster();
  } );
}

updateCommonRepos();
updateSims();
updateCommonCheckingStatus( false );
updateSimCheckingStatus( false );
commonFilter( false );
simFilter( false );
  <commit_msg>lint, https://github.com/phetsims/phetmarks/issues/41<commit_after>// Copyright 2020, University of Colorado Boulder

// will be replaced by domain name in the future
var domain = 'phettest.colorado.edu';

// common repo fields
var commonSameMasterStatusElements = {};
var commonRows = [];
var outOfDateCommonRows = [];
var showAllCommon = true;
var showOutOfDateCommon = false;
var commonCheckingStatus = document.getElementById( 'commonCheckingStatus' );

// sim repo fields
var simSameMasterStatusElements = {};
var simRows = [];
var outOfDateSimRows = [];
var showAllSims = true;
var showOutOfDateSims = false;
var simCheckingStatus = document.getElementById( 'simCheckingStatus' );

function updateOutOfDateCommon() {
  outOfDateCommonRows.forEach( function( row ) {
    if ( !showAllCommon ) {
      row.style.display = showOutOfDateCommon ? 'table-row' : 'none';
    }
  } );
}

function updateAllCommon() {
  commonRows.forEach( function( row ) {
    row.style.display = showAllCommon ? 'table-row' : 'none';
  } );
}

var commonFilterRadioOut = document.getElementById( 'commonFilterRadioOut' );
commonFilterRadioOut.addEventListener( 'change', function() {
  commonFilter( true );
} );

var commonFilterRadioAll = document.getElementById( 'commonFilterRadioAll' );
commonFilterRadioAll.addEventListener( 'change', function() {
  commonFilter( false );
} );

function commonFilter( isFiltered ) {

  showOutOfDateCommon = isFiltered;
  showAllCommon = !isFiltered;

  commonCheckingStatus.style.display = isFiltered ? 'block' : 'none';

  updateAllCommon();
  isFiltered && updateOutOfDateCommon();
}

function updateOutOfDateSims() {
  outOfDateSimRows.forEach( function( row ) {
    if ( !showAllSims ) {
      row.style.display = showOutOfDateSims ? 'table-row' : 'none';
    }
  } );
}

function updateAllSims() {
  simRows.forEach( function( row ) {
    row.style.display = showAllSims ? 'table-row' : 'none';
  } );
}

var simFilterRadioOut = document.getElementById( 'simFilterRadioOut' );
simFilterRadioOut.addEventListener( 'change', function() {
  simFilter( true );
} );

var simFilterRadioAll = document.getElementById( 'simFilterRadioAll' );
simFilterRadioAll.addEventListener( 'change', function() {
  simFilter( false );
} );

function simFilter( isFiltered ) {

  showOutOfDateSims = isFiltered;
  showAllSims = !isFiltered;

  simCheckingStatus.style.display = isFiltered ? 'block' : 'none';

  updateAllSims();
  isFiltered && updateOutOfDateSims();
}

function checkSimSameMaster( reposToCheck ) {
  if ( reposToCheck === undefined ) {
    reposToCheck = Object.keys( simSameMasterStatusElements );
  }

  function checkSim( sim ) {
    var statusElement = simSameMasterStatusElements[ sim ].status;
    $( statusElement ).text( '?' );
    statusElement.className = 'masterStatus';
    $.ajax( 'http://' + domain + ':45362/same-as-remote-master?repo=' + sim ).done( function( data ) {
      if ( data.output === 'same' ) {
        $( statusElement ).text( 'up-to-date' );
        statusElement.className = 'masterStatus masterUpToDate';
        outOfDateSimRows = remove( outOfDateSimRows, simSameMasterStatusElements[ sim ].row );
      }
      else if ( data.output === 'different' ) {
        $( statusElement ).text( 'out-of-date' );
        statusElement.className = 'masterStatus masterOutOfDate';
        outOfDateSimRows.push( simSameMasterStatusElements[ sim ].row );
        updateOutOfDateSims();
      }
      else {
        $( statusElement ).text( 'failed' );
        statusElement.className = 'masterStatus masterFailed';
      }
      if ( reposToCheck.length ) {

        checkSim( reposToCheck.shift() );
      }
      else {

        updateSimCheckingStatus( true );
      }
    } ).fail( function() {
      $( statusElement ).text( 'failed' );
      statusElement.className = 'masterStatus masterFailed';
      reposToCheck.length && checkSim( reposToCheck.shift() );
    } );
  }

  checkSim( reposToCheck.shift() );
}

function updateSimCheckingStatus( done ) {

  if ( done ) {
    if ( outOfDateSimRows.length ) {
      $( simCheckingStatus ).text( '' );
    }
    else {
      $( simCheckingStatus ).text( 'No out-of-date simulation repositories!' );
    }
  }
  else {
    $( simCheckingStatus ).text( 'checking...' );
  }
}

function checkCommonSameMaster( reposToCheck ) {
  if ( reposToCheck === undefined ) {
    reposToCheck = Object.keys( commonSameMasterStatusElements );
  }

  function checkCommon( commonRepo ) {
    var statusElement = commonSameMasterStatusElements[ commonRepo ].status;
    $( statusElement ).text( '?' );
    statusElement.className = 'masterStatus';
    $.ajax( 'http://' + domain + ':45362/same-as-remote-master?repo=' + commonRepo ).done( function( data ) {
      if ( data.output === 'same' ) {
        $( statusElement ).text( 'up-to-date' );
        statusElement.className = 'masterStatus masterUpToDate';
        outOfDateCommonRows = remove( outOfDateCommonRows, commonSameMasterStatusElements[ commonRepo ].row );
      }
      else if ( data.output === 'different' ) {
        $( statusElement ).text( 'out-of-date' );
        statusElement.className = 'masterStatus masterOutOfDate';
        outOfDateCommonRows.push( commonSameMasterStatusElements[ commonRepo ].row );
        updateOutOfDateCommon();
      }
      else {
        $( statusElement ).text( 'failed' );
        statusElement.className = 'masterStatus masterFailed';
      }

      if ( reposToCheck.length ) {

        checkCommon( reposToCheck.shift() );
      }
      else {

        updateCommonCheckingStatus( true );
      }
    } ).fail( function() {
      $( statusElement ).text( 'failed' );
      statusElement.className = 'masterStatus masterFailed';
      reposToCheck.length && checkCommon( reposToCheck.shift() );
    } );
  }

  checkCommon( reposToCheck.shift() );
}

function updateCommonCheckingStatus( done ) {

  if ( done ) {
    if ( outOfDateCommonRows.length ) {
      $( commonCheckingStatus ).text( '' );
    }
    else {
      $( commonCheckingStatus ).text( 'No out-of-date common repositories!' );
    }
  }
  else {
    $( commonCheckingStatus ).text( 'checking...' );
  }
}

document.getElementById( 'pullAll' ).addEventListener( 'click', function() {
  var status = document.getElementById( 'pullStatus' );
  $( status ).text( 'pulling...' );
  $.ajax( 'http://' + domain + ':45362/pull-all' ).done( function( data ) {
    $( status ).text( '' );

    checkCommonSameMaster();
    checkSimSameMaster();
  } ).fail( function() {
    $( status ).text( 'pull failed' );
  } );
} );

document.getElementById( 'perennialRefresh' ).addEventListener( 'click', function() {
  var status = document.getElementById( 'perennialStatus' );
  $( status ).text( 'refreshing perennial' );
  $.ajax( 'http://' + domain + ':45362/perennial-refresh' ).done( function( data ) {
    $( status ).text( '' );

    updateCommonRepos();
    updateSims();
    updateCommonCheckingStatus( false );
    updateSimCheckingStatus( false );
  } ).fail( function() {
    $( status ).text( 'perennial refresh failed' );
  } );
} );

function remove( array, element ) {
  return array.filter( e => e !== element );
}

function updateCommonRepos() {
  var commonTable = document.getElementById( 'common' );
  while ( commonTable.childNodes.length ) {
    commonTable.removeChild( commonTable.childNodes[ 0 ] );
  }
  $.ajax( 'http://' + domain + ':45362/sim-list' ).done( function( data ) {
    var sims = data.output;

    $.ajax( 'http://' + domain + ':45362/repo-list' ).done( function( data ) {
      var repos = data.output;
      const commonRepos = repos.filter( function( repo ) {
        return !_.includes( sims, repo );
      } );

      _.each( commonRepos, function( commonRepoName ) {
        // row
        var tr = document.createElement( 'tr' );
        commonTable.appendChild( tr );

        function cell( element ) {
          var td = document.createElement( 'td' );
          tr.appendChild( td );
          td.appendChild( element );
        }

        function linkCell( text, url ) {
          var a = document.createElement( 'a' );
          $( a ).text( text );
          a.href = url;
          cell( a );
        }

        function actionCell( text, url ) {
          var button = document.createElement( 'button' );
          var status = document.createElement( 'span' );
          status.className = 'status';
          $( button ).text( text );
          button.addEventListener( 'click', function() {
            $( status ).text( 'running' );
            $.ajax( url ).done( function handle( data ) {
              if ( data.success ) {
                $( status ).text( '' );
              }
              else {
                $( status ).text( 'failed' );
              }
              checkCommonSameMaster( [ commonRepoName ] );
            } ).fail( function() {
              $( status ).text( 'failed' );
            } );
          } );
          cell( button );
          cell( status );
        }

        function sameAsMasterCell( commonRepoName ) {
          var status = document.createElement( 'span' );
          status.className = 'masterStatus';
          $( status ).text( '?' );
          commonSameMasterStatusElements[ commonRepoName ] = { row: tr, status: status };
          cell( status );
        }

        var name = document.createElement( 'div' );
        name.textContent = commonRepoName;
        cell( name );
        sameAsMasterCell( commonRepoName );
        actionCell( 'Pull', 'http://' + domain + ':45362/pull?sim=' + commonRepoName );
        linkCell( 'GitHub Issues', 'http://github.com/phetsims/' + commonRepoName + '/issues' );

        commonRows.push( tr );
      } );

      updateAllCommon();
      checkCommonSameMaster();
    } );
  } );
}

function updateSims() {
  var simsTable = document.getElementById( 'sims' );
  while ( simsTable.childNodes.length ) {
    simsTable.removeChild( simsTable.childNodes[ 0 ] );
  }
  $.ajax( 'http://' + domain + ':45362/sim-list' ).done( function( data ) {
    var sims = data.output;

    _.each( sims, function( simName ) {
      // row
      var tr = document.createElement( 'tr' );
      simsTable.appendChild( tr );

      function cell( element ) {
        var td = document.createElement( 'td' );
        tr.appendChild( td );
        td.appendChild( element );
      }

      function linkCell( text, url ) {
        var a = document.createElement( 'a' );
        $( a ).text( text );
        a.href = url;
        cell( a );
      }

      function actionCell( text, url ) {
        var button = document.createElement( 'button' );
        var status = document.createElement( 'span' );
        status.className = 'status';
        $( button ).text( text );
        button.addEventListener( 'click', function() {
          $( status ).text( 'running' );
          $.ajax( url ).done( function handle( data ) {
            if ( data.success ) {
              $( status ).text( '' );
            }
            else {
              $( status ).text( 'failed' );
            }
            checkSimSameMaster( [ simName ] );
          } ).fail( function( xhr ) {
            $( status ).text( 'failed' );
            console.error( xhr );
          } );
        } );
        cell( button );
        cell( status );
      }

      function sameAsMasterCell( simName ) {
        var status = document.createElement( 'span' );
        status.className = 'masterStatus';
        $( status ).text( '?' );
        simSameMasterStatusElements[ simName ] = { row: tr, status: status };
        cell( status );
      }

      linkCell( simName, 'http://' + domain + '/' + simName + '/' + simName + '_en.html?ea&brand=phet' );
      sameAsMasterCell( simName );
      actionCell( 'Pull', 'http://' + domain + ':45362/pull?sim=' + simName );
      actionCell( 'Build', 'http://' + domain + ':45362/build?sim=' + simName );
      linkCell( 'Built Version', 'http://' + domain + '/' + simName + '/build/phet/' + simName + '_en_phet.html' );
      linkCell( 'GitHub Issues', 'http://github.com/phetsims/' + simName + '/issues' );
      linkCell( 'Dev', 'https://phet-dev.colorado.edu/html/' + simName );
      linkCell( 'Production', 'http://phet.colorado.edu/sims/html/' + simName + '/latest/' + simName + '_en.html' );

      simRows.push( tr );
    } );

    updateAllSims();
    checkSimSameMaster();
  } );
}

updateCommonRepos();
updateSims();
updateCommonCheckingStatus( false );
updateSimCheckingStatus( false );
commonFilter( false );
simFilter( false );
  <|endoftext|>


<commit_before>function getSearchText() {
    /*
     * Gets the predefined search text from the current page url
     */
    var searchText = "";
    if (window.location.hash !== "") {
      searchText = window.location.hash.substring(1);
    }
    return searchText;
}

function drawNodeListTable(searchText) {
    /*
     * Creates a list of nodes DataTable
     */
    oTable = $('#nodes').dataTable({
        "bPaginate": false,
        "oLanguage": {
            "sSearch": "",
            "sInfo" : "Showing _TOTAL_ nodes",
            "sInfoEmpty": "No nodes found",
            "sInfoFiltered": " (filtering from _MAX_ total)",
            "sZeroRecords": "No nodes to display"
        },
        "oSearch": {
            "sSearch": searchText,
        },
        "aoColumnDefs": [
            /* Expander */ { "bSortable": false, "aTargets": [0] },
        ],
        "sDom": '<"top"if>rt<"bottom"lp><"clear">'
    });
    setSearchBox();
    setExtendedRows(oTable, 1);
}

function drawNodeVirtTable(searchText) {
    /*
     * Creates the guests DataTable, grouped by hosts
     */
    oTable = $('#nodes').dataTable({
        "fnDrawCallback": function (oSettings) {
            if (oSettings.aiDisplay.length == 0) {
                return;
            }
            var nTrs = $('#nodes tbody tr');
            var iColspan = nTrs[0].getElementsByTagName('td').length;
            var sLastGroup = "";
            for (var i=0;i<nTrs.length;i++) {
                var iDisplayIndex = oSettings._iDisplayStart + i;
                var sGroup = oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[1];
                if (sGroup != sLastGroup) {
                    var nGroup = document.createElement('tr');
                    var nCell = document.createElement('td');
                    nCell.colSpan = iColspan;
                    nCell.id = "host_grouper";
                    nCell.innerHTML = sGroup;
                    nGroup.appendChild(nCell);
                    nTrs[i].parentNode.insertBefore(nGroup, nTrs[i]);
                    sLastGroup = sGroup;
                }
            }
        },
        "bPaginate": false,
        "oLanguage": {
            "sSearch": "",
            "sInfo" : "Showing _TOTAL_ nodes",
            "sInfoEmpty": "No nodes found",
            "sInfoFiltered": " (filtering from _MAX_ total)",
            "sZeroRecords": "No nodes to display"
        },
        "oSearch": {
            "sSearch": searchText,
        },
        "aoColumnDefs": [
            /* Expander */ { "bSortable": false, "aTargets": [0] },
            /* Grouper */ { "bVisible": false, "aTargets": [1] }
        ],
        "aaSortingFixed": [[ 1, 'asc' ]],
        "aaSorting": [[ 2, 'asc' ]],
        "sDom": '<"top"if>rt<"bottom"lp><"clear">'
    });

    setSearchBox();
    setExtendedRows(oTable, 2);
}

function setSearchBox() {
    /*
    * Sets a predefined string inside the DataTables filter box
    */
    $('#nodes_filter input').attr("placeholder", "Search");
    $('#nodes_filter input:text').focus();
}

function setExtendedRows(oTable, nodeNamePosition) {
    /*
     * Sets an event listener for opening and closing details
     */
    $('#nodes td.control').html('');
    $('#nodes td.control').live('click', function () {
        var nTr = $(this).parents('tr')[0];
        if (oTable.fnIsOpen(nTr)) {
            $(this).html('');
            oTable.fnClose(nTr);
        }
        else {
            $(this).html('');
            oTable.fnOpen(nTr, fnFormatNodeDetails(oTable, nTr, nodeNamePosition), 'details');
        }
    } );
}

function fnFormatNodeDetails (oTable, nTr, nodeNamePosition) {
    /*
     * Establishes the content of the extended row
     */
    var aData = oTable.fnGetData(nTr);
    var node = undefined;
    for(var i=0;i<nodes.length;i++) {
        if (nodes[i].name.substring(0, aData[nodeNamePosition].length) == aData[nodeNamePosition]) {
            node = nodes[i];
            break;
        }
    }
    var sOut = '
';
    nodeJson = syntaxHighlight(JSON.stringify(node, undefined, 4));
    sOut += nodeJson;
    sOut += '
';
    return sOut;
}

function syntaxHighlight(json) {
    /*
    * Highlights JSON code
    */
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '' + match + '';
    });
}
<commit_msg>Get predefined search text from the url<commit_after>function getSearchText() {
    /*
     * Gets the predefined search text from the &search page url parameter
     */
    searchText = window.location.search.split("&search=")[1];
    if (searchText == undefined) {
        return "";
    } else {
        searchText = searchText.split("&")[0]
        return searchText;
    }
}

function drawNodeListTable(searchText) {
    /*
     * Creates a list of nodes DataTable
     */
    oTable = $('#nodes').dataTable({
        "bPaginate": false,
        "oLanguage": {
            "sSearch": "",
            "sInfo" : "Showing _TOTAL_ nodes",
            "sInfoEmpty": "No nodes found",
            "sInfoFiltered": " (filtering from _MAX_ total)",
            "sZeroRecords": "No nodes to display"
        },
        "oSearch": {
            "sSearch": searchText,
        },
        "aoColumnDefs": [
            /* Expander */ { "bSortable": false, "aTargets": [0] },
        ],
        "sDom": '<"top"if>rt<"bottom"lp><"clear">'
    });
    setSearchBox();
    setExtendedRows(oTable, 1);
}

function drawNodeVirtTable(searchText) {
    /*
     * Creates the guests DataTable, grouped by hosts
     */
    oTable = $('#nodes').dataTable({
        "fnDrawCallback": function (oSettings) {
            if (oSettings.aiDisplay.length == 0) {
                return;
            }
            var nTrs = $('#nodes tbody tr');
            var iColspan = nTrs[0].getElementsByTagName('td').length;
            var sLastGroup = "";
            for (var i=0;i<nTrs.length;i++) {
                var iDisplayIndex = oSettings._iDisplayStart + i;
                var sGroup = oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[1];
                if (sGroup != sLastGroup) {
                    var nGroup = document.createElement('tr');
                    var nCell = document.createElement('td');
                    nCell.colSpan = iColspan;
                    nCell.id = "host_grouper";
                    nCell.innerHTML = sGroup;
                    nGroup.appendChild(nCell);
                    nTrs[i].parentNode.insertBefore(nGroup, nTrs[i]);
                    sLastGroup = sGroup;
                }
            }
        },
        "bPaginate": false,
        "oLanguage": {
            "sSearch": "",
            "sInfo" : "Showing _TOTAL_ nodes",
            "sInfoEmpty": "No nodes found",
            "sInfoFiltered": " (filtering from _MAX_ total)",
            "sZeroRecords": "No nodes to display"
        },
        "oSearch": {
            "sSearch": searchText,
        },
        "aoColumnDefs": [
            /* Expander */ { "bSortable": false, "aTargets": [0] },
            /* Grouper */ { "bVisible": false, "aTargets": [1] }
        ],
        "aaSortingFixed": [[ 1, 'asc' ]],
        "aaSorting": [[ 2, 'asc' ]],
        "sDom": '<"top"if>rt<"bottom"lp><"clear">'
    });

    setSearchBox();
    setExtendedRows(oTable, 2);
}

function setSearchBox() {
    /*
    * Sets a predefined string inside the DataTables filter box
    */
    $('#nodes_filter input').attr("placeholder", "Search");
    $('#nodes_filter input:text').focus();
}

function setExtendedRows(oTable, nodeNamePosition) {
    /*
     * Sets an event listener for opening and closing details
     */
    $('#nodes td.control').html('');
    $('#nodes td.control').live('click', function () {
        var nTr = $(this).parents('tr')[0];
        if (oTable.fnIsOpen(nTr)) {
            $(this).html('');
            oTable.fnClose(nTr);
        }
        else {
            $(this).html('');
            oTable.fnOpen(nTr, fnFormatNodeDetails(oTable, nTr, nodeNamePosition), 'details');
        }
    } );
}

function fnFormatNodeDetails (oTable, nTr, nodeNamePosition) {
    /*
     * Establishes the content of the extended row
     */
    var aData = oTable.fnGetData(nTr);
    var node = undefined;
    for(var i=0;i<nodes.length;i++) {
        if (nodes[i].name.substring(0, aData[nodeNamePosition].length) == aData[nodeNamePosition]) {
            node = nodes[i];
            break;
        }
    }
    var sOut = '
';
    nodeJson = syntaxHighlight(JSON.stringify(node, undefined, 4));
    sOut += nodeJson;
    sOut += '
';
    return sOut;
}

function syntaxHighlight(json) {
    /*
    * Highlights JSON code
    */
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '' + match + '';
    });
}
<|endoftext|>


<commit_before>#!/usr/bin/env seed
Seed.import_namespace("Clutter");

Clutter.init(null, null);

colors = [ "blanched almond",
	   "OldLace",
	   "MistyRose",
	   "White",
	   "LavenderBlush",
	   "CornflowerBlue",
	   "chartreuse",
	   "chocolate",
	   "light coral",
	   "medium violet red",
	   "LemonChiffon2",
	   "RosyBrown3"];

function alpha_func(alpha)
{
    try
    {
	    timeline = alpha.get_timeline();
	    frame = timeline.get_current_frame();
	    n_frames = timeline.num_frames;
	    fps = timeline.fps;
	    duration = n_frames/fps;
	    time = frame/fps;

	    if ((time/=duration) < (1/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625*time*time);
	    else if (time < (2/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
						(time-=(1.5/2.75))*time+.75);
	    else if (time < (2.5/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
						(time-=(2.25/2.75))*time+.9375);
	    else
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 * (time-=
							  (2.625/2.75))*time+.984375);

    }
    catch (e)
    {
	    Seed.print(e.message);
    }
}

var stage = new Clutter.Stage();
stage.signal.hide.connect(Clutter.main_quit);
var timeline = new Clutter.Timeline({fps:60, num_frames:300});
stage.show_all();

var rheight = stage.height/(colors.length);
var width = stage.width;
var rectangles = new Array(colors.length);

var black = Clutter.Color._new();
Clutter.color_parse("Black", black);
var white = Clutter.Color._new();
Clutter.color_parse("White", white);

stage.color = black;

for (var i = 0; i < colors.length; i++)
{
	var c = Clutter.Color._new();
	Clutter.color_parse(colors[i],c);

	var r = new Clutter.Rectangle();
	r.width = r.height = rheight;
	r.color = c;
	r.y = i * r.height+r.height/2;

	r.anchor_x = r.height/2;
	r.anchor_y = r.height/2;

	stage.add_actor(r);
	rectangles[i] = r;
}
// Was initially intended as a test to see if performance was accetable to do
// custom animations at 60fps. Turns out to be fine, serves as an example now.
timeline.signal.new_frame.connect(
	function(timeline, frame_num)
	{
		for (var i = 0; i < colors.length; i++)
		{
			rectangles[i].x += width/600;
			rectangles[i].rotation_angle_z += 1;
		}
	});
timeline.signal.completed.connect(
	function(timeline)
	{

		var text = new Clutter.Label({text:"Congratulations!",
					  font_name:"Bitstream Vera Sans 40"});
		var fadeline = new Clutter.Timeline({fps:60, num_frames:200});
		var effect = Clutter.EffectTemplate._new(timeline,
							 alpha_func);

		text.show();
		stage.add_actor(text);
		text.color = white;

		text.anchor_x = text.width/2;
		text.anchor_y = text.height/2;

		text.x = stage.width/2;

		text.y = -text.height;
		Clutter.effect_move(effect,
				    text,
				    text.x,
				    stage.height/2);

		for (i in rectangles)
		{
        	        Clutter.effect_fade(effect, rectangles[i],
					0);
			Clutter.effect_move(effect, rectangles[i],
					    Math.random()*stage.width,
					    Math.random()*stage.height/2 +
					    stage.height/2);
		}
	});

timeline.start();

Clutter.main();

<commit_msg>Deprecated ._new stuff in clutter example.<commit_after>#!/usr/bin/env seed
Seed.import_namespace("Clutter");

Clutter.init(null, null);

colors = [ "blanched almond",
	   "OldLace",
	   "MistyRose",
	   "White",
	   "LavenderBlush",
	   "CornflowerBlue",
	   "chartreuse",
	   "chocolate",
	   "light coral",
	   "medium violet red",
	   "LemonChiffon2",
	   "RosyBrown3"];

function alpha_func(alpha)
{
    try
    {
	    timeline = alpha.get_timeline();
	    frame = timeline.get_current_frame();
	    n_frames = timeline.num_frames;
	    fps = timeline.fps;
	    duration = n_frames/fps;
	    time = frame/fps;

	    if ((time/=duration) < (1/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625*time*time);
	    else if (time < (2/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
						(time-=(1.5/2.75))*time+.75);
	    else if (time < (2.5/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
						(time-=(2.25/2.75))*time+.9375);
	    else
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 * (time-=
							  (2.625/2.75))*time+.984375);

    }
    catch (e)
    {
	    Seed.print(e.message);
    }
}

var stage = new Clutter.Stage();
stage.signal.hide.connect(Clutter.main_quit);
var timeline = new Clutter.Timeline({fps:60, num_frames:300});
stage.show_all();

var rheight = stage.height/(colors.length);
var width = stage.width;
var rectangles = new Array(colors.length);

var black = new Clutter.Color();
Clutter.color_parse("Black", black);
var white = new Clutter.Color();
Clutter.color_parse("White", white);

stage.color = black;

for (var i = 0; i < colors.length; i++)
{
	var c = new Clutter.Color();
	Clutter.color_parse(colors[i],c);

	var r = new Clutter.Rectangle();
	r.width = r.height = rheight;
	r.color = c;
	r.y = i * r.height+r.height/2;

	r.anchor_x = r.height/2;
	r.anchor_y = r.height/2;

	stage.add_actor(r);
	rectangles[i] = r;
}
// Was initially intended as a test to see if performance was accetable to do
// custom animations at 60fps. Turns out to be fine, serves as an example now.
timeline.signal.new_frame.connect(
	function(timeline, frame_num)
	{
		for (var i = 0; i < colors.length; i++)
		{
			rectangles[i].x += width/600;
			rectangles[i].rotation_angle_z += 1;
		}
	});
timeline.signal.completed.connect(
	function(timeline)
	{

		var text = new Clutter.Label({text:"Congratulations!",
					  font_name:"Bitstream Vera Sans 40"});
		var fadeline = new Clutter.Timeline({fps:60, num_frames:200});
		var effect = Clutter.EffectTemplate._new(timeline,
							 alpha_func);

		text.show();
		stage.add_actor(text);
		text.color = white;

		text.anchor_x = text.width/2;
		text.anchor_y = text.height/2;

		text.x = stage.width/2;

		text.y = -text.height;
		Clutter.effect_move(effect,
				    text,
				    text.x,
				    stage.height/2);

		for (i in rectangles)
		{
        	        Clutter.effect_fade(effect, rectangles[i],
					0);
			Clutter.effect_move(effect, rectangles[i],
					    Math.random()*stage.width,
					    Math.random()*stage.height/2 +
					    stage.height/2);
		}
	});

timeline.start();

Clutter.main();

<|endoftext|>


<commit_before>var _; // globals

describe("About Applying What We Have Learnt", function() {
  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  }); //CONGRATULATIONS SAN FRANCISCO, YOU RUINED PIZZA!

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {
    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {
      var productsICanEat = [];
          /* solve using filter() & all() / any() */
          var hasNuts = function(pizza) {
              return pizza.containsNuts;
          };

          var hasMush = function(pizza) {
              return _(pizza.ingredients).any(function(x) {
                  return x === "mushrooms";
              });
          };

          productsICanEat = products.filter(function(x) {
              return (!hasNuts(x) && !hasMush(x));
          });

          expect(productsICanEat.length).toBe(1);
      });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {
    var sum = 0;

    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {
    var sum = 0;
    /* try chaining range() and reduce() */

    sum = _.chain(_.range(1, 1000))
                    .filter(function(x) { return (x % 3 === 0 || x % 5 === 0) } )
                    .reduce(function(sum, x) { return sum + x } )
                    .value();

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(2);
  });

// This solution works, but does not use the Reduce function. I don't know if it's the answer you're looking for.
  it("should count the ingredient occurrence (functional)", function () {
  var ingredientCount = { "{ingredient name}": 0 };

   ingredientCountArray =  _.chain(products)
                      .map(function (cv, i, products) {return products[i].ingredients;})
                      .flatten()
                      .map(function (cv, i) {
                        if(ingredientCount[cv] == undefined || ingredientCount[cv] == NaN) { ingredientCount[cv] = 1 } else {
                          ingredientCount[cv] = ingredientCount[cv] + 1 }
                        })
                     .value();

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  it("should find the largest prime factor of a composite number", function () {

    var findPrimes = function(maxValue, primes, value) {
        if (primes === undefined || value === undefined) {
            var primes = [2];
            var value = 3;
        };
        if (value <= maxValue) {
            if (primes.some(function(el) {
                return value % el === 0
            })) {
                return findPrimes(maxValue, primes, value + 2);
            } else {
                primes.push(value);
                return findPrimes(maxValue, primes, value + 2);
            };
        };
        return primes;
    };

    var largestPrimeFactor = function(composite){
      var primesLower = findPrimes(composite - 1);
      primesLower.reverse();
      for(var i = 0; i < primesLower.length; i++){
          if(composite % primesLower[i] === 0){
            var output = primesLower[i];
                        i = primesLower.length + 1;
          } // end if
      }; // end for
      return output;
    };

  expect(largestPrimeFactor(600)).toBe(5);
  });
/*
  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });

*/

});
<commit_msg>Solved Largest Palendrome Problem, mod: koans/AboutApplyingWhatWeHaveLearnt.js<commit_after>var _; // globals

describe("About Applying What We Have Learnt", function() {
  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  }); //CONGRATULATIONS SAN FRANCISCO, YOU RUINED PIZZA!

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {
    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {
      var productsICanEat = [];
          /* solve using filter() & all() / any() */
          var hasNuts = function(pizza) {
              return pizza.containsNuts;
          };

          var hasMush = function(pizza) {
              return _(pizza.ingredients).any(function(x) {
                  return x === "mushrooms";
              });
          };

          productsICanEat = products.filter(function(x) {
              return (!hasNuts(x) && !hasMush(x));
          });

          expect(productsICanEat.length).toBe(1);
      });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {
    var sum = 0;

    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {
    var sum = 0;
    /* try chaining range() and reduce() */

    sum = _.chain(_.range(1, 1000))
                    .filter(function(x) { return (x % 3 === 0 || x % 5 === 0) } )
                    .reduce(function(sum, x) { return sum + x } )
                    .value();

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(2);
  });

// This solution works, but does not use the Reduce function. I don't know if it's the answer you're looking for.
  it("should count the ingredient occurrence (functional)", function () {
  var ingredientCount = { "{ingredient name}": 0 };

   ingredientCountArray =  _.chain(products)
                      .map(function (cv, i, products) {return products[i].ingredients;})
                      .flatten()
                      .map(function (cv, i) {
                        if(ingredientCount[cv] == undefined || ingredientCount[cv] == NaN) { ingredientCount[cv] = 1 } else {
                          ingredientCount[cv] = ingredientCount[cv] + 1 }
                        })
                     .value();

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  it("should find the largest prime factor of a composite number", function () {

    var findPrimes = function(maxValue, primes, value) {
        if (primes === undefined || value === undefined) {
            var primes = [2];
            var value = 3;
        };
        if (value <= maxValue) {
            if (primes.some(function(el) {
                return value % el === 0
            })) {
                return findPrimes(maxValue, primes, value + 2);
            } else {
                primes.push(value);
                return findPrimes(maxValue, primes, value + 2);
            };
        };
        return primes;
    };

    var largestPrimeFactor = function(composite){
      var primesLower = findPrimes(composite - 1);
      primesLower.reverse();
      for(var i = 0; i < primesLower.length; i++){
          if(composite % primesLower[i] === 0){
            var output = primesLower[i];
                        i = primesLower.length + 1;
          } // end if
      }; // end for
      return output;
    };

  expect(largestPrimeFactor(600)).toBe(5);
  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

    var isPalindrome = function(test){
      strTest = test.toString();
      if(
        strTest.charAt(0) === strTest.charAt(strTest.length-1) &&
        strTest.charAt(1) === strTest.charAt(strTest.length-2) &&
        strTest.charAt(2) === strTest.charAt(strTest.length-3) ){
        return true;
      } else {
        return false;
      }; // This simple test works for all 5 digit and 6 digit numbers. I could impliment a more inclusive version using recrusion to test whether ANY string is a palindrome, but that's not part of the assignment.
    };

    var largestPalindrome = function(){
    var king = 0;
    var challenger = 0;
    var i, j; //brute force okay with you?
      for(i = 100; i < 1000; i++){
        for(j = 100; j < 1000; j++){
          challenger = i * j;
          if( isPalindrome(challenger) && challenger > king){king = challenger; console.log(i + " , " + j + "king: " + king)};
        }
      }
    return king;
    };

    expect(largestPalindrome()).toBe(906609); // 913 * 993)
  });
/*
  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });

*/

});
<|endoftext|>


<commit_before>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */
      productsICanEat = _.filter(products, function(product){
             return (!product.containsNuts &&
                      _.all(product.ingredients, function(ingredient){
                        return !(ingredient === "mushrooms")
                      })
                    )
        });

      expect(productsICanEat.length).toBe(1);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = FILL_ME_IN;    /* try chaining range() and reduce() */

    expect(233168).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */
  /*
  it("should find the largest prime factor of a composite number", function () {

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });
  */
});
<commit_msg>Complete koans   51 in 9.AboutApplyingWhatWeHaveLearned.js<commit_after>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */
      productsICanEat = _.filter(products, function(product){
             return (!product.containsNuts &&
                      _.all(product.ingredients, function(ingredient){
                        return !(ingredient === "mushrooms")
                      })
                    )
        });

      expect(productsICanEat.length).toBe(1);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = _.reduce(_.range(1000), function(sum, num){
      if (num % 3 === 0 || num % 5 === 0) return sum + num
        else return sum;
    },0);    /* try chaining range() and reduce() */

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */
  /*
  it("should find the largest prime factor of a composite number", function () {

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });
  */
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         nuget.org to fuget.org
// @namespace    https://github.com/nordinrahman/
// @version      0.1
// @description  Add link to fuget.org from nuget.org page
// @author       Nordin Rahman
// @copyright    2018, Nordin Rahman
// @license      MIT; https://opensource.org/licenses/MIT
// supportURL    https://github.com/nordinrahman/userscript/issues
// @match        https://www.nuget.org/packages/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';
    $("<li>")
        .append($("<i>")
            .addClass("ms-Icon ms-Icon--Globe")
            .attr("aria-hidden", true))
        .append($("<a>")
            .attr("href", document.URL.toString().replace("://www.nuget.org/", "://www.fuget.org/"))
            .attr("target", "_blank")
            .attr("title", "Visit nuget package browser combined with an API browser")
            .text("Open in fuget.org"))
        .appendTo($(".package-details-info>ul").get(0));
})();
<commit_msg>Another update to nuget-to-fuget.user.js license statement<commit_after>// ==UserScript==
// @name         nuget.org to fuget.org
// @namespace    https://github.com/nordinrahman/
// @version      0.1
// @description  Add link to fuget.org from nuget.org page
// @author       Nordin Rahman
// @copyright    2018, Nordin Rahman
// @license      MIT license (MIT)
// supportURL    https://github.com/nordinrahman/userscript/issues
// @match        https://www.nuget.org/packages/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';
    $("<li>")
        .append($("<i>")
            .addClass("ms-Icon ms-Icon--Globe")
            .attr("aria-hidden", true))
        .append($("<a>")
            .attr("href", document.URL.toString().replace("://www.nuget.org/", "://www.fuget.org/"))
            .attr("target", "_blank")
            .attr("title", "Visit nuget package browser combined with an API browser")
            .text("Open in fuget.org"))
        .appendTo($(".package-details-info>ul").get(0));
})();
<|endoftext|>


<commit_before>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */
      var noNuts = _.where(products, { containsNuts: false });
      productsICanEat = _.filter(noNuts, function(product) {
        return _.all(product.ingredients, function(ingredient) { return ingredient !== "mushrooms"; });
      });

      expect(productsICanEat.length).toBe(1);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(FILL_ME_IN);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = FILL_ME_IN;    /* try chaining range() and reduce() */

    expect(233168).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */
  /*
  it("should find the largest prime factor of a composite number", function () {

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });
  */
});
<commit_msg>the adding of mulitples of 3 and 5 tests are passing<commit_after>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */
      var noNuts = _.where(products, { containsNuts: false });
      productsICanEat = _.filter(noNuts, function(product) {
        return _.all(product.ingredients, function(ingredient) { return ingredient !== "mushrooms"; });
      });

      expect(productsICanEat.length).toBe(1);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = _.chain(_.range(1000))
      .filter(function(n) { return n % 3 === 0 || n % 5 === 0; })
      .reduce(function(memo, x) { return memo + x; })
      .value();

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */
  /*
  it("should find the largest prime factor of a composite number", function () {

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });
  */
});
<|endoftext|>


<commit_before>module.exports = [
  {
    name: 'Per Guth',
    role: 'Project Manager / P2P-Guru / Scrummy Thing',
    img: 'https://avatars1.githubusercontent.com/u/85259?v=3&s=400',
    github: 'https://github.com/pguth',
    homepage: 'https://pguth.js.org',
    desc: '"Can we teach people, not just to code, but to demand the right to participate in shaping society?"'
  },
  {
    name: 'Paul Sonnentag',
    role: 'Technical Lead / Mr. JavaScript',
    img: 'https://avatars1.githubusercontent.com/u/650540?v=3&s=400',
    github: 'https://github.com/paulsonnentag',
    homepage: 'http://paulsonnentag.com',
    desc: 'Passionate developer, studying computer science. At home on the web. Building things with JavaScript, Elm and Clojure.'
  },
  {
    name: 'Johannes Klakhöfer',
    role: 'Developer / Evil Mind',
    img: 'https://avatars1.githubusercontent.com/u/5808849?v=3&s=400',
    github: 'https://github.com/H3rby7',
    desc: 'Laberei, laber laber bla laber labbellabab laber laber, label babel laber lab.'
  },
  {
    name: 'Tim Großmann',
    role: 'Developer',
    img: 'https://avatars3.githubusercontent.com/u/16529337?v=3&s=400',
    github: 'https://github.com/timgrossmann',
    desc: 'Passionate learner and developer. Studying computer science at the Media University. Looking forward to work with ingenious teams on challenging projects.'
  },
  {
    name: 'David Reeß',
    role: 'Consultant',
    img: 'https://avatars2.githubusercontent.com/u/4615516?v=3&s=400',
    github: 'https://github.com/queicherius',
    homepage: 'https://david-reess.de',
    desc: 'Full stack developer, currently in love with JavaScript. Main pet project is @gw2efficiency'
  },
  {
    name: 'Emre Kecik',
    role: 'User Testing',
    img: '../assets/img/emre.jpg',
    github: 'https://github.com/robotopia-x/robotopia',
    desc: 'Laberei, laber laber bla laber labbellabab laber laber, label babel laber lab.'
  }
]
<commit_msg>removed laberei<commit_after>module.exports = [
  {
    name: 'Per Guth',
    role: 'Project Manager / P2P-Guru / Scrummy Thing',
    img: 'https://avatars1.githubusercontent.com/u/85259?v=3&s=400',
    github: 'https://github.com/pguth',
    homepage: 'https://pguth.js.org',
    desc: '"Can we teach people, not just to code, but to demand the right to participate in shaping society?"'
  },
  {
    name: 'Paul Sonnentag',
    role: 'Technical Lead / Mr. JavaScript',
    img: 'https://avatars1.githubusercontent.com/u/650540?v=3&s=400',
    github: 'https://github.com/paulsonnentag',
    homepage: 'http://paulsonnentag.com',
    desc: 'Passionate developer, studying computer science. At home on the web. Building things with JavaScript, Elm and Clojure.'
  },
  {
    name: 'Johannes Klakhöfer',
    role: 'Developer / Evil Mind',
    img: 'https://avatars1.githubusercontent.com/u/5808849?v=3&s=400',
    github: 'https://github.com/H3rby7',
    desc: ''
  },
  {
    name: 'Tim Großmann',
    role: 'Developer',
    img: 'https://avatars3.githubusercontent.com/u/16529337?v=3&s=400',
    github: 'https://github.com/timgrossmann',
    desc: 'Passionate learner and developer. Studying computer science at the Media University. Looking forward to work with ingenious teams on challenging projects.'
  },
  {
    name: 'David Reeß',
    role: 'Consultant',
    img: 'https://avatars2.githubusercontent.com/u/4615516?v=3&s=400',
    github: 'https://github.com/queicherius',
    homepage: 'https://david-reess.de',
    desc: 'Full stack developer, currently in love with JavaScript. Main pet project is @gw2efficiency'
  },
  {
    name: 'Emre Kecik',
    role: 'User Testing',
    img: '../assets/img/emre.jpg',
    github: 'https://github.com/robotopia-x/robotopia',
    desc: ''
  }
]
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { TouchableHighlight, Image } from 'react-native';
import styles from './styles/ActorImageStyle';
<commit_msg>Add ActorImage component for showing actors image<commit_after>import React, { Component } from 'react';
import { TouchableOpacity, Image } from 'react-native';
import styles from './styles/ActorImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';

export default class ActorImage extends Component {
  static propTypes = {
    onPress: PropTypes.func,
    text: PropTypes.object,
    children: PropTypes.string,
    navigation: PropTypes.object
  }

  render() {
    return (
      <TouchableOpacity onPress={this.props.onPress}>
        <Image source={this.props.text} style={{width:40, height:40}}/>
      </TouchableOpacity>
    )
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  Linking,
  Alert,
  TouchableOpacity,
  Text,
  View,
  Image,
  TextInput,
  ListView,
  TouchableHighlight
} from 'react-native';
import styles from '../styles.ios.js';
import AddRecipe from './AddRecipe.ios.js';
import ShareFacebook from './ShareFacebook.ios.js';
import { connect } from "react-redux";

class Recipe extends Component {
  constructor(props) {
    super(props);
    let steps = props.recipe.analyzedInstructions[0] ? props.recipe.analyzedInstructions[0].steps : [];
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      steps: ds.cloneWithRows(steps),
      ingredients: []
    }
  }

  componentWillMount() {
    this.renderIngredients();
    this.renderOptions();
  }

  goBack() {
    this.props.navigator.pop();
  }

  renderIngredients() {
    let ingredients = [];
    for (let ingredient of this.props.recipe.extendedIngredients) {
      ingredients.push(ingredient.originalString);
    }
    this.setState({
      ingredients: ingredients
    })
  }

  renderOptions() {
    const recipe = this.props.recipe;
    recipe.vegan = recipe.vegan ? '∙ Vegan' : false;
    recipe.glutenFree = recipe.glutenFree ? '∙ Gluten Free' : false;
    recipe.dairyFree = recipe.dairyFree ? '∙ Dairy Free' : false;
    if (!recipe.vegan && !recipe.glutenFree && !recipe.dairyFree) {
      recipe.dairyFree = 'No Dietary Restrictions';
    }
    recipe.cheap = recipe.cheap ? '$' : '$$$';
    recipe.sustainable = recipe.sustainable ? '∙ Recipe Sustainable' : false;
    recipe.servings = recipe.servings ? recipe.servings : 'Not available';
    recipe.healthscore = recipe.healthscore ? recipe.healthscore : 'Not available';
    // recipe.sourceUrl
  }

  //DRY click handler for social media deep linking
  shareToSocialMedia(deepLink, appName, storeURL) {
    //deep link into the provided app if installed
    Linking.canOpenURL(appName.toLowerCase() + '://').then(supported => {
      if (!supported) {
        Alert.alert(`You must install the ${appName} app in order to use this feature.`,
                    '',
                    [{text: `Install ${appName}`, onPress: () => Linking.openURL(storeURL)},
                     {text: 'Not Now'}]
        );
      //else direct user to the proper app store link
      } else {
        return Linking.openURL(deepLink);
      }
    }).catch(err => console.error('Error: ', err));
  }

  render() {
    const ingredients = this.state.ingredients.map((ingredient, i) => {
      return (
        <Text style = {styles.ingredientListText2} key={i}>∙ {ingredient} </Text>
      )
    });
    const recipe = this.props.recipe;

    return (
      <View style={styles.recipe}>
        <View style={styles.resultsTitle}>
          <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}>
            <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} />
          </TouchableHighlight>
          <Text style={styles.resultsTitleText}>Instructions for {this.props.food}:</Text>
        </View>
        <View style={styles.ingredientContainer}>
          <View style={styles.ingredientList}>
            <Text> {recipe.vegan} {recipe.glutenFree} {recipe.dairyFree}</Text>
            <Text> {recipe.cheap} {recipe.sustainable} Servings: {recipe.servings} Healthscore: {recipe.healthscore}</Text>
            <Text style={styles.recipeTitle2}>Ingredients:</Text>
            <Text style={styles.ingredientListText2}>{ingredients}</Text>
          </View>
          <View style={styles.recipeImageAndIcons}>
            <Image source={{uri: this.props.image}} style={styles.recipeImage} />
            <View style={styles.iconsContainer}>
              {
                this.props.state.isAuthenticated
                  ? (<ShareFacebook url={this.props.recipe.sourceUrl} />)
                  : (<Text></Text>)
              }
              <TouchableOpacity onPress={
                () => this.shareToSocialMedia('instagram://camera', 'Instagram', 'https://itunes.apple.com/us/app/instagram/id389801252?mt=8')
              }>
                <Image source={require('../public/instagram_icon.png')} style={styles.shareIcons} />
              </TouchableOpacity>
              <TouchableOpacity onPress={
                () => this.shareToSocialMedia(
                  //pre-poplated tweet that includes the recipe name, url for more info, and the app name
                  `twitter://post?message=I%20just%20made%20${this.props.food.split(' ').join('%20')}%20with%20a%20little%20help%20from%20the%20app%20Snacktime!

                  ${this.props.recipe.sourceUrl}`,
                  'Twitter',
                  'https://itunes.apple.com/us/app/twitter/id333903271?mt=8'
                )
              }>
                <Image source={require('../public/twitter_icon.png')} style={styles.shareIcons} />
              </TouchableOpacity>
            </View>
            <AddRecipe info={this.props.recipe} ingredients={this.state.ingredients} userid={this.props.state.id} navigator={this.props.navigator} store={this.props.store}/>
          </View>
        </View>
        <View>
          <Text style={styles.recipeTitle2}>Directions:</Text>
        </View>
        <ListView
          style={styles.recipe}
          dataSource={this.state.steps}
          renderRow={(step, i) => {
            let image = step.ingredients[0] ? step.ingredients[0].image : 'https://s3-us-west-1.amazonaws.com/filmedin/food+(1).png';
            return (
              <View
                key={i}
                style={styles.recipeStep}
                underlayColor="grey"
              >
                <Image source={{uri: image}} style={styles.recipeImage} />
                <Text style={styles.recipeStepText}>step {step.number}: {step.step}</Text>
              </View>
            )
          }}
        />
      </View>
    )
  }
}

export default connect(state => ({
    state: state.facebook
  }), null
)(Recipe);
<commit_msg>(feat-update) Implemented a conditional render to the recipe view to prevent empty list-views from rendering<commit_after>import React, { Component } from 'react';
import {
  Linking,
  Alert,
  TouchableOpacity,
  Text,
  View,
  Image,
  TextInput,
  ListView,
  TouchableHighlight
} from 'react-native';
import styles from '../styles.ios.js';
import AddRecipe from './AddRecipe.ios.js';
import ShareFacebook from './ShareFacebook.ios.js';
import { connect } from "react-redux";

class Recipe extends Component {
  constructor(props) {
    super(props);
    let steps = props.recipe.analyzedInstructions[0] ? props.recipe.analyzedInstructions[0].steps : [];
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      steps: ds.cloneWithRows(steps),
      ingredients: []
    }
  }

  componentWillMount() {
    this.renderIngredients();
    this.renderOptions();
  }

  goBack() {
    this.props.navigator.pop();
  }

  renderIngredients() {
    let ingredients = [];
    for (let ingredient of this.props.recipe.extendedIngredients) {
      ingredients.push(ingredient.originalString);
    }
    this.setState({
      ingredients: ingredients
    })
  }

  renderOptions() {
    const recipe = this.props.recipe;
    recipe.vegan = recipe.vegan ? '∙ Vegan' : false;
    recipe.glutenFree = recipe.glutenFree ? '∙ Gluten Free' : false;
    recipe.dairyFree = recipe.dairyFree ? '∙ Dairy Free' : false;
    if (!recipe.vegan && !recipe.glutenFree && !recipe.dairyFree) {
      recipe.dairyFree = 'No Dietary Restrictions';
    }
    recipe.cheap = recipe.cheap ? '$' : '$$$';
    recipe.sustainable = recipe.sustainable ? '∙ Recipe Sustainable' : false;
    recipe.servings = recipe.servings ? recipe.servings : 'Not available';
    recipe.healthscore = recipe.healthscore ? recipe.healthscore : 'Not available';
    // recipe.sourceUrl
  }

  //DRY click handler for social media deep linking
  shareToSocialMedia(deepLink, appName, storeURL) {
    //deep link into the provided app if installed
    Linking.canOpenURL(appName.toLowerCase() + '://').then(supported => {
      if (!supported) {
        Alert.alert(`You must install the ${appName} app in order to use this feature.`,
                    '',
                    [{text: `Install ${appName}`, onPress: () => Linking.openURL(storeURL)},
                     {text: 'Not Now'}]
        );
      //else direct user to the proper app store link
      } else {
        return Linking.openURL(deepLink);
      }
    }).catch(err => console.error('Error: ', err));
  }

  render() {
    const ingredients = this.state.ingredients.map((ingredient, i) => {
      return (
        <Text style = {styles.ingredientListText2} key={i}>∙ {ingredient} </Text>
      )
    });
    const recipe = this.props.recipe;

    return (
      <View style={styles.recipe}>
        <View style={styles.resultsTitle}>
          <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}>
            <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} />
          </TouchableHighlight>
          <Text style={styles.resultsTitleText}>Instructions for {this.props.food}:</Text>
        </View>
        <View style={styles.ingredientContainer}>
          <View style={styles.ingredientList}>
            <Text> {recipe.vegan} {recipe.glutenFree} {recipe.dairyFree}</Text>
            <Text> {recipe.cheap} {recipe.sustainable} Servings: {recipe.servings} Healthscore: {recipe.healthscore}</Text>
            <Text style={styles.recipeTitle2}>Ingredients:</Text>
            <Text style={styles.ingredientListText2}>{ingredients}</Text>
          </View>
          <View style={styles.recipeImageAndIcons}>
            <Image source={{uri: this.props.image}} style={styles.recipeImage} />
            <View style={styles.iconsContainer}>
              {
                this.props.state.isAuthenticated
                  ? (<ShareFacebook url={this.props.recipe.sourceUrl} />)
                  : (<Text></Text>)
              }
              <TouchableOpacity onPress={
                () => this.shareToSocialMedia('instagram://camera', 'Instagram', 'https://itunes.apple.com/us/app/instagram/id389801252?mt=8')
              }>
                <Image source={require('../public/instagram_icon.png')} style={styles.shareIcons} />
              </TouchableOpacity>
              <TouchableOpacity onPress={
                () => this.shareToSocialMedia(
                  //pre-poplated tweet that includes the recipe name, url for more info, and the app name
                  `twitter://post?message=I%20just%20made%20${this.props.food.split(' ').join('%20')}%20with%20a%20little%20help%20from%20the%20app%20Snacktime!

                  ${this.props.recipe.sourceUrl}`,
                  'Twitter',
                  'https://itunes.apple.com/us/app/twitter/id333903271?mt=8'
                )
              }>
                <Image source={require('../public/twitter_icon.png')} style={styles.shareIcons} />
              </TouchableOpacity>
            </View>
            <AddRecipe info={this.props.recipe} ingredients={this.state.ingredients} userid={this.props.state.id} navigator={this.props.navigator} store={this.props.store}/>
          </View>
        </View>
        <View>
          <Text style={styles.recipeTitle2}>Directions:</Text>
        </View>
        <ListView
          style={styles.recipe}
          dataSource={this.state.steps}
          renderRow={(step, i) => {
            let image = step.ingredients[0] ? step.ingredients[0].image : 'https://s3-us-west-1.amazonaws.com/filmedin/food+(1).png';
            let stepCounter = 1;
            {/* Conditional render to accomodate the spoonacular api returning empty step results */}
            return step.step.length > 1
              ?
                (
                  <View
                    key={i}
                    style={styles.recipeStep}
                    underlayColor="grey"
                  >
                    {console.log('***************************************')}
                    {console.log('step: ' + step.step)}
                    {console.log('***************************************')}
                    <Image source={{uri: image}} style={styles.recipeImage} />
                    <Text style={styles.recipeStepText}>Step: {step.step}</Text>
                  </View>
                )
              :
                (
                  <Text></Text>
                )
          }}
        />
      </View>
    )
  }
}

export default connect(state => ({
    state: state.facebook
  }), null
)(Recipe);
<|endoftext|>


<commit_before>export function getBot() {
    // Todo: create logic for get bot
}

export function getStudent(id) {
    // Todo: create logic for get bot
}
<commit_msg>Fixted lint<commit_after>export function getBot() {
  // Todo: create logic for get bot
}

export function getStudent(id) {
  const students = id;
  // Todo: create logic for get student
  return students;
}

export function createBot(key, password) {
  const response = { key, password };
  // Todo: create logic for add bot
  return response;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'

import { fetchLocations } from '../../core/firebaseRestAPI'
import { calculateAllDistances } from '../../core/distance'

import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import FilterBar from '../../components/FilterBar'
import LocationList from '../../components/LocationList'
import { filterByOptionsString } from '../../lib/filterLocations'
import R from 'ramda'

function getParameterByName(name) {
  const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search)
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '))
}

function mergeLocationsAndDistances(locations, matrixResponses) {
  const zip = (e, index) => {
    return [locations[index], matrixResponses[index]]
  }

  const merge = ([location, responseObj]) => {
    const locationAndDistance = location
    const durationInfo = responseObj || {}
    locationAndDistance.duration = durationInfo.duration // i hate this; it breaks the consistency of the whole app
    return locationAndDistance
  }

  return locations.map((e, i) => merge(zip(e, i)))
}

export default class LocationsPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      locations: null,
      locationsWithDistance: [],
      currentLocation: null,
    }
  }

  componentDidMount() {
    document.title = 'Link-SF'

    fetchLocations(20)
      .then(locations => {
        this.setState({ locations }, this.loadRemaining)
      })
  }

  setCurrentLocation = () => {
    if (navigator) {
      navigator.geolocation.getCurrentPosition(currentLocation => {
        this.setState({ currentLocation }, this.addDistances)
      })
    }
  }

  addDistances = () => {
    const { currentLocation, locations, locationsWithDistance } = this.state
    const locationSlices = R.splitEvery(25, locations)

    if (!currentLocation) return

    this.calculateDistances(locationSlices, currentLocation)
  }

  calculateDistances = (locationSlices, currentLocation) => {
    const { locationsWithDistance } = this.state
    const a = R.splitAt(1, locationSlices)
    const locations = a[0][0] // this will always only have one element, the array of our working locations
    const remaining = a[1]

    if (locations) {
      // we can only call the distance matrix API with 25 elements at a time,
      // and 100 elements per second, so lets call with 25 elements every 250ms
      setTimeout(_ => {
        calculateAllDistances(locations, currentLocation)
          .then(matrixResponse => {
            const matrixResponses = matrixResponse.rows[0].elements
            const updatedLocations = mergeLocationsAndDistances(locations, matrixResponses)

            this.setState({ locationsWithDistance: [...locationsWithDistance, ...updatedLocations] }, _ => {
              this.calculateDistances(remaining, currentLocation)
            })
          })
      }, 250)
    } else {
      // we should have to do this, but mergeLocationsAndDistances modifies the
      // the location, so as a side effect the state gets updated anyway
      // this.setState({ locations: locationsWithDistance }) // if the above comment is implemented,
    }
  }

  loadRemaining = () => {
    const { locations } = this.state
    const lastItemId = locations[locations.length - 1].id

    fetchLocations(0, lastItemId)
      .then(newLocations => {
        this.setState({ locations: [...locations, ...newLocations] }, this.setCurrentLocation)
      })
  }

  render() {
    const { locations } = this.state
    const loading = locations == null
    const category = getParameterByName('categories')
    const showOpen = window.location.search.includes('hours=open')
    const sortDist = window.location.search.includes('sort=dist')
    const locationsList = Object.values(locations || {})
    const queryString = window.location.search
    const filteredLocations = filterByOptionsString(queryString.slice(1, queryString.length), locationsList)

    filteredLocations.sort(function(a,b) {
      if (a.duration && b.duration) {
        return a.duration.value - b.duration.value
      } else {
        return 0
      }
    });

    return (
      <Layout>
        { loading ?
          <Loading /> :

            <FilterBar
              showOpen={showOpen}
              sortDist={sortDist}
              queryString={queryString}
            />
            <LocationList locations={filteredLocations} />

        }
        </Layout>
    )
  }
}
<commit_msg>only sort if option is selected<commit_after>import React, { Component } from 'react'

import { fetchLocations } from '../../core/firebaseRestAPI'
import { calculateAllDistances } from '../../core/distance'

import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import FilterBar from '../../components/FilterBar'
import LocationList from '../../components/LocationList'
import { filterByOptionsString } from '../../lib/filterLocations'
import R from 'ramda'

function getParameterByName(name) {
  const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search)
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '))
}

function mergeLocationsAndDistances(locations, matrixResponses) {
  const zip = (e, index) => {
    return [locations[index], matrixResponses[index]]
  }

  const merge = ([location, responseObj]) => {
    const locationAndDistance = location
    const durationInfo = responseObj || {}
    locationAndDistance.duration = durationInfo.duration // i hate this; it breaks the consistency of the whole app
    return locationAndDistance
  }

  return locations.map((e, i) => merge(zip(e, i)))
}

export default class LocationsPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      locations: null,
      locationsWithDistance: [],
      currentLocation: null,
    }
  }

  componentDidMount() {
    document.title = 'Link-SF'

    fetchLocations(20)
      .then(locations => {
        this.setState({ locations }, this.loadRemaining)
      })
  }

  setCurrentLocation = () => {
    if (navigator) {
      navigator.geolocation.getCurrentPosition(currentLocation => {
        this.setState({ currentLocation }, this.addDistances)
      })
    }
  }

  addDistances = () => {
    const { currentLocation, locations, locationsWithDistance } = this.state
    const locationSlices = R.splitEvery(25, locations)

    if (!currentLocation) return

    this.calculateDistances(locationSlices, currentLocation)
  }

  calculateDistances = (locationSlices, currentLocation) => {
    const { locationsWithDistance } = this.state
    const a = R.splitAt(1, locationSlices)
    const locations = a[0][0] // this will always only have one element, the array of our working locations
    const remaining = a[1]

    if (locations) {
      // we can only call the distance matrix API with 25 elements at a time,
      // and 100 elements per second, so lets call with 25 elements every 250ms
      setTimeout(_ => {
        calculateAllDistances(locations, currentLocation)
          .then(matrixResponse => {
            const matrixResponses = matrixResponse.rows[0].elements
            const updatedLocations = mergeLocationsAndDistances(locations, matrixResponses)

            this.setState({ locationsWithDistance: [...locationsWithDistance, ...updatedLocations] }, _ => {
              this.calculateDistances(remaining, currentLocation)
            })
          })
      }, 250)
    } else {
      // we should have to do this, but mergeLocationsAndDistances modifies the
      // the location, so as a side effect the state gets updated anyway
      // this.setState({ locations: locationsWithDistance }) // if the above comment is implemented,
    }
  }

  loadRemaining = () => {
    const { locations } = this.state
    const lastItemId = locations[locations.length - 1].id

    fetchLocations(0, lastItemId)
      .then(newLocations => {
        this.setState({ locations: [...locations, ...newLocations] }, this.setCurrentLocation)
      })
  }

  render() {
    const { locations } = this.state
    const loading = locations == null
    const showOpen = window.location.search.includes('hours=open')
    const sortDist = window.location.search.includes('sort=dist')
    const locationsList = Object.values(locations || {})
    const queryString = window.location.search
    const filteredLocations = filterByOptionsString(queryString.slice(1, queryString.length), locationsList)

    if (sortDist) {
      filteredLocations.sort((a, b) => {
        if (a.duration && b.duration) {
          return a.duration.value - b.duration.value
        } else {
          return 0
        }
      })
    }

    return (
      <Layout>
        { loading ?
          <Loading /> :

            <FilterBar
              showOpen={showOpen}
              sortDist={sortDist}
              queryString={queryString}
            />
            <LocationList locations={filteredLocations} />

        }
        </Layout>
    )
  }
}
<|endoftext|>