<commit_before>(function webmakerKits( window, document ) {
  'use strict';

  // ensure we have the makeapi-client for anything magic we want to do
  if ( !window.Make ) {
    var script = document.createElement( 'script' );
    script.src = '//webmaker.org/bower_components/makeapi-client/src/make-api.js';
    script.onload = function() {
      webmakerKits( window, document );
    };
    document.head.appendChild( script );

    return;
  }

  /*
   * convert simple list into checklist when it has the `.checklist` class
   */
  var checklist = document.querySelectorAll( '.checklist li' );
  for ( var i = 0, j = checklist.length; i < j; i++ ) {
    checklist[i].innerHTML = '<input id="r' + i + '" type="checkbox"> ' + checklist[i].innerHTML;
  }

  /*
   * add tags to the kit based on what tags for it are in the makeapi
   */
  // this should only really be used once, so lets
  var tagsSection = document.querySelector( '#magicTags' );
  if ( tagsSection ) {
    var makeapi = new window.Make({
      apiURL: 'https://makeapi.webmaker.org'
    });

    // when on published location w/ makeapi data garunteed.
    if ( window.location.toString().match( /^https?:\/\/([A-Za-z0-9_\-]+)\.makes\.org\/thimble\/(([A-Za-z0-9]+)==\/)?([A-Za-z0-9_\-]+)_?$/ ) ) {
      var url = window.location.href;
      if( url.slice(-1) === '_' ) {
        url = url.slice( 0, -1 );
      }

      makeapi.url( url ).then( function( err, makes ) {
        if( err ) {
          console.log( err );
          return;
        }

        if( makes.length !== 1 ) {
          console.log( 'make not found' );
          return;
        }

        var make = makes[0];
        var tagList = '
\n';

        make.tags.forEach( function( tag ){
          tagList += '
#' + tag + '
\n';
        });

        tagList += '
\n';

        tagsSection.innerHTML += tagList;
        tagsSection.querySelector( '#magicNotice' ).parentNode.removeChild( tagsSection.querySelector( '#magicNotice' ) );
      });
    }

    // not published OR in editor
    else if( !window.location.toString().match( /^https?:\/\/mozillathimblelivepreview\.net\// ) ) {
      tagsSection.parentNode.removeChild( tagsSection );
    }
  }

})( this, this.document );
<commit_msg>correcting typo<commit_after>(function webmakerKits( window, document ) {
  'use strict';

  // ensure we have the makeapi-client for anything magic we want to do
  if ( !window.Make ) {
    var script = document.createElement( 'script' );
    script.src = '//webmaker.org/bower_components/makeapi-client/src/make-api.js';
    script.onload = function() {
      webmakerKits( window, document );
    };
    document.head.appendChild( script );

    return;
  }

  /*
   * convert simple list into checklist when it has the `.checklist` class
   */
  var checklist = document.querySelectorAll( '.checklist li' );
  for ( var i = 0, j = checklist.length; i < j; i++ ) {
    checklist[i].innerHTML = '<input id="r' + i + '" type="checkbox"> ' + checklist[i].innerHTML;
  }

  /*
   * add tags to the kit based on what tags for it are in the makeapi
   */
  // this should only really be used once, so lets
  var tagsSection = document.querySelector( '#magicTags' );
  if ( tagsSection ) {
    var makeapi = new window.Make({
      apiURL: 'https://makeapi.webmaker.org'
    });

    // when on published location w/ makeapi data guaranteed.
    if ( window.location.toString().match( /^https?:\/\/([A-Za-z0-9_\-]+)\.makes\.org\/thimble\/(([A-Za-z0-9]+)==\/)?([A-Za-z0-9_\-]+)_?$/ ) ) {
      var url = window.location.href;
      if( url.slice(-1) === '_' ) {
        url = url.slice( 0, -1 );
      }

      makeapi.url( url ).then( function( err, makes ) {
        if( err ) {
          console.log( err );
          return;
        }

        if( makes.length !== 1 ) {
          console.log( 'make not found' );
          return;
        }

        var make = makes[0];
        var tagList = '
\n';

        make.tags.forEach( function( tag ){
          tagList += '
#' + tag + '
\n';
        });

        tagList += '
\n';

        tagsSection.innerHTML += tagList;
        tagsSection.querySelector( '#magicNotice' ).parentNode.removeChild( tagsSection.querySelector( '#magicNotice' ) );
      });
    }

    // not published OR in editor
    else if( !window.location.toString().match( /^https?:\/\/mozillathimblelivepreview\.net\// ) ) {
      tagsSection.parentNode.removeChild( tagsSection );
    }
  }

})( this, this.document );
<|endoftext|>


<commit_before>const BASE_URL = 'https://api.datausa.io/api/?show=geo&sumlevel=state&required=pop,age,income'
var states; // Global object that holds state information
let stats = ["population", "median_age", "median_income"];

// Loads state object
$(document).ready(function($) {

  // getWikipedia(5407);
  location.hash = 'landing';

  $.ajax({
    url: 'https://raw.githubusercontent.com/takatanium/UCB-Project1/master/assets/json/states.json',
    dataType: 'json',
    method: 'GET',
    success: function(res) {
      states = res;

      for (let i = 0; i < states.length; i++) {
        states[i]['population'] = {}
        states[i]['median_age'] = {}
        states[i]['median_income'] = {}
      }
      getData();
    },
    error: function(e) {
      console.log(e);
    }
  })
});

/**
 * [getData description]
 * @return {[type]} [description]
 */
function getData() {
  $.ajax({
    url: BASE_URL,
    dataType: 'json',
    method: 'GET',
    success: function(res) {

      for (let i = 0; i < res.data.length; i++) {
        let id = res.data[i][1];

        for (let j = 0; j < states.length; j++) {

          if (id == states[j].id) {

            let year = res.data[i][0];

            // @mmenschig - would love for this to be dynamic
            if (!states[j]['population'].hasOwnProperty(year)) {
              states[j]['population'][year] = res.data[i][2];
            }

            if (!states[j]['median_age'].hasOwnProperty(year)) {
              states[j]['median_age'][year] = res.data[i][3];
            }

            if (!states[j]['median_income'].hasOwnProperty(year)) {
              states[j]['median_income'][year] = res.data[i][4];
            }
          }
        }
      }

      createAllDivs();
      $.scrollify.move('#landing');
      $('#landing-page').fadeTo(2000, 1);
      initiateInput('landing');
      popDataInfo();
    },
    error: function(e) {
      console.log(e);
    }
  })
}

/**
 * Returns a Wikipedia API response object
 * @param  {string} state The state we are retrieving data for
 * @return {object}       Wikipedia API response
 */
function getWikipedia(pageid, state) {
  let BASEURL = 'https://en.wikipedia.org/w/api.php'
  let url = BASEURL + '?' + $.param({
    action: 'query',
    prop: 'extracts',
    exintro: null,
    explaintext: null,
    exsentences: 5,
    pageids: pageid,
    format: 'json'
  });

  console.log(url);

  $.ajax({
    url: url,
    dataType: 'jsonp',
    crossDomain: true,
    method: 'GET',
    success: function(res) {

      let extract = getExtract(res);
      console.log(extract);
      $('#'+state+'-card-content').html(extract);
      return extract;
    },
    error: function(e) {
      console.log(e);
    }
  })
}

function getExtract(data) {
  let pages = data.query.pages;

  for (var key in pages) {
    if (pages.hasOwnProperty(key)) {
      return pages[key]["extract"];
    }
  }

}
<commit_msg>added functionality to include additional metrics<commit_after>const BASE_URL = 'https://api.datausa.io/api/?show=geo&sumlevel=state&required=pop,age,income'
const CHR_URL = 'https://api.datausa.io/api/?show=geo&sumlevel=state&required=unemployment,uninsured,high_school_graduation,some_college'
var states; // Global object that holds state information
let stats = ["population", "median_age", "median_income"];

/*
******************************************************
STATISTICS DESCRIPTION
******************************************************

American Community Survey (ACS)
  pop                    - Population
  age                    - Median Age
  income                 - Median household income

County Health Rankings (CHR)
  unemployment           - Percentage of the civilian labor force, age 16 and older, that is unemployed but seeking work
  uninsured              - Percentage of the population under age 65 thath has no health insurance coverage
  high_school_graduation - Percentage of nith-grade cohort in public schools that graduates from high school in four years
  some_college           - Percentage of the population ages 25-44 with some post-secondary education, such as enrollment
                           in vocational/technical school, junior colleges, or four-year colleges, including individuals
                           who pursued education following high school but did not receive a degree
 */

// Loads state object
$(document).ready(function($) {

  location.hash = 'landing';

  $.ajax({
    url: 'https://raw.githubusercontent.com/takatanium/UCB-Project1/master/assets/json/states.json',
    dataType: 'json',
    method: 'GET',
    success: function(res) {
      states = res;

      // Optimize this routine
      for (let i = 0; i < states.length; i++) {
        states[i]['population'] = {};
        states[i]['median_age'] = {};
        states[i]['median_income'] = {};
        states[i]['unemployment'] = {};
        states[i]['uninsured'] = {};
        states[i]['high_school_graduation'] = {};
        states[i]['some_college'] = {};
      }
      getACSData();
      getCHRData();
    },
    error: function(e) {
      console.log(e);
    }
  })
});

/**
 * [getCHRData description]
 * @return {[type]} [description]
 */
function getCHRData() {
  $.ajax({
    url: CHR_URL,
    dataType: 'json',
    method: 'GET',
    success: function(res) {

      for (let i = 0; i < res.data.length; i++) {
        let id = res.data[i][1];

        for (let j = 0; j < states.length; j++) {
          if (id == states[j].id) {

            let year = res.data[i][0];
            // @mmenschig - optimize this routine
            if (!states[j]['unemployment'].hasOwnProperty(year)) {
              states[j]['unemployment'][year] = res.data[i][2];
            }

            if (!states[j]['uninsured'].hasOwnProperty(year)) {
              states[j]['uninsured'][year] = res.data[i][3];
            }

            if (!states[j]['high_school_graduation'].hasOwnProperty(year)) {
              states[j]['high_school_graduation'][year] = res.data[i][4];
            }

            if (!states[j]['some_college'].hasOwnProperty(year)) {
              states[j]['some_college'][year] = res.data[i][5];
            }

          }
        }
      }

    },
    error: function(e) {
      console.log(e);
    }
  })
}

/**
 * [getData description]
 * @return {[type]} [description]
 */
function getACSData() {
  $.ajax({
    url: BASE_URL,
    dataType: 'json',
    method: 'GET',
    success: function(res) {

      for (let i = 0; i < res.data.length; i++) {
        let id = res.data[i][1];

        for (let j = 0; j < states.length; j++) {
          if (id == states[j].id) {

            let year = res.data[i][0];

            // @mmenschig - would love for this to be dynamic
            if (!states[j]['population'].hasOwnProperty(year)) {
              states[j]['population'][year] = res.data[i][2];
            }

            if (!states[j]['median_age'].hasOwnProperty(year)) {
              states[j]['median_age'][year] = res.data[i][3];
            }

            if (!states[j]['median_income'].hasOwnProperty(year)) {
              states[j]['median_income'][year] = res.data[i][4];
            }
          }
        }
      }

      createAllDivs();
      $.scrollify.move('#landing');
      $('#landing-page').fadeTo(2000, 1);
      initiateInput('landing');
      popDataInfo();
    },
    error: function(e) {
      console.log(e);
    }
  })
}

/**
 * Returns a Wikipedia API response object
 * @param  {string} state The state we are retrieving data for
 * @return {object}       Wikipedia API response
 */
function getWikipedia(pageid, state) {
  let BASEURL = 'https://en.wikipedia.org/w/api.php'
  let url = BASEURL + '?' + $.param({
    action: 'query',
    prop: 'extracts',
    exintro: null,
    explaintext: null,
    exsentences: 5,
    pageids: pageid,
    format: 'json'
  });

  console.log(url);

  $.ajax({
    url: url,
    dataType: 'jsonp',
    crossDomain: true,
    method: 'GET',
    success: function(res) {

      let extract = getExtract(res);
      console.log(extract);
      $('#'+state+'-card-content').html(extract);
      return extract;
    },
    error: function(e) {
      console.log(e);
    }
  })
}

function getExtract(data) {
  let pages = data.query.pages;

  for (var key in pages) {
    if (pages.hasOwnProperty(key)) {
      return pages[key]["extract"];
    }
  }
}
<|endoftext|>


<commit_before>//global vars
//

var numPosts = 0;
var craigslistItems = new Array();
var ebayHighPrice = 0;
var ebayAvgPrice = 0;
var ebayLowPrice = 0;

var priceList = new Array();
var clComplete = false;
var ebayComplete = false;

function search(_query){
    //replace commas
    _query = _query.replace(/,/g,"&");
    //replace apostrophes
    _query = _query.replace(/'/g,"&");
    //replace white space with & for search awesomeness
    _query = _query.replace(/ /g,"&");

    findCraigslistProducts(_query);
    findEbayItem(_query);

}

//generates a post to append to the list
//then appends it to the list
// variables:
//  _link: standard href stuff, the entire post will link here so choose carefully
//  _price: the price to purchase the item
//  _title: title of the post
function generatePost(_link, _price, _title){

    //console.log('generate post called');

    //collapse code
	$("#list").append('

' + '$' + _price + ' - ' + _title +'

');

    var body = 'Link to Craigslist post';
    body += '
High: $' + ebayHighPrice + '
';
    body += '
Average: $' + ebayAvgPrice + '
';
    body += '
Low: $' + ebayLowPrice + '
';
    body += '
Gas expenses: $x
';
    body += '
Profit: $' + _price + '
';

    	$("#sparkline").sparkline( [ebayLowPrice,((ebayAvgPrice-ebayLowPrice)/2),ebayAvgPrice,((ebayHighPrice-ebayAvgPrice)/2),ebayHighPrice], {
	    type: 'box',
	    raw: false,
	    target: ebayAvgPrice,
	    minValue: ebayLowPrice,
	    maxValue: ebayHighPrice});

    body += '
<canvas width="62" height="18" style="display: inline-block; width: 62px; height: 18px; vertical-align: top;"></canvas>
';

    //item body
    $("#list").append('

' + body + '
<button class="btn" data-toggle="collapse" data-parent="#accordion" href="#collapse' + numPosts + '">Close</button>

');

    //$("#list").append('');

    numPosts++;
}

//////
//
//   START CRAIGSLIST STUFF
//
//////
function findCraigslistProducts(search){
    $.ajax({
        type: "GET",
        url: "assets/php/proxy.php?search=" + search,
        dataType: "xml",
        success: parseXml
     });
}

function parseXml(xml) {
    //console.log(xml);
    $(xml).find("item").each(function() {
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        //parse title down so it's not super long
        var prettyTitle = title.substr(0, title.indexOf("$"));
        //parse price out of title
        var price = title.substr(title.indexOf("$"), title.indexOf(" ") + 1);

        var priceInt = parseInt(price.substr(1));

        var items = new Array();
        //this will get rid of TRADE items
        if ( priceInt >= 0 ) {
            generatePost(link, priceInt, prettyTitle);
            items.push( new Object(link, priceInt, prettyTitle));

        }
        ////console.log(items);
        craigslistItems = items;
        clComplete = true;

    });
}

//////
//
//   END CRAIGSLIST STUFF
//
//////

//////
//
//   START EBAY STUFF
//
//////
function findEbayItem(search){

           $.ajax({
		type: "GET",
		url: "assets/php/proxyEbay.php?search=" + search,
		dataType: "xml",
		success: parseEbayXml
	     });

        }

	function parseEbayXml(xml) {
	//console.log(xml);

	var items = Array();

	var numItems = 0;
	var price = 0;
	var maxPrice = -1;
	var minPrice = 99999999;

	$(xml).find("item").each(function() {

	    var condition =  $(this).find("conditionDisplayName").text();
	    ////console.log(condition);
	    if((condition == 'New') || (condition == 'New other (see details)') || (condition == 'Manufacturer refurbished') || (condition == 'Used')){

		var currentPrice = $(this).find("currentPrice").text();
		currentPrice = parseFloat(currentPrice);
		priceList.push(currentPrice);

		if(currentPrice > maxPrice){
		    maxPrice = currentPrice;
		}
		if(currentPrice < minPrice){
		    minPrice = currentPrice;
		}
		price += currentPrice;
		numItems++;
	    }
	});
	var avgPrice = parseFloat(price / numItems);
	var sAvgPrice = 0;
	for( var i = 0; i < 30; i++){
	    sAvgPrice += priceList[i] / 30;
	}

	//calculate stDev
	var stddev = 0;
	var sum = 0;
	for( var i = 0; i < 30; i++){
	    var difference = priceList[i] - sAvgPrice;
	    sum += difference * difference/30;
	}

	stdev = Math.pow(sum, 1/2);
	////console.log('test of difference: ' + (priceList[1] - avgPrice));
	//console.log('sum: '+ sum);
	//console.log('avg price: ' + avgPrice);
	//console.log( 'price list before culling: ' + priceList.length );
	//console.log('stdev: ' + stdev);
	//console.log('price: ' + price);
	//console.log('num: ' + numItems);

	var higherThanAvg = 0;
	var lowerThanAvg = 0;

	for(var i = 0; i < priceList.length; i++){
	    if (priceList[i] > avgPrice) {
		higherThanAvg++;
	    }
	    if (priceList[i] < avgPrice) {
		lowerThanAvg++;
	    }
	}
	//go through price list, drop lower tail of stdev
	//anything that's less than the avg-(stdev*2)
	var standardizedSum = 0;

	var lowerTail = avgPrice - (lowerThanAvg/(lowerThanAvg + higherThanAvg) * stdev);
	//console.log('lower tail: ' + lowerTail);

	for( var i = 0; i < priceList.length; i++){
	    if (priceList[i] < lowerTail) {
		//find index of item
		var index = priceList.indexOf(priceList[i]);
		//remove the item
		priceList.splice(index, 1);
	    }
	    else{
		//the number is within boundaries, keep it
		standardizedSum += priceList[i];
	    }
	}
	//console.log( 'price list after culling: ' + priceList.length );
	////console.log( 'higher than average: ' + higherThanAvg);
	////console.log( 'lower than average: ' + lowerThanAvg);

        ebayHighPrice = Math.max.apply(Math, priceList);
        ebayAvgPrice = standardizedSum / priceList.length;
        ebayLowPrice = Math.min.apply(Math, priceList);

	ebayHighPrice = Math.round(ebayHighPrice * 100) / 100;
	ebayAvgPrice = Math.round(ebayAvgPrice * 100) / 100;
	ebayLowPrice = Math.round(ebayLowPrice * 100) / 100;
	//console.log( ebayHighPrice );
	//console.log( ebayLowPrice );

        $('.highPrice').each(function(){
            $(this).empty();
            $(this).append(ebayHighPrice);
        });

        $('.avgPrice').each(function(){
            $(this).empty();
            $(this).append(ebayAvgPrice);
        });

        $('.lowPrice').each(function(){
            $(this).empty();
            $(this).append(ebayLowPrice);
        });

        $('.profit').each(function(){
            var cost = parseInt($(this).text());
	    $(this).empty();
            $(this).append(ebayAvgPrice - cost);
        });

        ebayComplete = true;

	////console.log('Highest price: ' + maxPrice);
	////console.log('Average price: ' + avgPrice);
	////console.log('Lowest price: ' + minPrice);

	////console.log(numItems);

	//$('#content').append('
Highest price: '+ maxPrice + '
');
	//$('#content').append('
Average price: '+ avgPrice + '
');
	//$('#content').append('
Lowest price: '+ minPrice + '
');
}
//////
//
//   END EBAY STUFF
//
//////

<commit_msg>I can't do javascripting<commit_after>//global vars
//

var numPosts = 0;
var craigslistItems = new Array();
var ebayHighPrice = 0;
var ebayAvgPrice = 0;
var ebayLowPrice = 0;

var priceList = new Array();
var clComplete = false;
var ebayComplete = false;

function search(_query){
    //replace commas
    _query = _query.replace(/,/g,"&");
    //replace apostrophes
    _query = _query.replace(/'/g,"&");
    //replace white space with & for search awesomeness
    _query = _query.replace(/ /g,"&");

    findCraigslistProducts(_query);
    findEbayItem(_query);

}

//generates a post to append to the list
//then appends it to the list
// variables:
//  _link: standard href stuff, the entire post will link here so choose carefully
//  _price: the price to purchase the item
//  _title: title of the post
function generatePost(_link, _price, _title){

    //console.log('generate post called');

    //collapse code
	$("#list").append('

' + '$' + _price + ' - ' + _title +'

');

    var body = 'Link to Craigslist post';
    body += '
High: $' + ebayHighPrice + '
';
    body += '
Average: $' + ebayAvgPrice + '
';
    body += '
Low: $' + ebayLowPrice + '
';
    body += '
Gas expenses: $x
';
    body += '
Profit: $' + _price + '
';

    body += '
<canvas width="62" height="18" style="display: inline-block; width: 62px; height: 18px; vertical-align: top;"></canvas>
';

    //item body
    $("#list").append('

' + body + '
<button class="btn" data-toggle="collapse" data-parent="#accordion" href="#collapse' + numPosts + '">Close</button>

');

    //$("#list").append('');

    numPosts++;
}

//////
//
//   START CRAIGSLIST STUFF
//
//////
function findCraigslistProducts(search){
    $.ajax({
        type: "GET",
        url: "assets/php/proxy.php?search=" + search,
        dataType: "xml",
        success: parseXml
     });
}

function parseXml(xml) {
    //console.log(xml);
    $(xml).find("item").each(function() {
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        //parse title down so it's not super long
        var prettyTitle = title.substr(0, title.indexOf("$"));
        //parse price out of title
        var price = title.substr(title.indexOf("$"), title.indexOf(" ") + 1);

        var priceInt = parseInt(price.substr(1));

        var items = new Array();
        //this will get rid of TRADE items
        if ( priceInt >= 0 ) {
            generatePost(link, priceInt, prettyTitle);
            items.push( new Object(link, priceInt, prettyTitle));

        }
        ////console.log(items);
        craigslistItems = items;
        clComplete = true;

    });
}

//////
//
//   END CRAIGSLIST STUFF
//
//////

//////
//
//   START EBAY STUFF
//
//////
function findEbayItem(search){

           $.ajax({
		type: "GET",
		url: "assets/php/proxyEbay.php?search=" + search,
		dataType: "xml",
		success: parseEbayXml
	     });

        }

	function parseEbayXml(xml) {
	//console.log(xml);

	var items = Array();

	var numItems = 0;
	var price = 0;
	var maxPrice = -1;
	var minPrice = 99999999;

	$(xml).find("item").each(function() {

	    var condition =  $(this).find("conditionDisplayName").text();
	    ////console.log(condition);
	    if((condition == 'New') || (condition == 'New other (see details)') || (condition == 'Manufacturer refurbished') || (condition == 'Used')){

		var currentPrice = $(this).find("currentPrice").text();
		currentPrice = parseFloat(currentPrice);
		priceList.push(currentPrice);

		if(currentPrice > maxPrice){
		    maxPrice = currentPrice;
		}
		if(currentPrice < minPrice){
		    minPrice = currentPrice;
		}
		price += currentPrice;
		numItems++;
	    }
	});
	var avgPrice = parseFloat(price / numItems);
	var sAvgPrice = 0;
	for( var i = 0; i < 30; i++){
	    sAvgPrice += priceList[i] / 30;
	}

	//calculate stDev
	var stddev = 0;
	var sum = 0;
	for( var i = 0; i < 30; i++){
	    var difference = priceList[i] - sAvgPrice;
	    sum += difference * difference/30;
	}

	stdev = Math.pow(sum, 1/2);
	////console.log('test of difference: ' + (priceList[1] - avgPrice));
	//console.log('sum: '+ sum);
	//console.log('avg price: ' + avgPrice);
	//console.log( 'price list before culling: ' + priceList.length );
	//console.log('stdev: ' + stdev);
	//console.log('price: ' + price);
	//console.log('num: ' + numItems);

	var higherThanAvg = 0;
	var lowerThanAvg = 0;

	for(var i = 0; i < priceList.length; i++){
	    if (priceList[i] > avgPrice) {
		higherThanAvg++;
	    }
	    if (priceList[i] < avgPrice) {
		lowerThanAvg++;
	    }
	}
	//go through price list, drop lower tail of stdev
	//anything that's less than the avg-(stdev*2)
	var standardizedSum = 0;

	var lowerTail = avgPrice - (lowerThanAvg/(lowerThanAvg + higherThanAvg) * stdev);
	//console.log('lower tail: ' + lowerTail);

	for( var i = 0; i < priceList.length; i++){
	    if (priceList[i] < lowerTail) {
		//find index of item
		var index = priceList.indexOf(priceList[i]);
		//remove the item
		priceList.splice(index, 1);
	    }
	    else{
		//the number is within boundaries, keep it
		standardizedSum += priceList[i];
	    }
	}
	//console.log( 'price list after culling: ' + priceList.length );
	////console.log( 'higher than average: ' + higherThanAvg);
	////console.log( 'lower than average: ' + lowerThanAvg);

        ebayHighPrice = Math.max.apply(Math, priceList);
        ebayAvgPrice = standardizedSum / priceList.length;
        ebayLowPrice = Math.min.apply(Math, priceList);

	ebayHighPrice = Math.round(ebayHighPrice * 100) / 100;
	ebayAvgPrice = Math.round(ebayAvgPrice * 100) / 100;
	ebayLowPrice = Math.round(ebayLowPrice * 100) / 100;
	//console.log( ebayHighPrice );
	//console.log( ebayLowPrice );

        $('.highPrice').each(function(){
            $(this).empty();
            $(this).append(ebayHighPrice);
        });

        $('.avgPrice').each(function(){
            $(this).empty();
            $(this).append(ebayAvgPrice);
        });

        $('.lowPrice').each(function(){
            $(this).empty();
            $(this).append(ebayLowPrice);
        });

        $('.profit').each(function(){
            var cost = parseInt($(this).text());
	    $(this).empty();
            $(this).append(ebayAvgPrice - cost);
        });

        ebayComplete = true;

	    	$(".chart").sparkline( priceList, {
	    type: 'box',
	    raw: false,
	    target: ebayAvgPrice,
	    minValue: ebayLowPrice,
	    maxValue: ebayHighPrice});

	////console.log('Highest price: ' + maxPrice);
	////console.log('Average price: ' + avgPrice);
	////console.log('Lowest price: ' + minPrice);

	////console.log(numItems);

	//$('#content').append('
Highest price: '+ maxPrice + '
');
	//$('#content').append('
Average price: '+ avgPrice + '
');
	//$('#content').append('
Lowest price: '+ minPrice + '
');
}
//////
//
//   END EBAY STUFF
//
//////

<|endoftext|>


<commit_before>
//
// Main entry point.
//

require.config( {
    paths: {
        'jquery'                : "jquery-1.7.1.min",
        'jquery-ui'             : "jquery-ui-1.8.16.custom.min",
        'jquery-temporaryClass' : "jquery.temporaryClass",
        'mustache'              : "require-mustache"
    },
    shim: {
        'jquery' : {
            exports: "jQuery",
        },
        'jquery-ui' : {
            exports: "jQuery.ui",
            deps: ["jquery"],
        },
        'jquery-temporaryClass' : {
            exports: "jQuery.fn.temporaryClass",
            deps: ["jquery"]
        }
    }
} );

// Require Argumenta
require( ["argumenta"], function( undefined ) {

    // Argumenta is loaded & the app is running...

} );
<commit_msg>Remove extraneous commas for IE<commit_after>
//
// Main entry point.
//

require.config( {
    paths: {
        'jquery'                : "jquery-1.7.1.min",
        'jquery-ui'             : "jquery-ui-1.8.16.custom.min",
        'jquery-temporaryClass' : "jquery.temporaryClass",
        'mustache'              : "require-mustache"
    },
    shim: {
        'jquery' : {
            exports: "jQuery"
        },
        'jquery-ui' : {
            exports: "jQuery.ui",
            deps: ["jquery"]
        },
        'jquery-temporaryClass' : {
            exports: "jQuery.fn.temporaryClass",
            deps: ["jquery"]
        }
    }
} );

// Require Argumenta
require( ["argumenta"], function( undefined ) {

    // Argumenta is loaded & the app is running...

} );
<|endoftext|>


<commit_before>var map,
  // typeFilter - optional string type on which to limit data being transformed and returned
  // returns a valid geojson given data input from RUCS (not currently aligned to any standard)
  rucsToGeojson = function(data, typeFilter) {
    // Transform RUCS data into valid geojson
    var placeCount = 0,
      numPlaces = data.length,
      geoJsonData = {
        type: 'FeatureCollection',
        features: []
      };
    for (var i = 0; i < numPlaces; i++) {
      var place = data[i];
      if (place.Type === typeFilter
          && typeof place.Latitude === 'number'
          && typeof place.Longitude === 'number') {
        geoJsonData.features[placeCount] = {
          type: 'Feature',
          id: placeCount,
          properties: {
            NAME: place.Name,
            ADDRESS1: place["Street Address"],
            CITY: place.City,
            ZIP: place.Zip,
            DESCRIPTION: place.Description
          },
          geometry: {
            type: 'Point',
            coordinates: [place.Latitude, place.Longitude]
          }
        };
        placeCount++;
      }
    }
    return geoJsonData;
  },
  createMarkerGeoJsonLayer = function(type) {
    return new L.geoJson(null, {
      pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {
          icon: L.icon({
            iconUrl: "assets/img/pin-" + type + ".png",
            iconSize: [27, 45],
            iconAnchor: [12, 28],
            popupAnchor: [0, -27]
          }),
          title: feature.properties.NAME,
          riseOnHover: true
        });
      },
      onEachFeature: function (feature, layer) {
        if (feature.properties) {
          var content = "

"
            + "" + feature.properties.NAME + ""
            + "
" + feature.properties.DESCRIPTION + ""
            + "
" + feature.properties.ADDRESS1 + "" + "

";
          if (document.body.clientWidth <= 767) {
            layer.on({
              click: function (e) {
                $("#feature-title").html(feature.properties.NAME);
                $("#feature-info").html(content);
                $("#featureModal").modal("show");
              }
            });
          } else {
            layer.bindPopup(content, {
              maxWidth: "auto",
              closeButton: false
            });
          }
        }
      }
    });
  };

/* Basemap Layers */
var mapquestOSM = L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {
  maxZoom: 19,
  subdomains: ["otile1", "otile2", "otile3", "otile4"],
  attribution: 'MapQuest | OpenStreetMap'
});

/* Overlay Layers */
var farmersMarkets = createMarkerGeoJsonLayer('farmersmarkets');
var restaurants = createMarkerGeoJsonLayer('restaurants');
var csas = createMarkerGeoJsonLayer('csa');
var wineries = createMarkerGeoJsonLayer('wineries');
var agritourism = createMarkerGeoJsonLayer('agritourism');
$.getJSON("data/LocalFoodPlaces.json", function (data) {
  restaurants.addData(rucsToGeojson(data, "Restaurants"));
});/**/

window.awfulHackCallback = function() {
  restaurants.addData(rucsToGeojson(window.awfulHackDataStore, "Restaurants"));
  farmersMarkets.addData(rucsToGeojson(window.awfulHackDataStore, "Farmers Market"));
  csas.addData(rucsToGeojson(window.awfulHackDataStore, "CSA"));
  wineries.addData(rucsToGeojson(window.awfulHackDataStore, "Winery"));
  agritourism.addData(rucsToGeojson(window.awfulHackDataStore, "Agritourism"));
}
window.awfulHackDynamicApiLoad();

  map = L.map("map", {
    zoom: 15,
    center: [38.5750753, -121.4844454],
    layers: [mapquestOSM, restaurants]
  });

  /* Larger screens get expanded layer control */
  if (document.body.clientWidth <= 767) {
    var isCollapsed = true;
  } else {
    var isCollapsed = false;
  }

  var overlays = {
      " Restaurants": restaurants,
      " Farmers' Markets": farmersMarkets,
      " CSA": csas,
      " Wineries": wineries,
      " Agritourism": agritourism
    },
    layerControl = L.control.layers(overlays).addTo(map);

  var sidebar = L.control.sidebar("sidebar", {
    closeButton: true,
    position: "left"
  }).addTo(map);

  /* Highlight search box text on click */
  $("#searchbox").click(function () {
    $(this).select();
  });

  /* Typeahead search functionality */
  $(document).one("ajaxStop", function () {
    $("#loading").hide();
    /* instantiate the typeahead UI */
    $("#searchbox").on("typeahead:opened", function () {
      $(".navbar-collapse.in").css("max-height", $(document).height() - $(".navbar-header").height());
      $(".navbar-collapse.in").css("height", $(document).height() - $(".navbar-header").height());
    }).on("typeahead:closed", function () {
      $(".navbar-collapse.in").css("max-height", "");
      $(".navbar-collapse.in").css("height", "");
    });
    $(".twitter-typeahead").css("position", "static");
    $(".twitter-typeahead").css("display", "block");
  });

  /* Placeholder hack for IE */
  if (navigator.appName == "Microsoft Internet Explorer") {
    $("input").each(function () {
      if ($(this).val() === "" && $(this).attr("placeholder") !== "") {
        $(this).val($(this).attr("placeholder"));
        $(this).focus(function () {
          if ($(this).val() === $(this).attr("placeholder")) $(this).val("");
        });
        $(this).blur(function () {
          if ($(this).val() === "") $(this).val($(this).attr("placeholder"));
        });
      }
    });
  }
<commit_msg>remove a bit of unused js<commit_after>var map,
  // typeFilter - optional string type on which to limit data being transformed and returned
  // returns a valid geojson given data input from RUCS (not currently aligned to any standard)
  rucsToGeojson = function(data, typeFilter) {
    // Transform RUCS data into valid geojson
    var placeCount = 0,
      numPlaces = data.length,
      geoJsonData = {
        type: 'FeatureCollection',
        features: []
      };
    for (var i = 0; i < numPlaces; i++) {
      var place = data[i];
      if (place.Type === typeFilter
          && typeof place.Latitude === 'number'
          && typeof place.Longitude === 'number') {
        geoJsonData.features[placeCount] = {
          type: 'Feature',
          id: placeCount,
          properties: {
            NAME: place.Name,
            ADDRESS1: place["Street Address"],
            CITY: place.City,
            ZIP: place.Zip,
            DESCRIPTION: place.Description
          },
          geometry: {
            type: 'Point',
            coordinates: [place.Latitude, place.Longitude]
          }
        };
        placeCount++;
      }
    }
    return geoJsonData;
  },
  createMarkerGeoJsonLayer = function(type) {
    return new L.geoJson(null, {
      pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {
          icon: L.icon({
            iconUrl: "assets/img/pin-" + type + ".png",
            iconSize: [27, 45],
            iconAnchor: [12, 28],
            popupAnchor: [0, -27]
          }),
          title: feature.properties.NAME,
          riseOnHover: true
        });
      },
      onEachFeature: function (feature, layer) {
        if (feature.properties) {
          var content = "

"
            + "" + feature.properties.NAME + ""
            + "
" + feature.properties.DESCRIPTION + ""
            + "
" + feature.properties.ADDRESS1 + "" + "

";
          if (document.body.clientWidth <= 767) {
            layer.on({
              click: function (e) {
                $("#feature-title").html(feature.properties.NAME);
                $("#feature-info").html(content);
                $("#featureModal").modal("show");
              }
            });
          } else {
            layer.bindPopup(content, {
              maxWidth: "auto",
              closeButton: false
            });
          }
        }
      }
    });
  };

/* Basemap Layers */
var mapquestOSM = L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {
  maxZoom: 19,
  subdomains: ["otile1", "otile2", "otile3", "otile4"],
  attribution: 'MapQuest | OpenStreetMap'
});

/* Overlay Layers */
var farmersMarkets = createMarkerGeoJsonLayer('farmersmarkets');
var restaurants = createMarkerGeoJsonLayer('restaurants');
var csas = createMarkerGeoJsonLayer('csa');
var wineries = createMarkerGeoJsonLayer('wineries');
var agritourism = createMarkerGeoJsonLayer('agritourism');
$.getJSON("data/LocalFoodPlaces.json", function (data) {
  restaurants.addData(rucsToGeojson(data, "Restaurants"));
});/**/

window.awfulHackCallback = function() {
  restaurants.addData(rucsToGeojson(window.awfulHackDataStore, "Restaurants"));
  farmersMarkets.addData(rucsToGeojson(window.awfulHackDataStore, "Farmers Market"));
  csas.addData(rucsToGeojson(window.awfulHackDataStore, "CSA"));
  wineries.addData(rucsToGeojson(window.awfulHackDataStore, "Winery"));
  agritourism.addData(rucsToGeojson(window.awfulHackDataStore, "Agritourism"));
}
window.awfulHackDynamicApiLoad();

  map = L.map("map", {
    zoom: 15,
    center: [38.5750753, -121.4844454],
    layers: [mapquestOSM, restaurants]
  });

  var overlays = {
      " Restaurants": restaurants,
      " Farmers' Markets": farmersMarkets,
      " CSA": csas,
      " Wineries": wineries,
      " Agritourism": agritourism
    },
    layerControl = L.control.layers(overlays).addTo(map);

  var sidebar = L.control.sidebar("sidebar", {
    closeButton: true,
    position: "left"
  }).addTo(map);

  /* Highlight search box text on click */
  $("#searchbox").click(function () {
    $(this).select();
  });

  /* Typeahead search functionality */
  $(document).one("ajaxStop", function () {
    $("#loading").hide();
    /* instantiate the typeahead UI */
    $("#searchbox").on("typeahead:opened", function () {
      $(".navbar-collapse.in").css("max-height", $(document).height() - $(".navbar-header").height());
      $(".navbar-collapse.in").css("height", $(document).height() - $(".navbar-header").height());
    }).on("typeahead:closed", function () {
      $(".navbar-collapse.in").css("max-height", "");
      $(".navbar-collapse.in").css("height", "");
    });
    $(".twitter-typeahead").css("position", "static");
    $(".twitter-typeahead").css("display", "block");
  });

  /* Placeholder hack for IE */
  if (navigator.appName == "Microsoft Internet Explorer") {
    $("input").each(function () {
      if ($(this).val() === "" && $(this).attr("placeholder") !== "") {
        $(this).val($(this).attr("placeholder"));
        $(this).focus(function () {
          if ($(this).val() === $(this).attr("placeholder")) $(this).val("");
        });
        $(this).blur(function () {
          if ($(this).val() === "") $(this).val($(this).attr("placeholder"));
        });
      }
    });
  }
<|endoftext|>


<commit_before>//Require Configuration
require.config({
  baseUrl: "assets/js",
  // Break caching (DEVELOPMENTAL SETTING)
  urlArgs: "bust=" + (new Date()).getTime(),
  //Shim for non AMD libraries
  shim: {
    underscore: {
      exports: '_'
    },
    backbone: {
      deps: ["underscore", "jquery"],
      exports: "Backbone"
    },
    bootstrap: {
      deps: ["jquery"]
    }
  },
  paths: {
      // Library Specific Paths
      "backbone":     "lib/backbonejs/backbone-min", // Version:
      "underscore":   "lib/underscorejs/underscore-min", // Version:
      "jquery":       "lib/jQuery/jQuery", // Version:
      "bootstrap":    "lib/bootstrap/bootstrap.min", // Version:
      "doTCompiler":  "lib/doT/doT", // Version:
      "text":         "lib/requirejs-text/text", // Version:
      "doT":          "lib/requirejs-doT/doT" // Version:
  },
  doT: {
    ext: '.dot', // extension of the templates, defaults to .dot
    templateSettings: {
      evaluate:    /\{\{([\s\S]+?)\}\}/g,
      interpolate: /\{\{=([\s\S]+?)\}\}/g,
      encode:      /\{\{!([\s\S]+?)\}\}/g,
      use:         /\{\{#([\s\S]+?)\}\}/g,
      define:      /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
      conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
      iterate:     /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
      varname: 'it',
      strip: true,
      append: true,
      selfcontained: false
    }
  },
  waitSeconds: 15
});

//Kickstart the app
//Loads libraries as required and even shims things nicely
require(["app/app"], function(app) {
  app.init()
});<commit_msg>Added CDN repositories as the first location to request the large libraries. Made the included libraries the fallback version.<commit_after>//Require Configuration
require.config({
  baseUrl: "assets/js",
  // Break caching (DEVELOPMENTAL SETTING)
  urlArgs: "bust=" + (new Date()).getTime(),
  //Shim for non AMD libraries
  shim: {
    underscore: {
      exports: '_'
    },
    backbone: {
      deps: ["underscore", "jquery"],
      exports: "Backbone"
    },
    bootstrap: {
      deps: ["jquery"]
    }
  },
  paths: {
      // Library Specific Paths
      // First load from CDN if available, then fallback to local copies
      "backbone":     ["//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min", "lib/backbonejs/backbone-min"], // Version: 1.1.2 From: http://backbonejs.org/
      "underscore":   ["//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min", "lib/underscorejs/underscore-min"], // Version: 1.6.0 From: http://underscorejs.org/
      "jquery":       ["//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min", "lib/jQuery/jQuery"], // Version: 2.1.1 From: http://jquery.com/
      "bootstrap":    ["//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/js/bootstrap.min", "lib/bootstrap/bootstrap.min"], // Version: 3.1.1 From: http://getbootstrap.com/
      "doTCompiler":  ["lib/doT/doT"], // Version: 1.0.0 From: http://olado.github.io/doT/index.html
      "text":         ["//cdnjs.cloudflare.com/ajax/libs/require-text/2.0.10/text", "lib/requirejs-text/text"], // Version: 2.0.10 From: https://github.com/requirejs/text
      "doT":          ["lib/requirejs-doT/doT"] // Version: 0.1.2. From: https://github.com/ullmark/requirejs-doT
  },
  doT: {
    ext: '.dot', // extension of the templates, defaults to .dot
    templateSettings: {
      evaluate:    /\{\{([\s\S]+?)\}\}/g,
      interpolate: /\{\{=([\s\S]+?)\}\}/g,
      encode:      /\{\{!([\s\S]+?)\}\}/g,
      use:         /\{\{#([\s\S]+?)\}\}/g,
      define:      /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
      conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
      iterate:     /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
      varname: 'it',
      strip: true,
      append: true,
      selfcontained: false
    }
  },
  waitSeconds: 15
});

//Kickstart the app
//Loads libraries as required and even shims things nicely
require(["app/app"], function(app) {
  app.init()
});<|endoftext|>


<commit_before>$(document).ready(function(){
  var txtTarget = $('#cover p');
  var txt = txtTarget.html();
  var leng = txt.length;
  var timer = '';
  var cnt = 0;

  function typing(){
    txtTarget.html(txt.substring(0, cnt)+'_');
    cnt++;
    timer = setTimeout('typing()',100);
    if(leng < cnt){
      clearTimeout(timer)
          cnt = 0;
      }
  }

  typing();
});
<commit_msg>main js<commit_after>$(document).ready(function(){
  var txtTarget = $('#cover p');
  var txt = txtTarget.html();
  var leng = txt.length;
  var timer = '';
  var cnt = 0;

  function typing(){
    txtTarget.html(txt.substring(0, cnt)+'_');
    cnt++;
    timer = setTimeout('typing()',100);
    if(leng < cnt){
      clearTimeout(timer)
          cnt = 0;
      }
  }
});
<|endoftext|>


<commit_before>$(document).ready(function(){
    var myPlaylist;
    var base = "/m/";
    // var playerY = $("#the_player").position().top;
    var playerY = 40;

    var savePlayStatus = function(event) {
        var songs = [];
        var currentSong = 0;
        $(".jp-playlist li[songid]").each(function () {
            songs.push($(this).attr('songid'));
        });

        $('.jp-playlist li').each( function (index) {
            if ($(this).hasClass('jp-playlist-current')) { currentSong = index; return false };
        } )

        var currentTime = event.jPlayer.status.currentTime;

        $.cookie('playlist', songs.join(","), { expires: 30 });
        $.cookie('currentsong', currentSong, { expires: 30 });
        $.cookie('currenttime', currentTime, { expires: 30 });
    };

    var setPlayCookie = function (status) {
        return function (argument) {
                $.cookie('isplay', status, { expires: 30 });
        };
    };

    var playlistTooltip = function () {
        setTimeout(function () {
            $('#the_player li').tooltip('hide');
        }, 2000);
    };

    var play = function(data) {
        myPlaylist.setPlaylist(data);
        myPlaylist.option("autoPlay", true);
        playlistTooltip();
    };

    var readPlayStatus = function () {
        var playerID = "#jquery_jplayer_1";
        if (typeof $.cookie('playlist') != "undefined" && $.cookie('playlist') !== "") {
            var playlist = $.cookie('playlist');
            $.getJSON( base + 'playutils/songplay/' + playlist + "/0", function (data) {
                play(data);
                var index = $.cookie('currentsong');
                var time = $.cookie('currenttime');
                var isPlay = $.cookie('isplay')
                if ( typeof index != "undefined" ) { myPlaylist.select( parseInt(index) ) };
                if ( typeof time != "undefined" ) {
                    if ( isPlay == 1 ) {
                        $(playerID).jPlayer( 'play', parseFloat(time) );
                    } else {
                        $(playerID).jPlayer( 'pause', parseFloat(time) );
                    }

                };
                $(playerID).bind( $.jPlayer.event.timeupdate, savePlayStatus );
                $(playerID).bind( $.jPlayer.event.play,  setPlayCookie(1));
                $(playerID).bind( $.jPlayer.event.pause,  setPlayCookie(0));
            } );
        } else {
            play([]);
            $(playerID).bind( $.jPlayer.event.timeupdate, savePlayStatus );
        }
    };

    var setTagCanvas = function ( canvasid, tagid ) {
        $("#topSongsTags").on( 'click','li.topsongs a', function() {
            var songid = $(this).attr("songid");
            $.getJSON( base + 'playutils/songplay/' + songid + "/0", play );
        });

        if(! $(canvasid).tagcanvas({
                textColour : '#00f',
                textHeight : 25,
                outlineColour : '#ff9999',
                maxSpeed : 0.03,
                minSpeed : 0.005,
                minBrightness : 0.2,
                depth : 0.92,
                pulsateTo : 0.6,
                initial : [0.1,-0.1],
                decel : 0.98,
                reverse : true,
                hideTags : true,
                shadow : '#ccf',
                shadowBlur : 3,
                weight : false,
                imageScale : null,
                fadeIn : 1000
                }, tagid) ) {
            $(canvasid).hide();
        }

        $(window).blur(function(event) {
            $(canvasid).tagcanvas("pause");
        });
        $(window).focus(function(event) {
            $(canvasid).tagcanvas("resume");
        });
        $("#topsongs .timeline label").click(function() {
            var time = $(this).attr("time");
            var user = $("#topsongs .userstatus .active").attr("user");
            $("#topSongsTags").load(base + "home/topsongdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
        $('#topsongs .userstatus label').not(".disabled").click(function() {
            var user = $(this).attr("user");
            var time = $("#topsongs .timeline .active").attr("time");
            $("#topSongsTags").load(base + "home/topsongdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
        $("#topartists .timeline label").click(function() {
            var time = $(this).attr("time");
            var user = $("#topartists .userstatus .active").attr("user");
            $("#topArtistsTags").load(base + "home/topartistdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
        $('#topartists .userstatus label').not(".disabled").click(function() {
            var user = $(this).attr("user");
            var time = $("#topartists .timeline .active").attr("time");
            $("#topArtistsTags").load(base + "home/topartistdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
    };

    myPlaylist = new jPlayerPlaylist(
            {
                jPlayer: "#jquery_jplayer_1",
                cssSelectorAncestor: "#jp_container_1"
            }, [],
            {
                supplied: "mp3,m4a",
                swfPath: "/m/assets/jplayer/js",
                wmode: "window",
                smoothPlayBar: true,
                keyEnabled: true,
                volume: 0.88,
                preload: "auto",
                playlistOptions: {
                    autoPlay: false,
                    enableRemoveControls: true
                },
                ready: readPlayStatus
            }
    );

    var add = function(data) {
        myPlaylist.add(data[0]);
        playlistTooltip();
    };

    var reloadGif = function(){
        $("#data").empty();
        $("#data").append("");
    };

    var songListToggle = function () {
        $(".slide").slideToggle('slow');
        $(".song-list").click(function(){
            $(this).parent().prev().slideToggle('slow');
        });
    };

    var playSongs = function (selector) {
        return  function() {
            var songs = [];

            $(this).parent().parent().find(selector).each(function(){
                if ( this.checked ){
                    songs.push($(this).attr('songid'));
                }
            });
            $.getJSON( base + 'playutils/songplay/' + songs.join(","), play );
        };
    };

    function plays(){
        $("#data").on( 'click','.album-play', playSongs("input"));

        $("#data").on( 'click','.artist-play', playSongs(".in input"));

        $("#data").on( 'click','.song-play', function(){
            var songID = $(this).attr('songid');
            $.getJSON( base + 'playutils/songplay/' + songID, play );
        });

        $("#data").on( 'click','.song-add', function(){
            var songID = $(this).attr('songid');
            $.getJSON( base + 'playutils/songplay/' + songID, add);
        });

        $("#data").on( 'click','.reverse-check', function(){
            $(this).closest("div.songs").find("input[type='checkbox']").each(function(){
                $(this).prop( "checked", !$(this).prop("checked") );
            });
        });

        $("#data").on( 'click','.check-all', function(){
            $(this).closest("div.songs").find("input[type='checkbox']").prop("checked", true);
        });

        $("#data").on( 'click','.uncheck-all', function(){
            $(this).closest("div.songs").find("input[type='checkbox']").prop("checked", false);
        });

        $("#data").on( 'click','.pagination a[pageid]', function(){
            var pageid = $(this).attr("pageid");
            var pagetype = $("#data").attr("pagetype");

            reloadGif();
            $("#data").load( base + pagetype + "/load/" + pageid, $("#searching form").serialize(), function(){
                songListToggle();
            } );

        });

        $("#data").on( 'click', '.playlist-play', function () {
            var songs = $(this).attr("songids");
            $.getJSON( base + 'playutils/songplay/' + songs, play );
        } )

        $("#searching form").submit(function(){
            var pagetype = $("#data").attr("pagetype");
            reloadGif();
            $("#data").load( base + pagetype + "/load", $("#searching form").serialize(), function(){
                songListToggle();
            } );
            return false;
        });

        $("#randoms form").submit(function(){
            $.getJSON( base + 'home/random', $("#randoms form").serialize(), play );
            return false;
        });

        $(window).scroll(function() {
            if ( $(window).scrollTop() >= playerY && $(window).height() > $("#the_player").height() ) {
                $("#the_player").css({ "position": "fixed", "top": "0px" });
            } else {
                $("#the_player").css({ "position": "relative" });
            }
        });

        $('.jp-shuffle').click(playlistTooltip);
    }

    var run= function () {
        songListToggle();
        plays();
        setTagCanvas( "#topSongs", "topSongsTags" );
        setTagCanvas( "#topArtists", "topArtistsTags" );
    };

    run();
});
<commit_msg>fix the issue of setting cookies first time<commit_after>$(document).ready(function(){
    var myPlaylist;
    var base = "/m/";
    // var playerY = $("#the_player").position().top;
    var playerY = 40;

    var savePlayStatus = function(event) {
        var songs = [];
        var currentSong = 0;
        $(".jp-playlist li[songid]").each(function () {
            songs.push($(this).attr('songid'));
        });

        $('.jp-playlist li').each( function (index) {
            if ($(this).hasClass('jp-playlist-current')) { currentSong = index; return false };
        } )

        var currentTime = event.jPlayer.status.currentTime;

        $.cookie('playlist', songs.join(","), { expires: 30, path: '/' });
        $.cookie('currentsong', currentSong, { expires: 30, path: '/' });
        $.cookie('currenttime', currentTime, { expires: 30, path: '/' });
    };

    var setPlayCookie = function (status) {
        return function (argument) {
                $.cookie('isplay', status, { expires: 30, path: '/' });
        };
    };

    var playlistTooltip = function () {
        setTimeout(function () {
            $('#the_player li').tooltip('hide');
        }, 2000);
    };

    var play = function(data) {
        myPlaylist.setPlaylist(data);
        myPlaylist.option("autoPlay", true);
        playlistTooltip();
    };

    var readPlayStatus = function () {
        var playerID = "#jquery_jplayer_1";
        if (typeof $.cookie('playlist') != "undefined" && $.cookie('playlist') !== "") {
            var playlist = $.cookie('playlist');
            $.getJSON( base + 'playutils/songplay/' + playlist + "/0", function (data) {
                play(data);
                $(playerID).bind( $.jPlayer.event.play,  setPlayCookie(1));
                $(playerID).bind( $.jPlayer.event.pause,  setPlayCookie(0));
                var index = $.cookie('currentsong');
                var time = $.cookie('currenttime');
                var isPlay = $.cookie('isplay')
                if ( typeof index != "undefined" ) { myPlaylist.select( parseInt(index) ) };
                if ( typeof time != "undefined" ) {
                    if ( isPlay == 1 ) {
                        $(playerID).jPlayer( 'play', parseFloat(time) );
                    } else {
                        $(playerID).jPlayer( 'pause', parseFloat(time) );
                    }

                };
                $(playerID).bind( $.jPlayer.event.timeupdate, savePlayStatus );

            } );
        } else {
            play([]);
            $(playerID).bind( $.jPlayer.event.play,  setPlayCookie(1));
            $(playerID).bind( $.jPlayer.event.pause,  setPlayCookie(0));
            $(playerID).bind( $.jPlayer.event.timeupdate, savePlayStatus );
        }
    };

    var setTagCanvas = function ( canvasid, tagid ) {
        $("#topSongsTags").on( 'click','li.topsongs a', function() {
            var songid = $(this).attr("songid");
            $.getJSON( base + 'playutils/songplay/' + songid + "/0", play );
        });

        if(! $(canvasid).tagcanvas({
                textColour : '#00f',
                textHeight : 25,
                outlineColour : '#ff9999',
                maxSpeed : 0.03,
                minSpeed : 0.005,
                minBrightness : 0.2,
                depth : 0.92,
                pulsateTo : 0.6,
                initial : [0.1,-0.1],
                decel : 0.98,
                reverse : true,
                hideTags : true,
                shadow : '#ccf',
                shadowBlur : 3,
                weight : false,
                imageScale : null,
                fadeIn : 1000
                }, tagid) ) {
            $(canvasid).hide();
        }

        $(window).blur(function(event) {
            $(canvasid).tagcanvas("pause");
        });
        $(window).focus(function(event) {
            $(canvasid).tagcanvas("resume");
        });
        $("#topsongs .timeline label").click(function() {
            var time = $(this).attr("time");
            var user = $("#topsongs .userstatus .active").attr("user");
            $("#topSongsTags").load(base + "home/topsongdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
        $('#topsongs .userstatus label').not(".disabled").click(function() {
            var user = $(this).attr("user");
            var time = $("#topsongs .timeline .active").attr("time");
            $("#topSongsTags").load(base + "home/topsongdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
        $("#topartists .timeline label").click(function() {
            var time = $(this).attr("time");
            var user = $("#topartists .userstatus .active").attr("user");
            $("#topArtistsTags").load(base + "home/topartistdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
        $('#topartists .userstatus label').not(".disabled").click(function() {
            var user = $(this).attr("user");
            var time = $("#topartists .timeline .active").attr("time");
            $("#topArtistsTags").load(base + "home/topartistdata/" + user + "/" + time + "/" , function () {
                $(canvasid).tagcanvas("reload");
            });
        });
    };

    myPlaylist = new jPlayerPlaylist(
            {
                jPlayer: "#jquery_jplayer_1",
                cssSelectorAncestor: "#jp_container_1"
            }, [],
            {
                supplied: "mp3,m4a",
                swfPath: "/m/assets/jplayer/js",
                wmode: "window",
                smoothPlayBar: true,
                keyEnabled: true,
                volume: 0.88,
                preload: "auto",
                playlistOptions: {
                    autoPlay: false,
                    enableRemoveControls: true
                },
                ready: readPlayStatus
            }
    );

    var add = function(data) {
        myPlaylist.add(data[0]);
        playlistTooltip();
    };

    var reloadGif = function(){
        $("#data").empty();
        $("#data").append("");
    };

    var songListToggle = function () {
        $(".slide").slideToggle('slow');
        $(".song-list").click(function(){
            $(this).parent().prev().slideToggle('slow');
        });
    };

    var playSongs = function (selector) {
        return  function() {
            var songs = [];

            $(this).parent().parent().find(selector).each(function(){
                if ( this.checked ){
                    songs.push($(this).attr('songid'));
                }
            });
            $.getJSON( base + 'playutils/songplay/' + songs.join(","), play );
        };
    };

    function plays(){
        $("#data").on( 'click','.album-play', playSongs("input"));

        $("#data").on( 'click','.artist-play', playSongs(".in input"));

        $("#data").on( 'click','.song-play', function(){
            var songID = $(this).attr('songid');
            $.getJSON( base + 'playutils/songplay/' + songID, play );
        });

        $("#data").on( 'click','.song-add', function(){
            var songID = $(this).attr('songid');
            $.getJSON( base + 'playutils/songplay/' + songID, add);
        });

        $("#data").on( 'click','.reverse-check', function(){
            $(this).closest("div.songs").find("input[type='checkbox']").each(function(){
                $(this).prop( "checked", !$(this).prop("checked") );
            });
        });

        $("#data").on( 'click','.check-all', function(){
            $(this).closest("div.songs").find("input[type='checkbox']").prop("checked", true);
        });

        $("#data").on( 'click','.uncheck-all', function(){
            $(this).closest("div.songs").find("input[type='checkbox']").prop("checked", false);
        });

        $("#data").on( 'click','.pagination a[pageid]', function(){
            var pageid = $(this).attr("pageid");
            var pagetype = $("#data").attr("pagetype");

            reloadGif();
            $("#data").load( base + pagetype + "/load/" + pageid, $("#searching form").serialize(), function(){
                songListToggle();
            } );

        });

        $("#data").on( 'click', '.playlist-play', function () {
            var songs = $(this).attr("songids");
            $.getJSON( base + 'playutils/songplay/' + songs, play );
        } )

        $("#searching form").submit(function(){
            var pagetype = $("#data").attr("pagetype");
            reloadGif();
            $("#data").load( base + pagetype + "/load", $("#searching form").serialize(), function(){
                songListToggle();
            } );
            return false;
        });

        $("#randoms form").submit(function(){
            $.getJSON( base + 'home/random', $("#randoms form").serialize(), play );
            return false;
        });

        $(window).scroll(function() {
            if ( $(window).scrollTop() >= playerY && $(window).height() > $("#the_player").height() ) {
                $("#the_player").css({ "position": "fixed", "top": "0px" });
            } else {
                $("#the_player").css({ "position": "relative" });
            }
        });

        $('.jp-shuffle').click(playlistTooltip);
    }

    var run= function () {
        songListToggle();
        plays();
        setTagCanvas( "#topSongs", "topSongsTags" );
        setTagCanvas( "#topArtists", "topArtistsTags" );
    };

    run();
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var util = require('../../util');

var EnumType = {
  create: function(node, contract) {
    this.type = contract + '.' + node.attributes.name;
    this.values = _.map(node.children, function(node) {
      return node.attributes.name;
    });
    return this;
  },
  is: function(typeName, contract) {
    return typeName == 'enum ' + this.type;
  },
  init: function(node, typeCreator, contract) {
    this.storageType = 'memory';
    this.stackSize = 1;
    return this;
  },
  retrieve: function(storage, hashDict, position) {
    if (position.offset == 32) {
      util.inc(position.index);
      position.offset = 0;
    }

    var entry = _.find(storage, function(entry) {
      return entry.key.equals(position.index);
    });

    var value;
    if (entry) {
      var data = util.decodeRlp(entry.value);
      if (data.length > position.offset) {
        value = data.slice(data.length - position.offset - 1, data.length - position.offset);
      }
    }

    if (position.offset == 31) {
      util.inc(position.index);
      position.offset = 0;
    } else {
      position.offset++;
    }

    return this.parseValue(value);
  },
  retrieveStack: function(stack, index) {
    return this.parseValue(stack[index]);
  },
  parseValue: function(buf) {
    return this.values[buf && buf.length > 0 ? buf[0] : 0];
  }
};

module.exports = EnumType;
<commit_msg>Fix function enum variables reading during debugging<commit_after>var _ = require('lodash');
var util = require('../../util');

var EnumType = {
  create: function(node, contract) {
    this.type = contract + '.' + node.attributes.name;
    this.values = _.map(node.children, function(node) {
      return node.attributes.name;
    });
    return this;
  },
  is: function(typeName, contract) {
    return typeName == 'enum ' + this.type;
  },
  init: function(node, typeCreator, contract) {
    this.storageType = 'memory';
    this.stackSize = 1;
    return this;
  },
  retrieve: function(storage, hashDict, position) {
    if (position.offset == 32) {
      util.inc(position.index);
      position.offset = 0;
    }

    var entry = _.find(storage, function(entry) {
      return entry.key.equals(position.index);
    });

    var value;
    if (entry) {
      var data = util.decodeRlp(entry.value);
      if (data.length > position.offset) {
        value = data.slice(data.length - position.offset - 1, data.length - position.offset);
      }
    }

    if (position.offset == 31) {
      util.inc(position.index);
      position.offset = 0;
    } else {
      position.offset++;
    }

    return this.parseValue(value);
  },
  retrieveStack: function(stack, memory, index) {
    return this.parseValue(stack[index]);
  },
  parseValue: function(buf) {
    return this.values[buf && buf.length > 0 ? buf[0] : 0];
  }
};

module.exports = EnumType;
<|endoftext|>


<commit_before>define(['itemObjectModel', 'mac/roman', 'mac/extendedFloat'], function(itemOM, macRoman, extendedFloat) {

  'use strict';

  function wordAlign(v) { return v + v % 2; }

  function open(item) {
    return item.getBytes().then(function(bytes) {
      if (String.fromCharCode.apply(null, bytes.subarray(0, 4)) !== 'FORM') {
        return Promise.reject('FORM header not found');
      }
      var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      var length = dv.getUint32(4, false);
      if (bytes.byteLength < 8+length) {
        return Promise.reject('invalid data length');
      }
      if (String.fromCharCode.apply(null, bytes.subarray(8, 12)) !== 'AIFF') {
        return Promise.reject('AIFF header not found');
      }
      var audioInfo = {};
      var instrument;
      for (var pos = 12; pos < length; pos += 8 + wordAlign(dv.getUint32(pos + 4, false))) {
        var chunkName = String.fromCharCode.apply(null, bytes.subarray(pos, pos + 4));
        switch (chunkName) {
          case 'COMM':
            var chunkLength = dv.getUint32(pos + 4, false);
            if (chunkLength < 18) {
              return Promise.reject('bad length for COMM chunk (' + chunkLength + ' bytes)');
            }
            var chunkDV = new DataView(
              bytes.buffer,
              bytes.byteOffset + pos + 8,
              bytes.byteOffset + pos + 8 + chunkLength);
            audioInfo.channels = chunkDV.getUint16(0, false);
            audioInfo.numSampleFrames = chunkDV.getUint32(2, false);
            audioInfo.bytesPerSample = chunkDV.getUint16(6, false) / 8;
            audioInfo.sampleRate = extendedFloat(chunkDV, 8);
            break;
          case 'SSND':
            var dataLength = audioInfo.channels * audioInfo.bytesPerSample * audioInfo.numSampleFrames;
            var chunkLength = dv.getUint32(pos + 4, false);
            if (chunkLength < 8 + dataLength) {
              return Promise.reject('bad length for SSND chunk (' + chunkLength + ' bytes)');
            }
            var chunkDV = new DataView(
              bytes.buffer,
              bytes.byteOffset + pos + 8,
              4);
            var offset = chunkDV.getUint16(0, false);
            var blockLength = chunkDV.getUint16(2, false);
            if (offset !== 0 || blockLength !== 0) {
              return Promise.reject('AIFF: offset/blockLength not yet supported');
            }
            audioInfo.samples = bytes.subarray(
              pos + 12,
              pos + 12 + dataLength);
            if (audioInfo.bytesPerSample === 1) {
              var signed = new Int8Array(
                audioInfo.samples.buffer,
                audioInfo.samples.byteOffset,
                audioInfo.samples.byteLength);
              for (var i = 0; i < signed.length; i++) {
                audioInfo.samples[i] = signed[i] + 128;
              }
            }
            break;
          case 'INST':
            var chunkLength = dv.getUint32(pos + 4, false);
            if (chunkLength !== InstrumentView.byteLength) {
              return Promise.reject('bad length for INST chunk (' + chunkLength + ' bytes)');
            }
            instrument = new InstrumentView(
              bytes.buffer,
              bytes.byteOffset + pos + 8,
              InstrumentView.byteLength);
            break;
          case 'MARK':
            var markerCount = dv.getUint16(pos + 8, false);
            for (var markerPos = pos + 8 + 2; markerCount--; ) {
              var markerId = dv.getUint16(markerPos, false);
              var markerPos = dv.getUint32(markerPos + 2, false);
              var markerName = macRoman(bytes, markerPos + 6 + 1, bytes[markerPos + 6]);
              var markerItem = itemOM.createItem('marker ' + markerId + ' ' + markerName);
              markerItem.setDataObject(markerPos);
              item.addItem(markerItem);
              markerPos += 6 + 1 + markerName.length + markerName.length % 2;
            }
            break;
          case 'APPL':
            var applicationSignature = macRoman(bytes, pos + 8, 4);
            var appDataItem = itemOM.createItem('APPL-' + applicationSignature);
            appDataItem.byteSource = item.byteSource.slice(
              pos + 8 + 4,
              pos + 8 + dv.getUint32(pos + 4, false));
            item.addItem(appDataItem);
            break;
          default:
            console.log('AIFF chunk: ' + chunkName);
            break;
        }
      }
      if (instrument) {
        console.log(instrument);
      }
      item.setRawAudio(audioInfo);
    });
  };

  function InstrumentView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      bytes: {value:new Uint8Array(buffer, byteOffset, byteLength)},
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  InstrumentView.prototype = {
    get baseNote() {
      return this.bytes[0]; // MIDI note 0..127, 60 = middle C
    },
    get detune() {
      return this.bytes[1]; // pitch shift -50..+50 cents (-0.5..+0.5 semitone)
    },
    get lowNote() {
      return this.bytes[2]; // MIDI note 0..127
    },
    get highNote() {
      return this.bytes[3]; // MIDI note 0..127
    },
    get lowVelocity() {
      return this.bytes[4]; // MIDI velocity 1..127
    },
    get highVelocity() {
      return this.bytes[5]; // MIDI velocity 1..127
    },
    get gain() {
      return this.dataView.getInt16(6, false); // decibels, e.g. +6=double each sample point, -6=halve each
    },
    get sustainPlayMode() {
      var v;
      switch(v = this.dataView.getUint16(8, false)) {
        case 0: return 'normal';
        case 1: return 'loop';
        case 2: return 'pingpong';
        default: return v;
      }
    },
    get sustainMarker1() {
      return this.dataView.getUint16(10, false);
    },
    get sustainMarker2() {
      return this.dataView.getUint16(12, false);
    },
    get releasePlayMode() {
      var v;
      switch(v = this.dataView.getUint16(14, false)) {
        case 0: return 'normal';
        case 1: return 'loop';
        case 2: return 'pingpong';
        default: return v;
      }
    },
    get releaseMarker1() {
      return this.dataView.getUint16(16, false);
    },
    get releaseMarker2() {
      return this.dataView.getUint16(17, false);
    },
  };
  InstrumentView.byteLength = 20;

  return open;

});
<commit_msg>Stop logging the instrument<commit_after>define(['itemObjectModel', 'mac/roman', 'mac/extendedFloat'], function(itemOM, macRoman, extendedFloat) {

  'use strict';

  function wordAlign(v) { return v + v % 2; }

  function open(item) {
    return item.getBytes().then(function(bytes) {
      if (String.fromCharCode.apply(null, bytes.subarray(0, 4)) !== 'FORM') {
        return Promise.reject('FORM header not found');
      }
      var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      var length = dv.getUint32(4, false);
      if (bytes.byteLength < 8+length) {
        return Promise.reject('invalid data length');
      }
      if (String.fromCharCode.apply(null, bytes.subarray(8, 12)) !== 'AIFF') {
        return Promise.reject('AIFF header not found');
      }
      var audioInfo = {};
      var instrument;
      for (var pos = 12; pos < length; pos += 8 + wordAlign(dv.getUint32(pos + 4, false))) {
        var chunkName = String.fromCharCode.apply(null, bytes.subarray(pos, pos + 4));
        switch (chunkName) {
          case 'COMM':
            var chunkLength = dv.getUint32(pos + 4, false);
            if (chunkLength < 18) {
              return Promise.reject('bad length for COMM chunk (' + chunkLength + ' bytes)');
            }
            var chunkDV = new DataView(
              bytes.buffer,
              bytes.byteOffset + pos + 8,
              bytes.byteOffset + pos + 8 + chunkLength);
            audioInfo.channels = chunkDV.getUint16(0, false);
            audioInfo.numSampleFrames = chunkDV.getUint32(2, false);
            audioInfo.bytesPerSample = chunkDV.getUint16(6, false) / 8;
            audioInfo.sampleRate = extendedFloat(chunkDV, 8);
            break;
          case 'SSND':
            var dataLength = audioInfo.channels * audioInfo.bytesPerSample * audioInfo.numSampleFrames;
            var chunkLength = dv.getUint32(pos + 4, false);
            if (chunkLength < 8 + dataLength) {
              return Promise.reject('bad length for SSND chunk (' + chunkLength + ' bytes)');
            }
            var chunkDV = new DataView(
              bytes.buffer,
              bytes.byteOffset + pos + 8,
              4);
            var offset = chunkDV.getUint16(0, false);
            var blockLength = chunkDV.getUint16(2, false);
            if (offset !== 0 || blockLength !== 0) {
              return Promise.reject('AIFF: offset/blockLength not yet supported');
            }
            audioInfo.samples = bytes.subarray(
              pos + 12,
              pos + 12 + dataLength);
            if (audioInfo.bytesPerSample === 1) {
              var signed = new Int8Array(
                audioInfo.samples.buffer,
                audioInfo.samples.byteOffset,
                audioInfo.samples.byteLength);
              for (var i = 0; i < signed.length; i++) {
                audioInfo.samples[i] = signed[i] + 128;
              }
            }
            break;
          case 'INST':
            var chunkLength = dv.getUint32(pos + 4, false);
            if (chunkLength !== InstrumentView.byteLength) {
              return Promise.reject('bad length for INST chunk (' + chunkLength + ' bytes)');
            }
            instrument = new InstrumentView(
              bytes.buffer,
              bytes.byteOffset + pos + 8,
              InstrumentView.byteLength);
            break;
          case 'MARK':
            var markerCount = dv.getUint16(pos + 8, false);
            for (var markerPos = pos + 8 + 2; markerCount--; ) {
              var markerId = dv.getUint16(markerPos, false);
              var markerPos = dv.getUint32(markerPos + 2, false);
              var markerName = macRoman(bytes, markerPos + 6 + 1, bytes[markerPos + 6]);
              var markerItem = itemOM.createItem('marker ' + markerId + ' ' + markerName);
              markerItem.setDataObject(markerPos);
              item.addItem(markerItem);
              markerPos += 6 + 1 + markerName.length + markerName.length % 2;
            }
            break;
          case 'APPL':
            var applicationSignature = macRoman(bytes, pos + 8, 4);
            var appDataItem = itemOM.createItem('APPL-' + applicationSignature);
            appDataItem.byteSource = item.byteSource.slice(
              pos + 8 + 4,
              pos + 8 + dv.getUint32(pos + 4, false));
            item.addItem(appDataItem);
            break;
          default:
            console.log('AIFF chunk: ' + chunkName);
            break;
        }
      }
      item.setRawAudio(audioInfo);
    });
  };

  function InstrumentView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      bytes: {value:new Uint8Array(buffer, byteOffset, byteLength)},
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  InstrumentView.prototype = {
    get baseNote() {
      return this.bytes[0]; // MIDI note 0..127, 60 = middle C
    },
    get detune() {
      return this.bytes[1]; // pitch shift -50..+50 cents (-0.5..+0.5 semitone)
    },
    get lowNote() {
      return this.bytes[2]; // MIDI note 0..127
    },
    get highNote() {
      return this.bytes[3]; // MIDI note 0..127
    },
    get lowVelocity() {
      return this.bytes[4]; // MIDI velocity 1..127
    },
    get highVelocity() {
      return this.bytes[5]; // MIDI velocity 1..127
    },
    get gain() {
      return this.dataView.getInt16(6, false); // decibels, e.g. +6=double each sample point, -6=halve each
    },
    get sustainPlayMode() {
      var v;
      switch(v = this.dataView.getUint16(8, false)) {
        case 0: return 'normal';
        case 1: return 'loop';
        case 2: return 'pingpong';
        default: return v;
      }
    },
    get sustainMarker1() {
      return this.dataView.getUint16(10, false);
    },
    get sustainMarker2() {
      return this.dataView.getUint16(12, false);
    },
    get releasePlayMode() {
      var v;
      switch(v = this.dataView.getUint16(14, false)) {
        case 0: return 'normal';
        case 1: return 'loop';
        case 2: return 'pingpong';
        default: return v;
      }
    },
    get releaseMarker1() {
      return this.dataView.getUint16(16, false);
    },
    get releaseMarker2() {
      return this.dataView.getUint16(17, false);
    },
  };
  InstrumentView.byteLength = 20;

  return open;

});
<|endoftext|>


<commit_before>var request = require("request");

exports.hook_rcpt = function(next, connection, params) {
    var plugin = this;
    var transaction = connection.transaction;
    transaction.parse_body = true;

    var cfg = plugin.config.get('webhooks.ini');
    connection.notes.config = cfg;
    request.post(cfg.main.auth_url)
	.form({
	    "recipients": transaction.rcpt_to[0].user + "@" + transaction.rcpt_to[0].host,
	    "sender": transaction.mail_from.original
	})
	.on('response', function(response) {
	    response.on('data', function(data) {
	    	if (response.statusCode >= 200 && response.statusCode < 300) {
	    	    next(OK, data);
	    	}
	    	if (response.statusCode >= 400 && response.statusCode < 500) {
	    	    next(DENY, data);
	    	}
	    	if (response.statusCode >= 500) {
	    	    next(DENYSOFT, data);
	    	}
	    });
	})
	.on('error', function(error, response, body) {
	    next(DENYSOFT, body);
	});
}

exports.hook_data_post = function(next, connection, params) {
    var plugin = this;
    var transaction = connection.transaction;

    connection.notes.discard = true;
    var cfg = connection.notes.config;
    var body = transaction.body.children.slice(-1)[0];
    request.post(cfg.main.mail_url)
	.form({
	    "recipients": transaction.rcpt_to[0].user + "@" + transaction.rcpt_to[0].host,
	    "sender": transaction.mail_from.original,
	    "subject": transaction.body.header.get("Subject"),
	    "body": body.bodytext,
	    "headers": transaction.body.header.toString()
	})
	.on('response', function(response) {
	    response.on('data', function(data) {
	    	if (response.statusCode >= 200 && response.statusCode < 300) {
	    	    next(OK, data);
	    	}
	    	if (response.statusCode >= 400 && response.statusCode < 500) {
	    	    next(DENY, data);
	    	}
	    	if (response.statusCode >= 500) {
	    	    next(DENYSOFT, data);
	    	}
	    });
	})
	.on('error', function(error, response, body) {
	    next(DENYSOFT, "sys_unspecified");
	});
}
<commit_msg>Get the body of the mail. Covers multipart/mixed and multipart/alternative.<commit_after>var request = require("request");

exports.hook_rcpt = function(next, connection, params) {
    var plugin = this;
    var transaction = connection.transaction;
    transaction.parse_body = true;

    var cfg = plugin.config.get('webhooks.ini');
    connection.notes.config = cfg;
    request.post(cfg.main.auth_url)
	.form({
	    "recipients": transaction.rcpt_to[0].user + "@" + transaction.rcpt_to[0].host,
	    "sender": transaction.mail_from.original
	})
	.on('response', function(response) {
	    response.on('data', function(data) {
	    	if (response.statusCode >= 200 && response.statusCode < 300) {
	    	    next(OK, data);
	    	}
	    	if (response.statusCode >= 400 && response.statusCode < 500) {
	    	    next(DENY, data);
	    	}
	    	if (response.statusCode >= 500) {
	    	    next(DENYSOFT, data);
	    	}
	    });
	})
	.on('error', function(error, response, body) {
	    next(DENYSOFT, body);
	});
}

function getBody(children) {
    var ret = null;
    for (var ii=0; ii < children.length; ii++) {
	if (children[ii].state === 'body') {
	    ret = children[ii];
	} else {
	    if (children[ii].children.length > 0) {
		ret = getMultipartAlternative(children[ii].children);
	    }
	}
    }
    return ret;
}

exports.hook_data_post = function(next, connection, params) {
    var plugin = this;
    var transaction = connection.transaction;

    connection.notes.discard = true;
    var cfg = connection.notes.config;
    var body;
    if (transaction.body.children.length > 0) {
	body = getBody(transaction.body.children);
    } else {
	body = transaction.body;
    }
    request.post(cfg.main.mail_url)
	.form({
	    "recipients": transaction.rcpt_to[0].user + "@" + transaction.rcpt_to[0].host,
	    "sender": transaction.mail_from.original,
	    "subject": transaction.body.header.get("Subject"),
	    "body": body.bodytext || 'Blank Message',
	    "headers": transaction.body.header.toString()
	})
	.on('response', function(response) {
	    response.on('data', function(data) {
	    	if (response.statusCode >= 200 && response.statusCode < 300) {
	    	    next(OK, data);
	    	}
	    	if (response.statusCode >= 400 && response.statusCode < 500) {
	    	    next(DENY, data);
	    	}
	    	if (response.statusCode >= 500) {
	    	    next(DENYSOFT, data);
	    	}
	    });
	})
	.on('error', function(error, response, body) {
	    next(DENYSOFT, "sys_unspecified");
	});
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         YT ratio
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Stores visited video likes / dislikes ratios and creates browsable rankings.
// @author       Flagoul
// @match        https://www.youtube.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function fetchValues() {
        let values = document.querySelectorAll(".like-button-renderer > span:nth-of-type(odd) button span");
        let likes = parseInt(values[0].textContent.replace(/\s+/g, ""));
        let dislikes = parseInt(values[1].textContent.replace(/\s+/g, ""));

        return {
            "views": parseInt(document.querySelector(".watch-view-count").textContent.split(/\s+/).slice(0, -1).join("")),
            "likes": likes,
            "dislikes": dislikes,
            "ratio": likes/dislikes,
            "url": values[0].baseURI
        };
    }

    console.log(fetchValues());
})();<commit_msg>Raw display for ratio + fetching values on reload<commit_after>// ==UserScript==
// @name         YT ratio
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Stores visited video likes / dislikes ratios and creates browsable rankings.
// @author       Flagoul
// @match        https://www.youtube.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function fetchValues() {
        let values = document.querySelectorAll(".like-button-renderer > span:nth-of-type(odd) button span");

        if (values.length === 0) {
            return null;
        }

        let likes = parseInt(values[0].textContent.replace(/\s+/g, ""));
        let dislikes = parseInt(values[1].textContent.replace(/\s+/g, ""));

        return {
            "views": parseInt(document.querySelector(".watch-view-count").textContent.split(/\s+/).slice(0, -1).join("")),
            "likes": likes,
            "dislikes": dislikes,
            "ratio": likes/dislikes,
            "url": values[0].baseURI
        };
    }

    function displayRatioAndSaveValues() {
        let values = fetchValues();
        if (values !== null) {
            console.log("values:");
            console.log(values);

            let ratio = document.createElement("span");
            ratio.appendChild(document.createTextNode(values.ratio.toFixed(2)));
            document.querySelector(".like-button-renderer").appendChild(ratio);
        }
    }

    displayRatioAndSaveValues();

    window.addEventListener("spfdone", function(e) {
        displayRatioAndSaveValues();
    });
})();<|endoftext|>


<commit_before>var async = require('async');
var fetchData = require('./lib/fetch_data');
var data = require('./lib/data');
var util = require('./lib/util');

async.waterfall([
    function saveSummaryForAll (callback){
      // get the total combined numbers
      data.update2014TotalActive(null, function updatedAll (err) {
        callback(null);
      });
    },
    function saveSummaryForTeams (callback){
      var teams = util.validTeamNames();

      async.each(teams,
        function toEach (team, callback) {
          data.update2014TotalActive(team, function updatedAll (err) {
            callback(null);
          });
        },
        function eachDone (err) {
          callback(null);
        }
      );
    },
    function fetchLatestGithubData (callback){
      fetchData.fetchMoreData(function fetched (err, res) {
        callback(null);
      });
    }
], function (err, result) {
   console.log('summaries and tables updated');
   process.exit(0);
});

<commit_msg>testing on heroku<commit_after>var async = require('async');
var fetchData = require('./lib/fetch_data');
var data = require('./lib/data');
var util = require('./lib/util');

async.waterfall([
    function saveSummaryForAll (callback){
      console.log('saveSummaryForAll');
      // get the total combined numbers
      data.update2014TotalActive(null, function updatedAll (err) {
        callback(null);
      });
    },
    function saveSummaryForTeams (callback){
      var teams = util.validTeamNames();

      async.each(teams,
        function toEach (team, callback) {
          data.update2014TotalActive(team, function updatedAll (err) {
            callback(null);
          });
        },
        function eachDone (err) {
          callback(null);
        }
      );
    },
    function fetchLatestGithubData (callback){
      fetchData.fetchMoreData(function fetched (err, res) {
        callback(null);
      });
    }
], function (err, result) {
   console.log('summaries and tables updated');
   process.exit(0);
});

<|endoftext|>