<commit_before>$( document ).ready(function() {
  $("#map-data").hide();
  $("#getLocation").click(function(){
    console.log("getting location!");
    getLocation();
  });
});

function autoCompleteInit(){
  var start_input = /** @type {!HTMLInputElement} */(
      document.getElementById('start'));
  var end_input = /** @type {!HTMLInputElement} */(
      document.getElementById('end'));
  var start_autocomplete = new google.maps.places.Autocomplete(start_input);
  var end_autocomplete = new google.maps.places.Autocomplete(end_input);
}

function getLocation(){
  //var infoWindow = new google.maps.InfoWindow({map: map});

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(savePosition);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
}

function savePosition(position) {
   $("#start").val(position.coords.latitude + ", " + position.coords.longitude);
}

// Load the Visualization API and the columnchart package.
google.load('visualization', '1', {packages: ['columnchart']});

$("#getMap").click(function(){
  console.log("Getting Map!");

  initMap();
  $("#map-data").show("slow");

  $('html, body').animate({
    scrollTop: $("#map-data").offset().top
  }, 2000);

});

var mousemarker = null;
var map = null;

function initMap() {

  console.log("Initializing map");

  // Initialize path with random starting location
  var path = [
    {lat: 37.77, lng: -122.447},
    {lat: 37.768, lng: -122.511}];

  var start = $("#start").val();
  var end = $("#end").val();

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: path[0],
    mapTypeId: 'roadmap',
  });

  var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    panel: document.getElementById('right-panel')
  });

  var directionsService = new google.maps.DirectionsService;

  // Create an ElevationService.
  var elevator = new google.maps.ElevationService;

  directionsDisplay.setMap(map);

  directionsDisplay.addListener('directions_changed', function() {
    var directions = directionsDisplay.getDirections();
    console.log(directions);

    var start_lat = directions.routes[0].legs[0].steps[0].start_location.lat();
    var start_lng = directions.routes[0].legs[0].steps[0].start_location.lng();
    var end_lat = directions.routes[0].legs[0].steps[0].end_location.lat();
    var end_lng = directions.routes[0].legs[0].steps[0].end_location.lng();

    var start_add = directions.routes[0].legs[0].start_address;
    var end_add = directions.routes[0].legs[0].end_address;

    console.log(start_add);
    console.log(end_add);

    path[0] = {lat: start_lat, lng: start_lng};
    path[1] = {lat: end_lat, lng: end_lng};

    console.log(path);
    // Draw the path, using the Visualization API and the Elevation service.
    displayPathElevation(start_add, end_add, path, elevator, directionsService, directionsDisplay, map);

  });

  displayRoute(start, end, directionsService, directionsDisplay, map);

}

function displayRoute(origin, destination, service, display, map) {
  service.route({
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.WALKING,
    provideRouteAlternatives: true
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      console.log("Response:");
      console.log(response);
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}

//Draws routes on map
function displayPathElevation(origin, destination, path, elevator, directionsService, display, map) {

  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.

  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.WALKING,
    provideRouteAlternatives: true
    //waypoints: waypoints
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      //console.log("Routes:");
      //console.log(response.routes);
      //display.setDirections({routes: []});

      //display.setMap(null);
      //display.setMap(null);

      //new google.maps.DirectionsRenderer({
      //  map: map,
      //  directions: response,
      //  routeIndex: 2
      //});

      findBestRoute(response.routes, elevator);

      //TODO: uncomment
      //elevator.getElevationAlongPath({
      //  path: response.routes[2].overview_path,
      //  samples: 256
      //}, plotElevation);

    } else if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
      alert("Could not find a route between these points");
    } else {
      alert("Directions request failed");
    }
  });

}

//HACK: dont look haha
//TODO: async calls mean the routes might be processed in diff order. This need sto be fixed.
var data = [];
var route_leng = 0;

function findBestRoute(routes, elevator){
  route_leng = routes.length;
  for(var q = 0; q < routes.length; q++){
    elevator.getElevationAlongPath({
      path: routes[q].overview_path,
      samples: 256
    }, processResults);
  }

}

function processResults(elevations, status){
  //console.log("New Elev:");
  //console.log(elevations);

  var final = [];
  var dev = 0;

  //Create a new array of elevations
  for(var i = 0; i < elevations.length; i++){
      final.push(elevations[i].elevation);
  }

  //console.log("Final Array:");
  //console.log(final);

  console.log("Standard Deviation:");
  dev = math.std(final);
  console.log(dev);

  data.push(dev);

  if(route_leng === data.length){

    var best = data.indexOf(Math.min.apply( Math, data ));

    console.log("Minimum:");
    console.log(best);

  }

}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(elevations, status) {

  console.log("Elevations: ");
  console.log(elevations);

  var chartDiv = document.getElementById('elevation_chart');
  if (status !== google.maps.ElevationStatus.OK) {
    // Show the error code inside the chartDiv.
    chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
        status;
    return;
  }
  // Create a new chart in the elevation_chart DIV.
  var chart = new google.visualization.ColumnChart(chartDiv);

  //Move blue marker when mouse is over elevation chart
  google.visualization.events.addListener(chart, 'onmouseover', function(e) {
    if (mousemarker == null) {
      mousemarker = new google.maps.Marker({
        position: elevations[e.row].location,
        map: map,
        icon: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
      });
    } else {
      mousemarker.setPosition(elevations[e.row].location);
    }
  });

  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Sample');
  data.addColumn('number', 'Elevation');
  for (var i = 0; i < elevations.length; i++) {
    data.addRow(['', elevations[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: 'none',
    titleY: 'Elevation (m)'
  });
}

// Remove the green rollover marker when the mouse leaves the chart
function clearMouseMarker() {
  if (mousemarker != null) {
    mousemarker.setMap(null);
    mousemarker = null;
  }
}
<commit_msg>best path works. code is horrid and major flaw needs to be solved<commit_after>$( document ).ready(function() {
  $("#map-data").hide();
  $("#getLocation").click(function(){
    console.log("getting location!");
    getLocation();
  });
});

function autoCompleteInit(){
  var start_input = /** @type {!HTMLInputElement} */(
      document.getElementById('start'));
  var end_input = /** @type {!HTMLInputElement} */(
      document.getElementById('end'));
  var start_autocomplete = new google.maps.places.Autocomplete(start_input);
  var end_autocomplete = new google.maps.places.Autocomplete(end_input);
}

function getLocation(){
  //var infoWindow = new google.maps.InfoWindow({map: map});

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(savePosition);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
}

function savePosition(position) {
   $("#start").val(position.coords.latitude + ", " + position.coords.longitude);
}

// Load the Visualization API and the columnchart package.
google.load('visualization', '1', {packages: ['columnchart']});

$("#getMap").click(function(){
  console.log("Getting Map!");

  initMap();
  $("#map-data").show("slow");

  $('html, body').animate({
    scrollTop: $("#map-data").offset().top
  }, 2000);

});

var mousemarker = null;
var map = null;
var directionsDisplay = null;
var directionsService = null;
var elevator = null;

function initMap() {

  console.log("Initializing map");

  // Initialize path with random starting location
  var path = [
    {lat: 37.77, lng: -122.447},
    {lat: 37.768, lng: -122.511}];

  var start = $("#start").val();
  var end = $("#end").val();

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: path[0],
    mapTypeId: 'roadmap',
  });

  directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    panel: document.getElementById('right-panel')
  });

  directionsService = new google.maps.DirectionsService;

  // Create an ElevationService.
  elevator = new google.maps.ElevationService;

  directionsDisplay.setMap(map);

  directionsDisplay.addListener('directions_changed', function() {
    var directions = directionsDisplay.getDirections();
    console.log(directions);

    var start_lat = directions.routes[0].legs[0].steps[0].start_location.lat();
    var start_lng = directions.routes[0].legs[0].steps[0].start_location.lng();
    var end_lat = directions.routes[0].legs[0].steps[0].end_location.lat();
    var end_lng = directions.routes[0].legs[0].steps[0].end_location.lng();

    var start_add = directions.routes[0].legs[0].start_address;
    var end_add = directions.routes[0].legs[0].end_address;

    console.log(start_add);
    console.log(end_add);

    path[0] = {lat: start_lat, lng: start_lng};
    path[1] = {lat: end_lat, lng: end_lng};

    console.log(path);
    // Draw the path, using the Visualization API and the Elevation service.
    displayPathElevation(start_add, end_add, path, elevator, directionsService, directionsDisplay, map);

  });

  displayRoute(start, end, directionsService, directionsDisplay, map);

}

function displayRoute(origin, destination, service, display, map) {
  service.route({
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.WALKING,
    provideRouteAlternatives: true
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      console.log("Response:");
      console.log(response);
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}

//Draws routes on map
function displayPathElevation(origin, destination, path, elevator, directionsService, display, map) {

  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.

  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.WALKING,
    provideRouteAlternatives: true
    //waypoints: waypoints
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      //console.log("Routes:");
      //console.log(response.routes);
      //display.setDirections({routes: []});

      //display.setMap(null);

      //new google.maps.DirectionsRenderer({
      //  map: map,
      //  directions: response,
      //  routeIndex: 2
      //});

      curr_response = response;
      findBestRoute(response.routes, elevator);

      //TODO: uncomment
      //elevator.getElevationAlongPath({
      //  path: response.routes[2].overview_path,
      //  samples: 256
      //}, plotElevation);

    } else if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
      alert("Could not find a route between these points");
    } else {
      alert("Directions request failed");
    }
  });

}

//HACK: dont look haha
//TODO: async calls mean the routes might be processed in diff order. This need sto be fixed.
var data = [];

var route_leng = 0;
var curr_response = null;

function findBestRoute(routes, elevator){
  route_leng = routes.length;
  for(var q = 0; q < routes.length; q++){
    elevator.getElevationAlongPath({
      path: routes[q].overview_path,
      samples: 256
    }, processResults);
  }

}

function processResults(elevations, status){
  //console.log("New Elev:");
  //console.log(elevations);

  var final = [];
  var dev = 0;

  //Create a new array of elevations
  for(var i = 0; i < elevations.length; i++){
      final.push(elevations[i].elevation);
  }

  //console.log("Final Array:");
  //console.log(final);

  console.log("Standard Deviation:");
  dev = math.std(final);
  console.log(dev);

  data.push(dev);

  if(route_leng === data.length){

    var best = data.indexOf(Math.min.apply( Math, data ));

    console.log("Minimum:");
    console.log(best);

    renderEverything(best);

  }

}

function renderEverything(best){
  //Makes markers unmovable
  directionsDisplay.setMap(null);

  new google.maps.DirectionsRenderer({
    map: map,
    directions: curr_response,
    routeIndex: best
  });

  elevator.getElevationAlongPath({
    path: curr_response.routes[best].overview_path,
    samples: 256
  }, plotElevation);
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(elevations, status) {

  console.log("Elevations: ");
  console.log(elevations);

  var chartDiv = document.getElementById('elevation_chart');
  if (status !== google.maps.ElevationStatus.OK) {
    // Show the error code inside the chartDiv.
    chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
        status;
    return;
  }
  // Create a new chart in the elevation_chart DIV.
  var chart = new google.visualization.ColumnChart(chartDiv);

  //Move blue marker when mouse is over elevation chart
  google.visualization.events.addListener(chart, 'onmouseover', function(e) {
    if (mousemarker == null) {
      mousemarker = new google.maps.Marker({
        position: elevations[e.row].location,
        map: map,
        icon: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
      });
    } else {
      mousemarker.setPosition(elevations[e.row].location);
    }
  });

  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Sample');
  data.addColumn('number', 'Elevation');
  for (var i = 0; i < elevations.length; i++) {
    data.addRow(['', elevations[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: 'none',
    titleY: 'Elevation (m)'
  });
}

// Remove the green rollover marker when the mouse leaves the chart
function clearMouseMarker() {
  if (mousemarker != null) {
    mousemarker.setMap(null);
    mousemarker = null;
  }
}
<|endoftext|>


<commit_before>module.exports =
{ "AED": "د.إ"
, "AFN": "؋"
, "ALL": "L"
, "ANG": "ƒ"
, "AOA": "Kz"
, "ARS": "$"
, "AUD": "$"
, "AWG": "ƒ"
, "AZN": "₼"
, "BAM": "KM"
, "BBD": "$"
, "BDT": "৳"
, "BGN": "лв"
, "BHD": ".د.ب"
, "BIF": "FBu"
, "BMD": "$"
, "BND": "$"
, "BOB": "Bs."
, "BRL": "R$"
, "BSD": "$"
, "BTN": "Nu."
, "BWP": "P"
, "BYR": "p."
, "BZD": "BZ$"
, "CAD": "$"
, "CDF": "FC"
, "CHF": "Fr."
, "CLP": "$"
, "CNY": "¥"
, "COP": "$"
, "CRC": "₡"
, "CUC": "$"
, "CUP": "₱"
, "CVE": "$"
, "CZK": "Kč"
, "DJF": "Fdj"
, "DKK": "kr"
, "DOP": "RD$"
, "DZD": "دج"
, "EEK": "kr"
, "EGP": "£"
, "ERN": "Nfk"
, "ETB": "Br"
, "EUR": "€"
, "FJD": "$"
, "FKP": "£"
, "GBP": "£"
, "GEL": "₾"
, "GGP": "£"
, "GHC": "₵"
, "GHS": "GH₵"
, "GIP": "£"
, "GMD": "D"
, "GNF": "FG"
, "GTQ": "Q"
, "GYD": "$"
, "HKD": "$"
, "HNL": "L"
, "HRK": "kn"
, "HTG": "G"
, "HUF": "Ft"
, "IDR": "Rp"
, "ILS": "₪"
, "IMP": "£"
, "INR": "₹"
, "IQD": "ع.د"
, "IRR": "﷼"
, "ISK": "kr"
, "JEP": "£"
, "JMD": "J$"
, "JPY": "¥"
, "KES": "KSh"
, "KGS": "лв"
, "KHR": "៛"
, "KMF": "CF"
, "KPW": "₩"
, "KRW": "₩"
, "KYD": "$"
, "KZT": "₸"
, "LAK": "₭"
, "LBP": "£"
, "LKR": "₨"
, "LRD": "$"
, "LSL": "M"
, "LTL": "Lt"
, "LVL": "Ls"
, "MAD": "MAD"
, "MDL": "lei"
, "MGA": "Ar"
, "MKD": "ден"
, "MMK": "K"
, "MNT": "₮"
, "MOP": "MOP$"
, "MUR": "₨"
, "MVR": "Rf"
, "MWK": "MK"
, "MXN": "$"
, "MYR": "RM"
, "MZN": "MT"
, "NAD": "$"
, "NGN": "₦"
, "NIO": "C$"
, "NOK": "kr"
, "NPR": "₨"
, "NZD": "$"
, "OMR": "﷼"
, "PAB": "B/."
, "PEN": "S/."
, "PGK": "K"
, "PHP": "₱"
, "PKR": "₨"
, "PLN": "zł"
, "PYG": "Gs"
, "QAR": "﷼"
, "RMB": "￥"
, "RON": "lei"
, "RSD": "Дин."
, "RUB": "₽"
, "RWF": "R₣"
, "SAR": "﷼"
, "SBD": "$"
, "SCR": "₨"
, "SDG": "ج.س."
, "SEK": "kr"
, "SGD": "$"
, "SHP": "£"
, "SLL": "Le"
, "SOS": "S"
, "SRD": "$"
, "SSP": "£"
, "STD": "Db"
, "SVC": "$"
, "SYP": "£"
, "SZL": "E"
, "THB": "฿"
, "TJS": "SM"
, "TMT": "T"
, "TND": "د.ت"
, "TOP": "T$"
, "TRL": "₤"
, "TRY": "₺"
, "TTD": "TT$"
, "TVD": "$"
, "TWD": "NT$"
, "TZS": "TSh"
, "UAH": "₴"
, "UGX": "USh"
, "USD": "$"
, "UYU": "$U"
, "UZS": "лв"
, "VEF": "Bs"
, "VND": "₫"
, "VUV": "VT"
, "WST": "WS$"
, "XAF": "FCFA"
, "XBT": "Ƀ"
, "XCD": "$"
, "XOF": "CFA"
, "XPF": "₣"
, "YER": "﷼"
, "ZAR": "R"
, "ZWD": "Z$"
}
<commit_msg>Add the BTC symbol<commit_after>module.exports =
{ "AED": "د.إ"
, "AFN": "؋"
, "ALL": "L"
, "ANG": "ƒ"
, "AOA": "Kz"
, "ARS": "$"
, "AUD": "$"
, "AWG": "ƒ"
, "AZN": "₼"
, "BAM": "KM"
, "BBD": "$"
, "BDT": "৳"
, "BGN": "лв"
, "BHD": ".د.ب"
, "BIF": "FBu"
, "BMD": "$"
, "BND": "$"
, "BOB": "Bs."
, "BRL": "R$"
, "BSD": "$"
, "BTN": "Nu."
, "BWP": "P"
, "BYR": "p."
, "BZD": "BZ$"
, "CAD": "$"
, "CDF": "FC"
, "CHF": "Fr."
, "CLP": "$"
, "CNY": "¥"
, "COP": "$"
, "CRC": "₡"
, "CUC": "$"
, "CUP": "₱"
, "CVE": "$"
, "CZK": "Kč"
, "DJF": "Fdj"
, "DKK": "kr"
, "DOP": "RD$"
, "DZD": "دج"
, "EEK": "kr"
, "EGP": "£"
, "ERN": "Nfk"
, "ETB": "Br"
, "EUR": "€"
, "FJD": "$"
, "FKP": "£"
, "GBP": "£"
, "GEL": "₾"
, "GGP": "£"
, "GHC": "₵"
, "GHS": "GH₵"
, "GIP": "£"
, "GMD": "D"
, "GNF": "FG"
, "GTQ": "Q"
, "GYD": "$"
, "HKD": "$"
, "HNL": "L"
, "HRK": "kn"
, "HTG": "G"
, "HUF": "Ft"
, "IDR": "Rp"
, "ILS": "₪"
, "IMP": "£"
, "INR": "₹"
, "IQD": "ع.د"
, "IRR": "﷼"
, "ISK": "kr"
, "JEP": "£"
, "JMD": "J$"
, "JPY": "¥"
, "KES": "KSh"
, "KGS": "лв"
, "KHR": "៛"
, "KMF": "CF"
, "KPW": "₩"
, "KRW": "₩"
, "KYD": "$"
, "KZT": "₸"
, "LAK": "₭"
, "LBP": "£"
, "LKR": "₨"
, "LRD": "$"
, "LSL": "M"
, "LTL": "Lt"
, "LVL": "Ls"
, "MAD": "MAD"
, "MDL": "lei"
, "MGA": "Ar"
, "MKD": "ден"
, "MMK": "K"
, "MNT": "₮"
, "MOP": "MOP$"
, "MUR": "₨"
, "MVR": "Rf"
, "MWK": "MK"
, "MXN": "$"
, "MYR": "RM"
, "MZN": "MT"
, "NAD": "$"
, "NGN": "₦"
, "NIO": "C$"
, "NOK": "kr"
, "NPR": "₨"
, "NZD": "$"
, "OMR": "﷼"
, "PAB": "B/."
, "PEN": "S/."
, "PGK": "K"
, "PHP": "₱"
, "PKR": "₨"
, "PLN": "zł"
, "PYG": "Gs"
, "QAR": "﷼"
, "RMB": "￥"
, "RON": "lei"
, "RSD": "Дин."
, "RUB": "₽"
, "RWF": "R₣"
, "SAR": "﷼"
, "SBD": "$"
, "SCR": "₨"
, "SDG": "ج.س."
, "SEK": "kr"
, "SGD": "$"
, "SHP": "£"
, "SLL": "Le"
, "SOS": "S"
, "SRD": "$"
, "SSP": "£"
, "STD": "Db"
, "SVC": "$"
, "SYP": "£"
, "SZL": "E"
, "THB": "฿"
, "TJS": "SM"
, "TMT": "T"
, "TND": "د.ت"
, "TOP": "T$"
, "TRL": "₤"
, "TRY": "₺"
, "TTD": "TT$"
, "TVD": "$"
, "TWD": "NT$"
, "TZS": "TSh"
, "UAH": "₴"
, "UGX": "USh"
, "USD": "$"
, "UYU": "$U"
, "UZS": "лв"
, "VEF": "Bs"
, "VND": "₫"
, "VUV": "VT"
, "WST": "WS$"
, "XAF": "FCFA"
, "XBT": "Ƀ"
, "XCD": "$"
, "XOF": "CFA"
, "XPF": "₣"
, "YER": "﷼"
, "ZAR": "R"
, "ZWD": "Z$"
, "BTC": "฿"
}
<|endoftext|>


<commit_before>(function(){
  var crypt = require('crypt'),
      utf8 = require('charenc').utf8,
      bin = require('charenc').bin,

  // The core
  md5 = function (message, options) {
    // Convert to byte array
    if (message.constructor == String)
      if (options && options.encoding === 'binary')
        message = bin.stringToBytes(message);
      else
        message = utf8.stringToBytes(message);
    else if (typeof Buffer != 'undefined' &&
        typeof Buffer.isBuffer == 'function' && Buffer.isBuffer(message))
      message = Array.prototype.slice.call(message, 0);
    else if (!Array.isArray(message))
      message = message.toString();
    // else, assume byte array already

    var m = crypt.bytesToWords(message),
        l = message.length * 8,
        a =  1732584193,
        b = -271733879,
        c = -1732584194,
        d =  271733878;

    // Swap endian
    for (var i = 0; i < m.length; i++) {
      m[i] = ((m[i] <<  8) | (m[i] >>> 24)) & 0x00FF00FF |
             ((m[i] << 24) | (m[i] >>>  8)) & 0xFF00FF00;
    }

    // Padding
    m[l >>> 5] |= 0x80 << (l % 32);
    m[(((l + 64) >>> 9) << 4) + 14] = l;

    // Method shortcuts
    var FF = md5._ff,
        GG = md5._gg,
        HH = md5._hh,
        II = md5._ii;

    for (var i = 0; i < m.length; i += 16) {

      var aa = a,
          bb = b,
          cc = c,
          dd = d;

      a = FF(a, b, c, d, m[i+ 0],  7, -680876936);
      d = FF(d, a, b, c, m[i+ 1], 12, -389564586);
      c = FF(c, d, a, b, m[i+ 2], 17,  606105819);
      b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);
      a = FF(a, b, c, d, m[i+ 4],  7, -176418897);
      d = FF(d, a, b, c, m[i+ 5], 12,  1200080426);
      c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);
      b = FF(b, c, d, a, m[i+ 7], 22, -45705983);
      a = FF(a, b, c, d, m[i+ 8],  7,  1770035416);
      d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);
      c = FF(c, d, a, b, m[i+10], 17, -42063);
      b = FF(b, c, d, a, m[i+11], 22, -1990404162);
      a = FF(a, b, c, d, m[i+12],  7,  1804603682);
      d = FF(d, a, b, c, m[i+13], 12, -40341101);
      c = FF(c, d, a, b, m[i+14], 17, -1502002290);
      b = FF(b, c, d, a, m[i+15], 22,  1236535329);

      a = GG(a, b, c, d, m[i+ 1],  5, -165796510);
      d = GG(d, a, b, c, m[i+ 6],  9, -1069501632);
      c = GG(c, d, a, b, m[i+11], 14,  643717713);
      b = GG(b, c, d, a, m[i+ 0], 20, -373897302);
      a = GG(a, b, c, d, m[i+ 5],  5, -701558691);
      d = GG(d, a, b, c, m[i+10],  9,  38016083);
      c = GG(c, d, a, b, m[i+15], 14, -660478335);
      b = GG(b, c, d, a, m[i+ 4], 20, -405537848);
      a = GG(a, b, c, d, m[i+ 9],  5,  568446438);
      d = GG(d, a, b, c, m[i+14],  9, -1019803690);
      c = GG(c, d, a, b, m[i+ 3], 14, -187363961);
      b = GG(b, c, d, a, m[i+ 8], 20,  1163531501);
      a = GG(a, b, c, d, m[i+13],  5, -1444681467);
      d = GG(d, a, b, c, m[i+ 2],  9, -51403784);
      c = GG(c, d, a, b, m[i+ 7], 14,  1735328473);
      b = GG(b, c, d, a, m[i+12], 20, -1926607734);

      a = HH(a, b, c, d, m[i+ 5],  4, -378558);
      d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);
      c = HH(c, d, a, b, m[i+11], 16,  1839030562);
      b = HH(b, c, d, a, m[i+14], 23, -35309556);
      a = HH(a, b, c, d, m[i+ 1],  4, -1530992060);
      d = HH(d, a, b, c, m[i+ 4], 11,  1272893353);
      c = HH(c, d, a, b, m[i+ 7], 16, -155497632);
      b = HH(b, c, d, a, m[i+10], 23, -1094730640);
      a = HH(a, b, c, d, m[i+13],  4,  681279174);
      d = HH(d, a, b, c, m[i+ 0], 11, -358537222);
      c = HH(c, d, a, b, m[i+ 3], 16, -722521979);
      b = HH(b, c, d, a, m[i+ 6], 23,  76029189);
      a = HH(a, b, c, d, m[i+ 9],  4, -640364487);
      d = HH(d, a, b, c, m[i+12], 11, -421815835);
      c = HH(c, d, a, b, m[i+15], 16,  530742520);
      b = HH(b, c, d, a, m[i+ 2], 23, -995338651);

      a = II(a, b, c, d, m[i+ 0],  6, -198630844);
      d = II(d, a, b, c, m[i+ 7], 10,  1126891415);
      c = II(c, d, a, b, m[i+14], 15, -1416354905);
      b = II(b, c, d, a, m[i+ 5], 21, -57434055);
      a = II(a, b, c, d, m[i+12],  6,  1700485571);
      d = II(d, a, b, c, m[i+ 3], 10, -1894986606);
      c = II(c, d, a, b, m[i+10], 15, -1051523);
      b = II(b, c, d, a, m[i+ 1], 21, -2054922799);
      a = II(a, b, c, d, m[i+ 8],  6,  1873313359);
      d = II(d, a, b, c, m[i+15], 10, -30611744);
      c = II(c, d, a, b, m[i+ 6], 15, -1560198380);
      b = II(b, c, d, a, m[i+13], 21,  1309151649);
      a = II(a, b, c, d, m[i+ 4],  6, -145523070);
      d = II(d, a, b, c, m[i+11], 10, -1120210379);
      c = II(c, d, a, b, m[i+ 2], 15,  718787259);
      b = II(b, c, d, a, m[i+ 9], 21, -343485551);

      a = (a + aa) >>> 0;
      b = (b + bb) >>> 0;
      c = (c + cc) >>> 0;
      d = (d + dd) >>> 0;
    }

    return crypt.endian([a, b, c, d]);
  };

  // Auxiliary functions
  md5._ff  = function (a, b, c, d, x, s, t) {
    var n = a + (b & c | ~b & d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._gg  = function (a, b, c, d, x, s, t) {
    var n = a + (b & d | c & ~d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._hh  = function (a, b, c, d, x, s, t) {
    var n = a + (b ^ c ^ d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._ii  = function (a, b, c, d, x, s, t) {
    var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };

  // Package private blocksize
  md5._blocksize = 16;
  md5._digestsize = 16;

  module.exports = function (message, options) {
    var digestbytes = crypt.wordsToBytes(md5(message, options));
    return options && options.asBytes ? digestbytes :
        options && options.asString ? bin.bytesToString(digestbytes) :
        crypt.bytesToHex(digestbytes);
  };

})();
<commit_msg>Fix for crash when passing undefined<commit_after>(function(){
  var crypt = require('crypt'),
      utf8 = require('charenc').utf8,
      bin = require('charenc').bin,

  // The core
  md5 = function (message, options) {

    if(typeof message === "undefined") {
          return;
    }
    // Convert to byte array
    if (message.constructor == String)
      if (options && options.encoding === 'binary')
        message = bin.stringToBytes(message);
      else
        message = utf8.stringToBytes(message);
    else if (typeof Buffer != 'undefined' &&
        typeof Buffer.isBuffer == 'function' && Buffer.isBuffer(message))
      message = Array.prototype.slice.call(message, 0);
    else if (!Array.isArray(message))
      message = message.toString();
    // else, assume byte array already

    var m = crypt.bytesToWords(message),
        l = message.length * 8,
        a =  1732584193,
        b = -271733879,
        c = -1732584194,
        d =  271733878;

    // Swap endian
    for (var i = 0; i < m.length; i++) {
      m[i] = ((m[i] <<  8) | (m[i] >>> 24)) & 0x00FF00FF |
             ((m[i] << 24) | (m[i] >>>  8)) & 0xFF00FF00;
    }

    // Padding
    m[l >>> 5] |= 0x80 << (l % 32);
    m[(((l + 64) >>> 9) << 4) + 14] = l;

    // Method shortcuts
    var FF = md5._ff,
        GG = md5._gg,
        HH = md5._hh,
        II = md5._ii;

    for (var i = 0; i < m.length; i += 16) {

      var aa = a,
          bb = b,
          cc = c,
          dd = d;

      a = FF(a, b, c, d, m[i+ 0],  7, -680876936);
      d = FF(d, a, b, c, m[i+ 1], 12, -389564586);
      c = FF(c, d, a, b, m[i+ 2], 17,  606105819);
      b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);
      a = FF(a, b, c, d, m[i+ 4],  7, -176418897);
      d = FF(d, a, b, c, m[i+ 5], 12,  1200080426);
      c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);
      b = FF(b, c, d, a, m[i+ 7], 22, -45705983);
      a = FF(a, b, c, d, m[i+ 8],  7,  1770035416);
      d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);
      c = FF(c, d, a, b, m[i+10], 17, -42063);
      b = FF(b, c, d, a, m[i+11], 22, -1990404162);
      a = FF(a, b, c, d, m[i+12],  7,  1804603682);
      d = FF(d, a, b, c, m[i+13], 12, -40341101);
      c = FF(c, d, a, b, m[i+14], 17, -1502002290);
      b = FF(b, c, d, a, m[i+15], 22,  1236535329);

      a = GG(a, b, c, d, m[i+ 1],  5, -165796510);
      d = GG(d, a, b, c, m[i+ 6],  9, -1069501632);
      c = GG(c, d, a, b, m[i+11], 14,  643717713);
      b = GG(b, c, d, a, m[i+ 0], 20, -373897302);
      a = GG(a, b, c, d, m[i+ 5],  5, -701558691);
      d = GG(d, a, b, c, m[i+10],  9,  38016083);
      c = GG(c, d, a, b, m[i+15], 14, -660478335);
      b = GG(b, c, d, a, m[i+ 4], 20, -405537848);
      a = GG(a, b, c, d, m[i+ 9],  5,  568446438);
      d = GG(d, a, b, c, m[i+14],  9, -1019803690);
      c = GG(c, d, a, b, m[i+ 3], 14, -187363961);
      b = GG(b, c, d, a, m[i+ 8], 20,  1163531501);
      a = GG(a, b, c, d, m[i+13],  5, -1444681467);
      d = GG(d, a, b, c, m[i+ 2],  9, -51403784);
      c = GG(c, d, a, b, m[i+ 7], 14,  1735328473);
      b = GG(b, c, d, a, m[i+12], 20, -1926607734);

      a = HH(a, b, c, d, m[i+ 5],  4, -378558);
      d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);
      c = HH(c, d, a, b, m[i+11], 16,  1839030562);
      b = HH(b, c, d, a, m[i+14], 23, -35309556);
      a = HH(a, b, c, d, m[i+ 1],  4, -1530992060);
      d = HH(d, a, b, c, m[i+ 4], 11,  1272893353);
      c = HH(c, d, a, b, m[i+ 7], 16, -155497632);
      b = HH(b, c, d, a, m[i+10], 23, -1094730640);
      a = HH(a, b, c, d, m[i+13],  4,  681279174);
      d = HH(d, a, b, c, m[i+ 0], 11, -358537222);
      c = HH(c, d, a, b, m[i+ 3], 16, -722521979);
      b = HH(b, c, d, a, m[i+ 6], 23,  76029189);
      a = HH(a, b, c, d, m[i+ 9],  4, -640364487);
      d = HH(d, a, b, c, m[i+12], 11, -421815835);
      c = HH(c, d, a, b, m[i+15], 16,  530742520);
      b = HH(b, c, d, a, m[i+ 2], 23, -995338651);

      a = II(a, b, c, d, m[i+ 0],  6, -198630844);
      d = II(d, a, b, c, m[i+ 7], 10,  1126891415);
      c = II(c, d, a, b, m[i+14], 15, -1416354905);
      b = II(b, c, d, a, m[i+ 5], 21, -57434055);
      a = II(a, b, c, d, m[i+12],  6,  1700485571);
      d = II(d, a, b, c, m[i+ 3], 10, -1894986606);
      c = II(c, d, a, b, m[i+10], 15, -1051523);
      b = II(b, c, d, a, m[i+ 1], 21, -2054922799);
      a = II(a, b, c, d, m[i+ 8],  6,  1873313359);
      d = II(d, a, b, c, m[i+15], 10, -30611744);
      c = II(c, d, a, b, m[i+ 6], 15, -1560198380);
      b = II(b, c, d, a, m[i+13], 21,  1309151649);
      a = II(a, b, c, d, m[i+ 4],  6, -145523070);
      d = II(d, a, b, c, m[i+11], 10, -1120210379);
      c = II(c, d, a, b, m[i+ 2], 15,  718787259);
      b = II(b, c, d, a, m[i+ 9], 21, -343485551);

      a = (a + aa) >>> 0;
      b = (b + bb) >>> 0;
      c = (c + cc) >>> 0;
      d = (d + dd) >>> 0;
    }

    return crypt.endian([a, b, c, d]);
  };

  // Auxiliary functions
  md5._ff  = function (a, b, c, d, x, s, t) {
    var n = a + (b & c | ~b & d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._gg  = function (a, b, c, d, x, s, t) {
    var n = a + (b & d | c & ~d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._hh  = function (a, b, c, d, x, s, t) {
    var n = a + (b ^ c ^ d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._ii  = function (a, b, c, d, x, s, t) {
    var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };

  // Package private blocksize
  md5._blocksize = 16;
  md5._digestsize = 16;

  module.exports = function (message, options) {

    if(typeof message === "undefined") {
          return;
    }

    var digestbytes = crypt.wordsToBytes(md5(message, options));
    return options && options.asBytes ? digestbytes :
        options && options.asString ? bin.bytesToString(digestbytes) :
        crypt.bytesToHex(digestbytes);
  };

})();
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var readTextFileSync = require('read-text-file-sync');
var path = require('path');
var extname = path.extname;
var basename = path.basename;
var express = require('express');
var app = express();
var uploadsPath = 'uploads';
var multer = require('multer');
var upload = multer({ dest: uploadsPath });
var uploadPage = readTextFileSync(__dirname + '/upload.html');
var key = process.env.TEAMKEY;

if(!key) {
    console.error("Missing TEAMKEY.");
    process.exit(-1);
}

function keyCheck(req, res, next) {
    if(req.params.key !== key) {
        res.status(403);
        res.send("Bad team key.");
        return;
    }

    next();
}

app.get('/upload/:key', keyCheck, function(req, res) {
    res.send(uploadPage);
});

app.post('/upload/:key', keyCheck, upload.single('file'), function(req, res) {
    var originalPath = uploadsPath + '/' + req.file.filename;
    var newPath = originalPath + extname(req.file.originalname);
    var relUrl;

    fs.renameSync(originalPath, newPath);

    relUrl = '/' + basename(newPath) + '/' + req.file.originalname;

    if(req.get('User-Agent').startsWith('curl/')) {
        res.send(relUrl);
    }
    else {
        res.redirect(relUrl);
    }
});

app.use(function(req, res, next) {
    var urlPath = req.url;
    var reResults;

    reResults = /^(\/[^\/]+)/.exec(urlPath);

    if(!reResults) {
        next();
        return;
    }

    req.url = reResults[1];

    next();
});

app.use(express.static(uploadsPath));

app.listen(process.env.PORT || 3000);
<commit_msg>Run paths over realpathSync when determining MIME types based on file extensions.<commit_after>'use strict';

var fs = require('fs');
var readTextFileSync = require('read-text-file-sync');
var path = require('path');
var extname = path.extname;
var basename = path.basename;
var realpathSync = fs.realpathSync;
var express = require('express');
var app = express();
var uploadsPath = 'uploads';
var multer = require('multer');
var upload = multer({ dest: uploadsPath });
var uploadPage = readTextFileSync(__dirname + '/upload.html');
var key = process.env.TEAMKEY;

if(!key) {
    console.error("Missing TEAMKEY.");
    process.exit(-1);
}

function keyCheck(req, res, next) {
    if(req.params.key !== key) {
        res.status(403);
        res.send("Bad team key.");
        return;
    }

    next();
}

app.get('/upload/:key', keyCheck, function(req, res) {
    res.send(uploadPage);
});

app.post('/upload/:key', keyCheck, upload.single('file'), function(req, res) {
    var originalPath = uploadsPath + '/' + req.file.filename;
    var newPath = originalPath + extname(req.file.originalname);
    var relUrl;

    fs.renameSync(originalPath, newPath);

    relUrl = '/' + basename(newPath) + '/' + req.file.originalname;

    if(req.get('User-Agent').startsWith('curl/')) {
        res.send(relUrl);
    }
    else {
        res.redirect(relUrl);
    }
});

app.use(function(req, res, next) {
    var urlPath = req.url;
    var reResults;

    reResults = /^(\/[^\/]+)/.exec(urlPath);

    if(!reResults) {
        next();
        return;
    }

    req.url = reResults[1];

    next();
});

{
    let mime = express.static.mime;

    let originalFn = mime.lookup;

    mime.lookup = function (path, fallback) {
        if(fs.existsSync(path)) {
            path = realpathSync(path);
        }

        return originalFn.call(this, path, fallback);
    };
}

app.use(express.static(uploadsPath));

app.listen(process.env.PORT || 3000);
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

"use strict";

var express = require('express');
var twig = require('twig');
//var utils = require('./utils.js');

var app = express();
app.use(express.logger());
app.use(express.bodyParser());

app.use('/bootstrap', express.static(__dirname + '/bootstrap'));
app.use('/img', express.static(__dirname + '/img'));

//utils.dbConnect();

app.get('/node/', function(request, response) {
	response.send('Node.js is up and running.');
});

function extend(source, destination) {
	for (var i in source) {
		destination[i] = source[i];
	}
	return destination;
}

function phpgate(request, response)
{
	var child_process = require('child_process');
	var querystring = require('querystring');

	var env = {};
	extend(process.env, env);
	extend({
		'GATEWAY_INTERFACE': 'CGI/1.1',
		//SCRIPT_NAME: options.mountPoint,
		'SCRIPT_FILENAME': 'index.php',
		'REDIRECT_STATUS': 200,
		//PATH_INFO: req.uri.pathname.substring(options.mountPoint.length),
		'REQUEST_URI': request.originalUrl,
		//SERVER_NAME: address || 'unknown',
		//SERVER_PORT: port || 80,
		//SERVER_PROTOCOL: SERVER_PROTOCOL,
		//SERVER_SOFTWARE: SERVER_SOFTWARE
	}, env);
	for (var header in request.headers) {
		var name = 'HTTP_' + header.toUpperCase().replace(/-/g, '_');
		env[name] = request.headers[header];
	}
	//extend(options.env, env);
	env.REQUEST_METHOD = request.method;
	//env.QUERY_STRING = request.uri.query || '';
	if ('content-length' in request.headers) {
		env.CONTENT_LENGTH = request.headers['content-length'];
	}
	if ('content-type' in request.headers) {
		env.CONTENT_TYPE = request.headers['content-type'];
	}
	if ('authorization' in request.headers) {
		var auth = request.headers.authorization.split(' ');
		env.AUTH_TYPE = auth[0];
	}
	// SPAWN!
	var cgiSpawn = child_process.spawn('php-cgi', [], { env: env });
	// Re-send POST data
	cgiSpawn.stdin.write(querystring.stringify(request.body));

	var CGIParser = require('./cgiparser.js');
	var cgiResult = new CGIParser(cgiSpawn.stdout);
	// When the blank line after the headers has been parsed, then
	// the 'headers' event is emitted with a Headers instance.
	cgiResult.on('headers', function(headers) {
		headers.forEach(function(header) {
			// Don't set the 'Status' header. It's special, and should be
			// used to set the HTTP response code below.
			if (header.key === 'Status') return;
			response.header(header.key, header.value);
		});

		// set the response status code
		response.statusCode = parseInt(headers.status, 10) || 200;

		cgiResult.on('data', function (chunk) {
			response.send(chunk);
		});
	});
}

app.get('/', phpgate);
app.get('/about/', phpgate);
app.get('/register/', phpgate);
app.post('/register/', phpgate);
app.get('/login/', phpgate);
app.post('/login/', phpgate);
app.post('/profile/', phpgate);
// http://expressjs.com/api.html#app.VERB
//app.post('/profile/id/{id}/', phpgate);
//app.post('/profile/user/{user}/', phpgate);
app.get('/action/logout', phpgate);
app.get('/game/', phpgate);
//app.get('/action/go/{to}', phpgate);
app.get('/action/attack', phpgate);
app.get('/action/escape', phpgate);
//app.get('/ajax/isNickBusy/{nick}', phpgate);
app.get('/stats/', phpgate);
app.get('/world/', phpgate);
app.get('/development/', phpgate);

/*
app.get('/', function(request, response) {
	response.redirect('/about/');
});

app.get('/about/', function(request, response) {
	var t = Date.now();
	var options = {};
	options.instance = 'about';
	options.loggedIn = false;
	response.render('about.twig', options);
	console.log(request.path+' - done in '+(Date.now()-t)+' ms');
});
*/

/***** main *****/
var port = process.env.PORT || 5000;
app.listen(port, function() {
	console.log("Listening on " + port);
	if (port==5000) console.log("Try http://localhost:" + port + "/");
});
<commit_msg>CGI seems to function properly. Closes #188.<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

"use strict";

var express = require('express');
var twig = require('twig');
//var utils = require('./utils.js');

var app = express();
app.use(express.logger());
app.use(express.bodyParser());

app.use('/bootstrap', express.static(__dirname + '/bootstrap'));
app.use('/img', express.static(__dirname + '/img'));

//utils.dbConnect();

app.get('/node/', function(request, response) {
	response.send('Node.js is up and running.');
});

function extend(source, destination) {
	for (var i in source) {
		destination[i] = source[i];
	}
	return destination;
}

function phpgate(request, response)
{
	var child_process = require('child_process');
	var querystring = require('querystring');

	var env = {};
	extend(process.env, env);
	extend({
		'GATEWAY_INTERFACE': 'CGI/1.1',
		//SCRIPT_NAME: options.mountPoint,
		'SCRIPT_FILENAME': 'index.php',
		'REDIRECT_STATUS': 200,
		//PATH_INFO: req.uri.pathname.substring(options.mountPoint.length),
		'REQUEST_URI': request.originalUrl,
		//SERVER_NAME: address || 'unknown',
		//SERVER_PORT: port || 80,
		//SERVER_PROTOCOL: SERVER_PROTOCOL,
		//SERVER_SOFTWARE: SERVER_SOFTWARE
	}, env);
	for (var header in request.headers) {
		var name = 'HTTP_' + header.toUpperCase().replace(/-/g, '_');
		env[name] = request.headers[header];
	}
	//extend(options.env, env);
	env.REQUEST_METHOD = request.method;
	//env.QUERY_STRING = request.uri.query || '';
	if ('content-length' in request.headers) {
		env.CONTENT_LENGTH = request.headers['content-length'];
	}
	if ('content-type' in request.headers) {
		env.CONTENT_TYPE = request.headers['content-type'];
	}
	if ('authorization' in request.headers) {
		var auth = request.headers.authorization.split(' ');
		env.AUTH_TYPE = auth[0];
	}
	// SPAWN!
	var cgiSpawn = child_process.spawn('php-cgi', [], { env: env });
	// Re-send POST data
	cgiSpawn.stdin.write(querystring.stringify(request.body));

	var CGIParser = require('./cgiparser.js');
	var cgiResult = new CGIParser(cgiSpawn.stdout);
	// When the blank line after the headers has been parsed, then
	// the 'headers' event is emitted with a Headers instance.
	cgiResult.on('headers', function(headers) {
		headers.forEach(function(header) {
			// Don't set the 'Status' header. It's special, and should be
			// used to set the HTTP response code below.
			if (header.key === 'Status') return;
			response.header(header.key, header.value);
		});

		// set the response status code
		response.statusCode = parseInt(headers.status, 10) || 200;

		cgiResult.on('data', function (chunk) {
			response.send(chunk);
		});
	});
}

app.get('/', phpgate);
app.get('/about/', phpgate);
app.get('/register/', phpgate);
app.post('/register/', phpgate);
app.get('/login/', phpgate);
app.post('/login/', phpgate);
app.get('/profile/', phpgate);
app.get('/profile/id/:id/', phpgate);
app.get('/profile/user/:user/', phpgate);
app.get('/action/logout', phpgate);
app.get('/game/', phpgate);
app.get('/action/go/:to', phpgate);
app.get('/action/attack', phpgate);
app.get('/action/escape', phpgate);
app.get('/ajax/isNickBusy/:nick', phpgate);
app.get('/stats/', phpgate);
app.get('/world/', phpgate);
app.get('/development/', phpgate);

/*
app.get('/', function(request, response) {
	response.redirect('/about/');
});

app.get('/about/', function(request, response) {
	var t = Date.now();
	var options = {};
	options.instance = 'about';
	options.loggedIn = false;
	response.render('about.twig', options);
	console.log(request.path+' - done in '+(Date.now()-t)+' ms');
});
*/

/***** main *****/
var port = process.env.PORT || 5000;
app.listen(port, function() {
	console.log("Listening on " + port);
	if (port==5000) console.log("Try http://localhost:" + port + "/");
});
<|endoftext|>


<commit_before>var path = require('path')
  , fs = require('fs')
  , watch = require('watch')
  , request = require('request')
  , crypto = require('crypto')
  , mimetypes = require('./mimetypes')
  , spawn = require('child_process').spawn
  ;

var h = {'content-type':'application/json', 'accept-type':'application/json'}

/**
 * Recursively load directory contents into ddoc
 *
 * It's really convenient to see the main couchapp code in single file,
 * rather than mapped into little files in lots of directories like
 * the python couchapp. But there are definitely cases where we might want
 * to use some module or another on the server side. This addition
 * loads file contents from a given directory (recursively) into a js
 * object that can be added to a design document and require()'d in
 * lists, shows, etc.
 *
 * Use couchapp.loadFiles() in app.js like this:
 *
 *    ddoc = {
 *        _id: '_design/app'
 *      , views: {}
 *      , ...
 *      , lib: couchapp.loadFiles('./lib')
 *      , vendor: couchapp.loadFiles('./vendor')
 *    }
 *
 * Optionally, pass in operators to process file contents. For example,
 * generate mustache templates from jade templates.
 *
 * In yourapp/templates/index.jade
 *
 * !!!5
 * html
 *   head
 *     //- jade locals.title
 *     title!= title
 *   body
 *     .item
 *       //- mustache variable for server-side rendering
 *       h1 {{ heading }}
 *
 * in yourapp/app.js
 * var couchapp = require('couchapp')
 *   , jade = require('jade')
 *   , options = {
 *       , operators: [
 *           function renderJade (content, options) {
 *             var compiler = jade.compile(content);
 *             return compiler(options.locals || {});
 *           }
 *         ]
 *       , locals: { title: 'Now we\'re cookin with gas!' }
 *   };
 *
 * ddoc = { ... };
 *
 * ddoc.templates = loadFiles(dir, options);
 */

function loadFiles(dir, options) {
  var listings = fs.readdirSync(dir)
    , options = options || {}
    , obj = {};

  listings.forEach(function (listing) {
    var file = path.join(dir, listing)
      , prop = listing.split('.')[0] // probably want regexp or something more robust
      , stat = fs.statSync(file);

      if (stat.isFile()) {
        var content = fs.readFileSync(file).toString();
        if (options.operators) {
          options.operators.forEach(function (op) {
            content = op(content, options);
          });
        }
        obj[prop] = content;
      } else if (stat.isDirectory()) {
        obj[listing] = loadFiles(file, options);
      }
  });

  return obj;
}

/**
 * End of patch (also see exports and end of file)
 */

function loadAttachments (doc, root, prefix) {
  doc.__attachments = doc.__attachments || []
  try {
    fs.statSync(root)
  } catch(e) {
    throw e
    throw new Error("Cannot stat file "+root)
  }
  doc.__attachments.push({root:root, prefix:prefix});
}

function copy (obj) {
  var n = {}
  for (i in obj) n[i] = obj[i];
  return n
}

function playSound () {
  fs.exists("/usr/bin/afplay", function (exists) {
    if (exists === true) {
      spawn("/usr/bin/afplay", ["/System/Library/Sounds/Blow.aiff"]);
    }
  })
}

function createApp (doc, url, cb) {
  var app = {doc:doc}

  app.fds = {};

  app.prepare = function () {
    var p = function (x) {
      for (i in x) {
        if (i[0] != '_') {
          if (typeof x[i] == 'function') {
            x[i] = x[i].toString()
            x[i] = 'function '+x[i].slice(x[i].indexOf('('))
          }
          if (typeof x[i] == 'object') {
            p(x[i])
          }
        }
      }
    }
    p(app.doc);
    app.doc.__attachments = app.doc.__attachments || []
    app.doc.attachments_md5 = app.doc.attachments_md5 || {}
    app.doc._attachments = app.doc._attachments || {}
  }

  var push = function (callback) {
    console.log('Serializing.')
    var doc = copy(app.doc);
    doc._attachments = copy(app.doc._attachments)
    delete doc.__attachments;
    var body = JSON.stringify(doc)
    console.log('PUT '+url.replace(/^(https?:\/\/[^@:]+):[^@]+@/, '$1:******@'))
    request({uri:url, method:'PUT', body:body, headers:h}, function (err, resp, body) {
      if (err) throw err;
      if (resp.statusCode !== 201) {
        throw new Error("Could not push document\nCode: " + resp.statusCode + "\n"+body);
      }
      app.doc._rev = JSON.parse(body).rev
      console.log('Finished push. '+app.doc._rev)
      playSound();
      request({uri:url, headers:h}, function (err, resp, body) {
        body = JSON.parse(body);
        app.doc._attachments = body._attachments;
        if (callback) callback()
      })
    })
  }

  app.push = function (callback) {
    var revpos
      , pending_dirs = 0
      ;

    console.log('Preparing.')
    var doc = app.current;
    for (i in app.doc) {
      if (i !== '_rev') doc[i] = app.doc[i]
    }
    app.doc = doc;
    app.prepare();
    revpos = app.doc._rev ? parseInt(app.doc._rev.slice(0,app.doc._rev.indexOf('-'))) : 0;

    var coffeeCompile;
    var coffeeExt;
    try{
      coffeeCompile = require('coffee-script');
      coffeeExt = /\.(lit)?coffee$/;
    } catch(e){}

    app.doc.__attachments.forEach(function (att) {
      watch.walk(att.root, {ignoreDotFiles:true}, function (err, files) {
        pending_dirs += 1;
        var pending_files = Object.keys(files).length;
        for (i in files) { (function (f) {
          fs.readFile(f, function (err, data) {
            if(f.match(coffeeExt)){
              data = new Buffer( coffeeCompile.compile(data.toString()) );
              f = f.replace(coffeeExt,'.js');
            }
            f = f.replace(att.root, att.prefix || '').replace(/\\/g,"/");
            if (f[0] == '/') f = f.slice(1)
            if (!err) {
              var d = data.toString('base64')
                , md5 = crypto.createHash('md5')
                , mime = mimetypes.lookup(path.extname(f).slice(1))
                ;
              md5.update(d)
              md5 = md5.digest('hex')
              if (app.doc.attachments_md5[f] && app.doc._attachments[f]) {
                if (app.doc._attachments[f].revpos === app.doc.attachments_md5[f].revpos &&
                    app.doc.attachments_md5[f].md5 === md5) {
                  pending_files -= 1;
                  if(pending_files === 0){
                    pending_dirs -= 1;
                    if(pending_dirs === 0){
                      push(callback);
                    }
                  }
                  return; // Does not need to be updated.
                }
              }
              app.doc._attachments[f] = {data:d, content_type:mime};
              app.doc.attachments_md5[f] = {revpos:revpos + 1, md5:md5};
            }
            pending_files -= 1
            if(pending_files === 0){
              pending_dirs -= 1;
              if(pending_dirs === 0){
                push(callback);
              }
            }
          })
        })(i)}
      })
    })
    if (!app.doc.__attachments || app.doc.__attachments.length == 0) push(callback);
  }

  app.sync = function (callback) {
    // A few notes.
    //   File change events are stored in an array and bundled up in to one write call.,
    // this reduces the amount of unnecessary processing as we get a lof of change events.
    //   The file descriptors are stored and re-used because it cuts down on the number of bad change events.
    //   And finally, we check the md5 and only push when the document is actually been changed.
    //   A lot of crazy workarounds for the fact that we basically get an event every time someone
    // looks funny at the underlying files and even reading and opening fds to check on the file trigger
    // more events.

    app.push(function () {
      var changes = [];
      console.log('Watching files for changes...')
      app.doc.__attachments.forEach(function (att) {
        var pre = att.root
        var slash = (process.platform === 'win32') ? '\\' : '/';
        if (pre[pre.length - 1] !== slash) pre += slash;
        watch.createMonitor(att.root, {ignoreDotFiles:true}, function (monitor) {
          monitor.on("removed", function (f, stat) {
            f = f.replace(pre, '');
            changes.push([null, f]);
          })
          monitor.on("created", function (f, stat) {
            changes.push([f, f.replace(pre, ''), stat]);
          })
          monitor.on("changed", function (f, curr, prev) {
            changes.push([f, f.replace(pre, ''), curr]);
          })
        })
      })
      var check = function () {
        var pending = 0
          , revpos = parseInt(app.doc._rev.slice(0,app.doc._rev.indexOf('-')))
          , dirty = false
          ;
        if (changes.length > 0) {
          changes.forEach(function (change) {
            if (!change[0]) {
              delete app.doc._attachments[change[1]];
              dirty = true;
              console.log("Removed "+change[1]);
            } else {
              pending += 1

              fs.readFile(change[0], function (err, data) {
                var f = change[1]
                  , d = data.toString('base64')
                  , md5 = crypto.createHash('md5')
                  , mime = mimetypes.lookup(path.extname(f).slice(1))
                  ;

                md5.update(d)
                md5 = md5.digest('hex')
                pending -= 1
                if (!app.doc.attachments_md5[f] || (md5 !== app.doc.attachments_md5[f].md5) ) {
                  app.doc._attachments[f] = {data:d, content_type:mime};
                  app.doc.attachments_md5[f] = {revpos:revpos + 1, md5:md5};
                  dirty = true;
                  console.log("Changed "+change[0]);
                }
                if (pending == 0 && dirty) push(function () {dirty = false; setTimeout(check, 50)})
                else if (pending == 0 && !dirty) setTimeout(check, 50)

              })
            }

          })
          changes = []
          if (pending == 0 && dirty) push(function () {dirty = false; setTimeout(check, 50)})
          else if (pending == 0 && !dirty) setTimeout(check, 50)
        } else {
          setTimeout(check, 50);
        }
      }
      setTimeout(check, 50)
    })
  }
  var _id = doc.app ? doc.app._id : doc._id

  if (url.slice(url.length - _id.length) !== _id) url += '/' + _id;

  request({uri:url, headers:h}, function (err, resp, body) {
    if (err) throw err;
    if (resp.statusCode == 404) app.current = {};
    else if (resp.statusCode !== 200) throw new Error("Failed to get doc\n"+body)
    else app.current = JSON.parse(body)
    cb(app)
  })
}

exports.createApp = createApp
exports.loadAttachments = loadAttachments
exports.bin = require('./bin')
exports.loadFiles = loadFiles
<commit_msg>Don't play the horn on push<commit_after>var path = require('path')
  , fs = require('fs')
  , watch = require('watch')
  , request = require('request')
  , crypto = require('crypto')
  , mimetypes = require('./mimetypes')
  , spawn = require('child_process').spawn
  ;

var h = {'content-type':'application/json', 'accept-type':'application/json'}

/**
 * Recursively load directory contents into ddoc
 *
 * It's really convenient to see the main couchapp code in single file,
 * rather than mapped into little files in lots of directories like
 * the python couchapp. But there are definitely cases where we might want
 * to use some module or another on the server side. This addition
 * loads file contents from a given directory (recursively) into a js
 * object that can be added to a design document and require()'d in
 * lists, shows, etc.
 *
 * Use couchapp.loadFiles() in app.js like this:
 *
 *    ddoc = {
 *        _id: '_design/app'
 *      , views: {}
 *      , ...
 *      , lib: couchapp.loadFiles('./lib')
 *      , vendor: couchapp.loadFiles('./vendor')
 *    }
 *
 * Optionally, pass in operators to process file contents. For example,
 * generate mustache templates from jade templates.
 *
 * In yourapp/templates/index.jade
 *
 * !!!5
 * html
 *   head
 *     //- jade locals.title
 *     title!= title
 *   body
 *     .item
 *       //- mustache variable for server-side rendering
 *       h1 {{ heading }}
 *
 * in yourapp/app.js
 * var couchapp = require('couchapp')
 *   , jade = require('jade')
 *   , options = {
 *       , operators: [
 *           function renderJade (content, options) {
 *             var compiler = jade.compile(content);
 *             return compiler(options.locals || {});
 *           }
 *         ]
 *       , locals: { title: 'Now we\'re cookin with gas!' }
 *   };
 *
 * ddoc = { ... };
 *
 * ddoc.templates = loadFiles(dir, options);
 */

function loadFiles(dir, options) {
  var listings = fs.readdirSync(dir)
    , options = options || {}
    , obj = {};

  listings.forEach(function (listing) {
    var file = path.join(dir, listing)
      , prop = listing.split('.')[0] // probably want regexp or something more robust
      , stat = fs.statSync(file);

      if (stat.isFile()) {
        var content = fs.readFileSync(file).toString();
        if (options.operators) {
          options.operators.forEach(function (op) {
            content = op(content, options);
          });
        }
        obj[prop] = content;
      } else if (stat.isDirectory()) {
        obj[listing] = loadFiles(file, options);
      }
  });

  return obj;
}

/**
 * End of patch (also see exports and end of file)
 */

function loadAttachments (doc, root, prefix) {
  doc.__attachments = doc.__attachments || []
  try {
    fs.statSync(root)
  } catch(e) {
    throw e
    throw new Error("Cannot stat file "+root)
  }
  doc.__attachments.push({root:root, prefix:prefix});
}

function copy (obj) {
  var n = {}
  for (i in obj) n[i] = obj[i];
  return n
}

function createApp (doc, url, cb) {
  var app = {doc:doc}

  app.fds = {};

  app.prepare = function () {
    var p = function (x) {
      for (i in x) {
        if (i[0] != '_') {
          if (typeof x[i] == 'function') {
            x[i] = x[i].toString()
            x[i] = 'function '+x[i].slice(x[i].indexOf('('))
          }
          if (typeof x[i] == 'object') {
            p(x[i])
          }
        }
      }
    }
    p(app.doc);
    app.doc.__attachments = app.doc.__attachments || []
    app.doc.attachments_md5 = app.doc.attachments_md5 || {}
    app.doc._attachments = app.doc._attachments || {}
  }

  var push = function (callback) {
    console.log('Serializing.')
    var doc = copy(app.doc);
    doc._attachments = copy(app.doc._attachments)
    delete doc.__attachments;
    var body = JSON.stringify(doc)
    console.log('PUT '+url.replace(/^(https?:\/\/[^@:]+):[^@]+@/, '$1:******@'))
    request({uri:url, method:'PUT', body:body, headers:h}, function (err, resp, body) {
      if (err) throw err;
      if (resp.statusCode !== 201) {
        throw new Error("Could not push document\nCode: " + resp.statusCode + "\n"+body);
      }
      app.doc._rev = JSON.parse(body).rev
      console.log('Finished push. '+app.doc._rev)
      request({uri:url, headers:h}, function (err, resp, body) {
        body = JSON.parse(body);
        app.doc._attachments = body._attachments;
        if (callback) callback()
      })
    })
  }

  app.push = function (callback) {
    var revpos
      , pending_dirs = 0
      ;

    console.log('Preparing.')
    var doc = app.current;
    for (i in app.doc) {
      if (i !== '_rev') doc[i] = app.doc[i]
    }
    app.doc = doc;
    app.prepare();
    revpos = app.doc._rev ? parseInt(app.doc._rev.slice(0,app.doc._rev.indexOf('-'))) : 0;

    var coffeeCompile;
    var coffeeExt;
    try{
      coffeeCompile = require('coffee-script');
      coffeeExt = /\.(lit)?coffee$/;
    } catch(e){}

    app.doc.__attachments.forEach(function (att) {
      watch.walk(att.root, {ignoreDotFiles:true}, function (err, files) {
        pending_dirs += 1;
        var pending_files = Object.keys(files).length;
        for (i in files) { (function (f) {
          fs.readFile(f, function (err, data) {
            if(f.match(coffeeExt)){
              data = new Buffer( coffeeCompile.compile(data.toString()) );
              f = f.replace(coffeeExt,'.js');
            }
            f = f.replace(att.root, att.prefix || '').replace(/\\/g,"/");
            if (f[0] == '/') f = f.slice(1)
            if (!err) {
              var d = data.toString('base64')
                , md5 = crypto.createHash('md5')
                , mime = mimetypes.lookup(path.extname(f).slice(1))
                ;
              md5.update(d)
              md5 = md5.digest('hex')
              if (app.doc.attachments_md5[f] && app.doc._attachments[f]) {
                if (app.doc._attachments[f].revpos === app.doc.attachments_md5[f].revpos &&
                    app.doc.attachments_md5[f].md5 === md5) {
                  pending_files -= 1;
                  if(pending_files === 0){
                    pending_dirs -= 1;
                    if(pending_dirs === 0){
                      push(callback);
                    }
                  }
                  return; // Does not need to be updated.
                }
              }
              app.doc._attachments[f] = {data:d, content_type:mime};
              app.doc.attachments_md5[f] = {revpos:revpos + 1, md5:md5};
            }
            pending_files -= 1
            if(pending_files === 0){
              pending_dirs -= 1;
              if(pending_dirs === 0){
                push(callback);
              }
            }
          })
        })(i)}
      })
    })
    if (!app.doc.__attachments || app.doc.__attachments.length == 0) push(callback);
  }

  app.sync = function (callback) {
    // A few notes.
    //   File change events are stored in an array and bundled up in to one write call.,
    // this reduces the amount of unnecessary processing as we get a lof of change events.
    //   The file descriptors are stored and re-used because it cuts down on the number of bad change events.
    //   And finally, we check the md5 and only push when the document is actually been changed.
    //   A lot of crazy workarounds for the fact that we basically get an event every time someone
    // looks funny at the underlying files and even reading and opening fds to check on the file trigger
    // more events.

    app.push(function () {
      var changes = [];
      console.log('Watching files for changes...')
      app.doc.__attachments.forEach(function (att) {
        var pre = att.root
        var slash = (process.platform === 'win32') ? '\\' : '/';
        if (pre[pre.length - 1] !== slash) pre += slash;
        watch.createMonitor(att.root, {ignoreDotFiles:true}, function (monitor) {
          monitor.on("removed", function (f, stat) {
            f = f.replace(pre, '');
            changes.push([null, f]);
          })
          monitor.on("created", function (f, stat) {
            changes.push([f, f.replace(pre, ''), stat]);
          })
          monitor.on("changed", function (f, curr, prev) {
            changes.push([f, f.replace(pre, ''), curr]);
          })
        })
      })
      var check = function () {
        var pending = 0
          , revpos = parseInt(app.doc._rev.slice(0,app.doc._rev.indexOf('-')))
          , dirty = false
          ;
        if (changes.length > 0) {
          changes.forEach(function (change) {
            if (!change[0]) {
              delete app.doc._attachments[change[1]];
              dirty = true;
              console.log("Removed "+change[1]);
            } else {
              pending += 1

              fs.readFile(change[0], function (err, data) {
                var f = change[1]
                  , d = data.toString('base64')
                  , md5 = crypto.createHash('md5')
                  , mime = mimetypes.lookup(path.extname(f).slice(1))
                  ;

                md5.update(d)
                md5 = md5.digest('hex')
                pending -= 1
                if (!app.doc.attachments_md5[f] || (md5 !== app.doc.attachments_md5[f].md5) ) {
                  app.doc._attachments[f] = {data:d, content_type:mime};
                  app.doc.attachments_md5[f] = {revpos:revpos + 1, md5:md5};
                  dirty = true;
                  console.log("Changed "+change[0]);
                }
                if (pending == 0 && dirty) push(function () {dirty = false; setTimeout(check, 50)})
                else if (pending == 0 && !dirty) setTimeout(check, 50)

              })
            }

          })
          changes = []
          if (pending == 0 && dirty) push(function () {dirty = false; setTimeout(check, 50)})
          else if (pending == 0 && !dirty) setTimeout(check, 50)
        } else {
          setTimeout(check, 50);
        }
      }
      setTimeout(check, 50)
    })
  }
  var _id = doc.app ? doc.app._id : doc._id

  if (url.slice(url.length - _id.length) !== _id) url += '/' + _id;

  request({uri:url, headers:h}, function (err, resp, body) {
    if (err) throw err;
    if (resp.statusCode == 404) app.current = {};
    else if (resp.statusCode !== 200) throw new Error("Failed to get doc\n"+body)
    else app.current = JSON.parse(body)
    cb(app)
  })
}

exports.createApp = createApp
exports.loadAttachments = loadAttachments
exports.bin = require('./bin')
exports.loadFiles = loadFiles
<|endoftext|>


<commit_before>define(["dojo/_base/kernel",
	"dojo/_base/lang",
	"dojo/_base/declare",
	"dojo/ready",
	"dojo/_base/window",
	"dojo/dom-construct",
	"dijit",
	"dojox",
	"dojo/cache",
	"dojo/fx",
	"dojox/json/ref",
	"dojo/parser",
	"./scene",
	"dojox/mobile/transition",
	"dojo/on"],
	function(dojo,lang,declare,ready,baseWindow,dom,dijit,dijox,cache,fx,jsonRef,parser,sceneCtor,transition,listen){
	var Application = declare([sceneCtor], {
		constructor: function(params){
			this.scenes={};
			if(params.stores){
			    //create stores in the configuration.
			    for (var item in params.stores){
			        if(item.charAt(0)!=="_"){//skip the private properties
			            var type = params.stores[item].type? params.stores[item].type : "dojo.store.Memory";
			            var config = {};
			            if(params.stores[item].params){
			                dojo.mixin(config, params.stores[item].params);
			            }
			            var storeCtor = dojo.getObject(type);
			            if(config.data && lang.isString(config.data)){
			                //get the object specified by string value of data property
			                //cannot assign object literal or reference to data property
			                //because json.ref will generate __parent to point to its parent
			                //and will cause infinitive loop when creating StatefulModel.
			                config.data = dojo.getObject(config.data);
			            }
			            params.stores[item].store = new storeCtor(config);
			        }
			    }
			}

		},
		templateString: "

",
		selectedChild: null,
		baseClass: "application mblView",
		defaultViewType: sceneCtor,
		buildRendering: function(){
			if (this.srcNodeRef===baseWindow.body()){
				this.srcNodeRef = dom.create("DIV",{},baseWindow.body());
			}
			this.inherited(arguments);
		}
	});

	function generateApp(config,node,appSchema,validate){

		//console.log("config.modules: ", config.modules);
		var modules = config.modules.concat(config.dependencies);

		if (config.template){
			//console.log("config.template: ", config.template);
			modules.push("dojo/text!" + "app/" + config.template);
		}
		//console.log("modules: ", modules);

		require(modules, function(){
			var modules=[Application];
			for(var i=0;i<config.modules.length;i++){
				modules.push(arguments[i]);
			}

			if (config.template){
				var ext = {
					templateString: arguments[arguments.length-1]
				}
			}
			App = declare(modules,ext);

			ready(function(){
				app = App(config,node || baseWindow.body());
				app.startup();
			});
		});
	}

	return function(config,node){
		if (!config){
			throw Error("App Config Missing");
		}

		if (config.validate){
			require(["dojox/json/schema","dojox/json/ref","dojo/text!dojox/application/schema/application.json"],function(schema,appSchema){
				schema = dojox.json.ref.resolveJson(schema);
				if (schema.validate(config,appSchema)){
					generateApp(config,node);
				}
			});

		}else{
			generateApp(config,node);
		}
	}
});
<commit_msg>add dojox.app as experimental<commit_after>define(["dojo/_base/kernel",
	"dojo/_base/lang",
	"dojo/_base/declare",
	"dojo/ready",
	"dojo/_base/window",
	"dojo/dom-construct",
	"dijit",
	"dojox",
	"dojo/cache",
	"dojo/fx",
	"dojox/json/ref",
	"dojo/parser",
	"./scene",
	"dojox/mobile/transition",
	"dojo/on"],
	function(dojo,lang,declare,ready,baseWindow,dom,dijit,dijox,cache,fx,jsonRef,parser,sceneCtor,transition,listen){
        dojo.experimental("dojox.app");
	var Application = declare([sceneCtor], {
		constructor: function(params){
			this.scenes={};
			if(params.stores){
			    //create stores in the configuration.
			    for (var item in params.stores){
			        if(item.charAt(0)!=="_"){//skip the private properties
			            var type = params.stores[item].type? params.stores[item].type : "dojo.store.Memory";
			            var config = {};
			            if(params.stores[item].params){
			                dojo.mixin(config, params.stores[item].params);
			            }
			            var storeCtor = dojo.getObject(type);
			            if(config.data && lang.isString(config.data)){
			                //get the object specified by string value of data property
			                //cannot assign object literal or reference to data property
			                //because json.ref will generate __parent to point to its parent
			                //and will cause infinitive loop when creating StatefulModel.
			                config.data = dojo.getObject(config.data);
			            }
			            params.stores[item].store = new storeCtor(config);
			        }
			    }
			}

		},
		templateString: "

",
		selectedChild: null,
		baseClass: "application mblView",
		defaultViewType: sceneCtor,
		buildRendering: function(){
			if (this.srcNodeRef===baseWindow.body()){
				this.srcNodeRef = dom.create("DIV",{},baseWindow.body());
			}
			this.inherited(arguments);
		}
	});

	function generateApp(config,node,appSchema,validate){

		//console.log("config.modules: ", config.modules);
		var modules = config.modules.concat(config.dependencies);

		if (config.template){
			//console.log("config.template: ", config.template);
			modules.push("dojo/text!" + "app/" + config.template);
		}
		//console.log("modules: ", modules);

		require(modules, function(){
			var modules=[Application];
			for(var i=0;i<config.modules.length;i++){
				modules.push(arguments[i]);
			}

			if (config.template){
				var ext = {
					templateString: arguments[arguments.length-1]
				}
			}
			App = declare(modules,ext);

			ready(function(){
				app = App(config,node || baseWindow.body());
				app.startup();
			});
		});
	}

	return function(config,node){
		if (!config){
			throw Error("App Config Missing");
		}

		if (config.validate){
			require(["dojox/json/schema","dojox/json/ref","dojo/text!dojox/application/schema/application.json"],function(schema,appSchema){
				schema = dojox.json.ref.resolveJson(schema);
				if (schema.validate(config,appSchema)){
					generateApp(config,node);
				}
			});

		}else{
			generateApp(config,node);
		}
	}
});
<|endoftext|>


<commit_before>var Service, Characteristic;

const Co2monitor = require('co2-monitor');
let co2Monitor = new Co2Monitor();

module.exports = function(homebridge) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  homebridge.registerAccessory("homebridge-aircontrol-mini", "aircontrol-mini", CO2Accessory);
}

function CO2Accessory(log, config) {
  var that = this;

  this.log = log;
  this.name = config["name"];

  // Set up CO2
  this.co2monitor = co2Monitor;
  this.co2service = new Service.CarbonDioxideSensor(this.name);

  this.co2Monitor.on('co2', (co2) => {
      console.log('co2: ' + co2);
	  	that.co2 = co2;
  });

  this.co2service
    .getCharacteristic(Characteristic.CarbonDioxideLevel)
    .on('get', this.getLevel.bind(this));

  this.co2service
    .getCharacteristic(Characteristic.CarbonDioxideDetected)
    .on('get', this.getDetected.bind(this));

  // Set up Temperature Service
	this.temperatureService = new Service.TemperatureSensor(this.name);

  this.co2Monitor.on('temp', (temp) => {
      console.log('temp (C): ' + temp);
	  	that.temperature = temp;
  });

	this.temperatureService
		.getCharacteristic(Characteristic.CurrentTemperature)
	.on('get', this.getCurrentTemperature.bind(this));

	// Connection
	this.co2Monitor.on('connected', (device) => {
	    co2Monitor.startTransfer();
	});

	this.co2Monitor.connect();
}

CO2Accessory.prototype.getLevel = function(callback) {
    this.log(this.name, " - CO2 : ", this.co2);
    callback(null, this.co2);
}

CO2Accessory.prototype.getDetected = function(callback) {
    var result = (this.co2 > 1000 ? Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL : Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL);
    callback(null, result);
}

CO2Accessory.prototype.getCurrentTemperature = function(callback) {
    this.log(this.name, " - Temperature (C) : ", this.temperature);
    callback(null, result);
}

CO2Accessory.prototype.getServices = function() {
  return [this.co2service, this.temperatureService];
}
<commit_msg>Parse actual data<commit_after>var Service, Characteristic;

const Co2Monitor = require('co2-monitor');
let co2Monitor = new Co2Monitor();

module.exports = function(homebridge) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  homebridge.registerAccessory("homebridge-aircontrol-mini", "aircontrol-mini", CO2Accessory);
}

function CO2Accessory(log, config) {
  var that = this;

  this.log = log;
  this.name = config["name"];

  // Set up CO2
	let monitor = co2Monitor;
  this.co2monitor = monitor;
  this.co2service = new Service.CarbonDioxideSensor(this.name);

  this.co2monitor.on('co2', (co2) => {
			if (that.co2 == null || that.co2 == undefined) {
			 	 that.log(that.name, "Recieved first CO2 value at ", co2);
				 that.co2_peak = co2;
			}	else if (co2 > that.co2_peak) {
				 that.co2_peak = co2;
			}
	  	that.co2 = co2;
  });

	this.informationService = new Service.AccessoryInformation();
  this.informationService.setCharacteristic(Characteristic.Manufacturer, "TFA-Dostmann");
  this.informationService.setCharacteristic(Characteristic.Model, "AirControl Mini")

  this.co2service
    .getCharacteristic(Characteristic.CarbonDioxideLevel)
    .on('get', this.getLevel.bind(this));

  this.co2service
    .getCharacteristic(Characteristic.CarbonDioxideDetected)
    .on('get', this.getDetected.bind(this));

	this.co2service
		.getCharacteristic(Characteristic.CarbonDioxidePeakLevel)
		.on('get', this.getPeakLevel.bind(this));

  // Set up Temperature Service
	this.temperatureService = new Service.TemperatureSensor(this.name);

  this.co2monitor.on('temp', (temp) => {
			if (that.temperature == null || that.temperature == undefined) {
					that.log(that.name, "Recieved first temperature value at ", temp);
			}
	  	that.temperature = temp;
  });

	this.temperatureService
		.getCharacteristic(Characteristic.CurrentTemperature)
	.on('get', this.getCurrentTemperature.bind(this));

	// Connection
	this.co2monitor.on('connected', (device) => {
	    monitor.startTransfer();
			that.log(that.name, "Connected, recieving data…");
	});

	this.co2monitor.connect();
}

CO2Accessory.prototype.getLevel = function(callback) {
	if (this.co2 == null || this.co2 == undefined) {
				callback(null, null);
				return;
		}
    callback(null, this.co2);
}

CO2Accessory.prototype.getPeakLevel = function(callback) {
	if (this.co2_peak == null || this.co2_peak == undefined) {
				callback(null, null);
				return;
		}
    callback(null, this.co2_peak);
}

CO2Accessory.prototype.getDetected = function(callback) {

	if (this.co2 == null || this.co2 == undefined) {
				callback(null, null);
				return;
		}
		var result = (this.co2 > 1000 ? Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL : Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL);
    callback(null, result);
}

CO2Accessory.prototype.getCurrentTemperature = function(callback) {
	if (this.temperature == null || this.temperature == undefined) {
			callback(null, null);
			return;
	}
    callback(null, new Number(this.temperature));
}

CO2Accessory.prototype.getServices = function() {
  return [this.co2service, this.temperatureService, this.informationService];
}
<|endoftext|>


<commit_before>var WIDTH = document.body.clientWidth, HEIGHT = document.body.clientHeight;

var scene = new THREE.Scene(),
    camera = new THREE.PerspectiveCamera(75, WIDTH / HEIGHT, 0.1, 1000),
    renderer = new THREE.WebGLRenderer({ alpha: true });

document.body.appendChild(renderer.domElement);
renderer.setSize(WIDTH, HEIGHT);

light = new THREE.PointLight(0xffffff, 1, 100);
scene.add(light);

var geometry = new THREE.BoxGeometry(10, 10, 10);
var north = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0xff0000}));
var south = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0x00ff00}));
var east  = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0x0000ff}));
var west  = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0xffff00}));

north.position.set(0, 0, -50);
south.position.set(0, 0,  50);

east.position.set( 50, 0, 0);
west.position.set(-50, 0, 0);

scene.add(north);
scene.add(east);
scene.add(south);
scene.add(west);

window.addEventListener("deviceorientation", function(e) {
  var heading = e.alpha,
      pitch   = e.gamma;

  // Correcting the sensors being "clever"
  if(Math.abs(e.beta) > 45) {
    heading += 90;
  } else {
    heading -= 90;
  }

  if(pitch < 0) {
    pitch = -90 - pitch;
  } else {
    pitch =  90 - pitch;
  }

  if(heading < 0) heading = 360 + heading;

  camera.rotation.set(deg2rad(pitch), deg2rad(heading), 0);
});

function deg2rad(angle) {
  return (angle / 180.0) * Math.PI;
}

var canvas = document.getElementById("camera"),
    video  = document.querySelector("video");

canvas.width = WIDTH;
canvas.height = HEIGHT;

var ctx = canvas.getContext("2d");

function draw() {
  ctx.fillStyle = "#ff00ff";
  ctx.fillRect(0,0,WIDTH,HEIGHT);
  ctx.drawImage(video, 0, 0, WIDTH, HEIGHT);

  north.rotation.y += 0.05;
  south.rotation.y += 0.05;

  east.rotation.y += 0.05;
  west.rotation.y += 0.05;

  renderer.render(scene, camera);
  requestAnimationFrame(draw);
}

navigator.getMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

MediaStreamTrack.getSources(function(mediaSources) {
  mediaSources.forEach(function(mediaSource){
    if (mediaSource.kind === 'video' && mediaSource.facing == "environment") {
      console.log("media source found...")
      showWebcamVideo(mediaSource.id);
    }
  });
});

function showWebcamVideo(sourceId) {
  console.log("About to start video...");
  navigator.getMedia({
    video: {
      optional: [{sourceId: sourceId}]
    }
  }, function onSuccess(stream) {
    console.log("Starting webcam video");
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(stream);
  }, function onError(err) {
    alert("Whoops: " + err);
    console.error(err);
  });
}

draw();
<commit_msg>Disabling pitch for now<commit_after>var WIDTH = document.body.clientWidth, HEIGHT = document.body.clientHeight;

var scene = new THREE.Scene(),
    camera = new THREE.PerspectiveCamera(75, WIDTH / HEIGHT, 0.1, 1000),
    renderer = new THREE.WebGLRenderer({ alpha: true });

document.body.appendChild(renderer.domElement);
renderer.setSize(WIDTH, HEIGHT);

light = new THREE.PointLight(0xffffff, 1, 100);
scene.add(light);

var geometry = new THREE.BoxGeometry(10, 10, 10);
var north = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0xff0000}));
var south = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0x00ff00}));
var east  = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0x0000ff}));
var west  = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({color: 0xffff00}));

north.position.set(0, 0, -50);
south.position.set(0, 0,  50);

east.position.set( 50, 0, 0);
west.position.set(-50, 0, 0);

scene.add(north);
scene.add(east);
scene.add(south);
scene.add(west);

window.addEventListener("deviceorientation", function(e) {
  var heading = e.alpha,
      pitch   = e.gamma;

  // Correcting the sensors being "clever"
  if(Math.abs(e.beta) > 45) {
    heading += 90;
  } else {
    heading -= 90;
  }

  if(pitch < 0) {
    pitch = -90 - pitch;
  } else {
    pitch =  90 - pitch;
  }

  if(heading < 0) heading = 360 + heading;

  camera.rotation.set(0, deg2rad(heading), 0);
});

function deg2rad(angle) {
  return (angle / 180.0) * Math.PI;
}

var canvas = document.getElementById("camera"),
    video  = document.querySelector("video");

canvas.width = WIDTH;
canvas.height = HEIGHT;

var ctx = canvas.getContext("2d");

function draw() {
  ctx.fillStyle = "#ff00ff";
  ctx.fillRect(0,0,WIDTH,HEIGHT);
  ctx.drawImage(video, 0, 0, WIDTH, HEIGHT);

  north.rotation.y += 0.05;
  south.rotation.y += 0.05;

  east.rotation.y += 0.05;
  west.rotation.y += 0.05;

  renderer.render(scene, camera);
  requestAnimationFrame(draw);
}

navigator.getMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

MediaStreamTrack.getSources(function(mediaSources) {
  mediaSources.forEach(function(mediaSource){
    if (mediaSource.kind === 'video' && mediaSource.facing == "environment") {
      console.log("media source found...")
      showWebcamVideo(mediaSource.id);
    }
  });
});

function showWebcamVideo(sourceId) {
  console.log("About to start video...");
  navigator.getMedia({
    video: {
      optional: [{sourceId: sourceId}]
    }
  }, function onSuccess(stream) {
    console.log("Starting webcam video");
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(stream);
  }, function onError(err) {
    alert("Whoops: " + err);
    console.error(err);
  });
}

draw();
<|endoftext|>


<commit_before>var async = require("async"),
    FeedParser = require('feedparser')
    request = require('request'),
    fs = require('fs');

var episodes = [ ];

var req = request('http://www.radiolab.org/feeds/podcast/'),
    feedparser = new FeedParser();

req.on('response', function (res) {
  var stream = this;
  if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));
  stream.pipe(feedparser);
});

feedparser.on('readable', function() {
  var stream = this
    , meta = this.meta // **NOTE** the "meta" is always available in the context of the feedparser instance
    , item;
  while (item = stream.read()) {
    episodes.push(item);
  }
});

feedparser.on('finish', function() {
    episodes.forEach(function (e) { e.pubdate = new Date(e.pubdate); });
    episodes.sort(function (a, b) { return a.pubdate - b.pubdate; });
    async.eachSeries(episodes, function (episode, callback) {
        var url = episode["feedburner:origenclosurelink"]["#"],
            filename = function () {
                var d = episode.pubdate;
                return d.getFullYear() +
                    ("0" + (d.getMonth() + 1)).slice(-2) +
                    ("0" + d.getDate()).slice(-2) +
                    url.match(/(\w+)(\.\w+)+(?!.*(\w+)(\.\w+)+)/)[2];
                }(),
            file = fs.createWriteStream("downloads/" + filename);
        console.log("Attempting download " + url + " to " + filename + "...");
        request
            .get(url)
            .on('error', function(err) {
                console.log(err)
            })
            .on("end", callback)
            .pipe(file);
    }, function (err) {
        if (err) console.log(err);
    });
});
<commit_msg>Now does not overwrite existing files<commit_after>var async = require("async"),
    FeedParser = require('feedparser')
    request = require('request'),
    fs = require('fs');

var episodes = [ ];

var req = request('http://www.radiolab.org/feeds/podcast/'),
    feedparser = new FeedParser();

req.on('response', function (res) {
  var stream = this;
  if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));
  stream.pipe(feedparser);
});

feedparser.on('readable', function() {
  var stream = this
    , meta = this.meta // **NOTE** the "meta" is always available in the context of the feedparser instance
    , item;
  while (item = stream.read()) {
    episodes.push(item);
  }
});

feedparser.on('finish', function() {
    episodes.forEach(function (e) { e.pubdate = new Date(e.pubdate); });
    episodes.sort(function (a, b) { return a.pubdate - b.pubdate; });
    async.eachSeries(episodes, function (episode, callback) {
        var url = episode["feedburner:origenclosurelink"]["#"],
            filename = function () {
                var d = episode.pubdate;
                return "downloads/" +
                    d.getFullYear() +
                    ("0" + (d.getMonth() + 1)).slice(-2) +
                    ("0" + d.getDate()).slice(-2) +
                    url.match(/(\w+)(\.\w+)+(?!.*(\w+)(\.\w+)+)/)[2];
                }();
        fs.stat(filename, function (err, stat) {
            if (!err) return callback(null);
            var file = fs.createWriteStream(filename);
            console.log("Downloading " + url + " to " + filename + "...");
            request
                .get(url)
                .on('error', function(err) {
                    console.log(err)
                })
                .on("end", callback)
                .pipe(file);
        });
    }, function (err) {
        if (err) console.log(err);
    });
});
<|endoftext|>