<commit_before>$(function() {
  var lat, lon, map;

  /*******************
  LOCATION AND MAPPING
  *******************/

  // Use HTML5 GeoLocation to get lat/long
  var getLocation = function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(getAddress);
    } else {
      updateLocationField('Geolocation not supported...');
    }
  };

  // Use GoogleMaps API to get nearest address for lat/long
  var getAddress = function(position) {
    lat =position.coords.latitude;
    lon =position.coords.longitude;

    initLeafletMap(lat, lon);

    var maps_url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lon +"&sensor=true";

    $.get(maps_url, function(data) {
      var parts   = data.results[0].address_components.slice(0,4);

      var address = "";
      $.each(parts, function(index, value) {
        if (index === 0) {
          address += value.short_name;
        } else {
          address += ", " + value.short_name;
        }
      });

      updateLocationField(address);
    })
    .fail(function() {
      updateLocationField('Cannot get location...');
    });
  };

  // Update 'location' field in UI
  var updateLocationField = function(text) {
    $('#location').html('
' + text + '
');
  };

  // Create Leaflet Map centered at user's location
  var initLeafletMap = function(lat, lon) {
    map = L.map('map', {scrollWheelZoom: false}).setView([lat, lon], 14);

    L.mapbox.tileLayer('alexnorton.h2hfjmmo', {detectRetina: true}).addTo(map);

    L.marker([lat, lon], {
      bounceOnAdd: true
    }).addTo(map);

    $('#map_btn').show();
    $('#map').css('border-style', 'solid');

    addPredictionCard();
  };

  var initFSMap = function(markers) {
    var fs_map = L.map('fs_map', {scrollWheelZoom: false}).setView([lat, lon], 14);
    L.mapbox.tileLayer('alexnorton.h2hfjmmo', {detectRetina: true}).addTo(fs_map);

    var colors = ['red', 'darkred', 'orange', 'green', 'darkgreen', 'blue', 'purple', 'darkpuple', 'cadetblue'];

    var icon_lookup = {
      'Pub': 'beer',
      'Plaza': 'leaf',
      'Café': 'coffee',
      'Fast Food': 'cutlery',
      'Grocery Store': 'shopping-cart',
      'Performing Arts': 'pencil',
      'Theater': 'smile-o'
    }

    $.each(markers, function(index, value) {
      var color = colors[Math.floor(Math.random() * colors.length)];

      var redMarker = L.AwesomeMarkers.icon({
        icon: icon_lookup[value.icon],
        prefix: 'fa',
        markerColor: color
      });

      var marker = L.marker(value.points, {icon: redMarker}, {
        bounceOnAdd: true
      }).addTo(fs_map);
      marker.bindPopup(value.text);
    });
  };

  getLocation();

  /***********
  ADDING CARDS
  ***********/

  var renderCards = function() {
    addTrafficCard();
    addWeatherCard();
    addFourSquareCard();
    addRoadWorksCard();
  };

  var addNewCard = function(html) {
    $('div[id=card]').last().after(html);
  };

  var addFourSquareCard = function() {
    var url = '/foursquare.json?lat=' + lat + '&long=' + lon

    $.getJSON(url, function(data) {
      var places = data.response.groups[0].items;
      var content = '

Places of interest nearby

'

      var markers = [];

      for(var i = 0; i < 5; i++) {
        var url = 'https://foursquare.com/v/' + places[i].venue.id
        content += '
' + places[i].venue.name + ' (' + places[i].venue.location.distance + 'm)
';

        var points = [places[i].venue.location.lat, places[i].venue.location.lng];
        markers.push({
          'points': points,
          'text' : places[i].venue.name,
          'icon': places[i].venue.categories[0].shortName
        })
      }

      content += '
Places Nearby
';

      content += '

';

      addNewCard(content);
      initFSMap(markers);
    });
  };

  var addTrafficCard = function() {
    var url = '/journey_times/nerarby_routes?lat=' + lat + '&long=' + lon + '&radius=10'
    $.getJSON(url, function(data) {
      var content = '

' + data.length + ' traffic reports nearby

'

      if(data[0] && data[0] > 0) {
          addMusicCard(data[0].ratio);
      } else {
          addMusicCard(1);
      }

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

        if(data[i].severity == "clear") {
          border_colour = "rgb(26, 140, 216)";
        }
        else if(data[i].severity == "normal") {
          border_colour = "rgb(50, 162, 35)";
        }
        else if(data[i].severity == "moderate") {
          border_colour = "rgb(248, 186, 55)";
        }
        else if(data[i].severity == "severe") {
          border_colour = "rgb(241, 40, 12)";
        }

        content += '
' + data[i].description + '  (' + data[i].difference + 's)
';
      };

      content += '
Traffic

';

      addNewCard(content);
    });
  };

  var addWeatherCard = function() {
    var url = 'weather/nearby_weather?lat=' + lat + '&long=' + lon
    $.getJSON(url, function(data) {
      var content = '

Local weather

'

      content += '
Now: ' + data.current_summary + ' - ' + data.current_temp + '°C, feels like ' + data.currently_feels_like + '°C
';
      content += '
Later: ' + data.next_summary + ' - ' + data.next_temp + '°C
';

      content += '
Weather

';

      addNewCard(content);
    });
  };

  var addRoadWorksCard = function() {
    var url = '/roadworks/neraby_roadworks?lat=' + lat + '&long=' + lon + '&radius=10'
    $.getJSON(url, function(data) {
      var content = '

' + data.length + ' road works nearby

'
      var border_colour;

      for(var i = 0; i < data.length; i++) {
        if(data[i].impact == "freeFlow") {
          border_colour = "rgb(50, 162, 35)";
        }
        else if(data[i].impact == "heavy") {
          border_colour = "rgb(248, 186, 55)";
        }
        else if(data[i].impact == "impossible") {
          border_colour = "rgb(241, 40, 12)";
        }

        var parts = data[i].comment.split('.');
        content += '
' + parts[0] + '
';
      };

      content += '
Road Works

';

      addNewCard(content);
    });
  };

  var addMusicCard = function(severity) {
      var embed = '';

      console.log(severity);
      var value = ((severity - 1) * 5) + 0.5;
      console.log(value);

      $.getJSON('/music/playlist.json', {
          speed: value,
          energy: value,
          danceability: 1
      }, function(data) {

          var content = '

Spotify playlist
';

          if ('songs' in data.response) {
              var tracks = []
              data.response.songs.forEach(function(song) {
                  if(song.tracks.length > 0) {
                      tracks.push(song.tracks[0].foreign_id.replace('spotify-WW:track:', ''));
                  }
              });
              var tembed = embed.replace('TRACKS', tracks.join()).replace('PREFEREDTITLE', 'Playlist');

              content += '
' + tembed + '
';

              $("#results").html(tembed);
          }

          content += 'Music
';

          addNewCard(content);
      });
  };

  var addPredictionCard = function() {
    var url = '/prediction.json?lat=' + lat + '&long=' + lon + '&radius=10'
    $.getJSON(url, function(data) {
      var content = '

' + data.description + '
Travel Prediction

'

      $('#map_wrapper').after(content);

      renderCards();
    });
  };

  /********
  LISTENERS
  ********/

  // Animate expanding the map
  $('#map_btn').click(function() {
    var height = $('#map').height();

    if (height > 170) {
      $('#map').css('height', '170px');
      $('#map_btn_wrapper').css('margin-top', '150px');
      $('#map_btn').addClass('glyphicon-chevron-down');
      $('#map_btn').removeClass('glyphicon-chevron-up');
      map.invalidateSize();
    } else {
      $('#map').css('height', '350px');
      $('#map_btn_wrapper').css('margin-top', '330px');
      $('#map_btn').addClass('glyphicon-chevron-up');
      $('#map_btn').removeClass('glyphicon-chevron-down');
      map.invalidateSize();
    }
  });
});
<commit_msg>Set FourSquare map bounds to fit visible markers<commit_after>$(function() {
  var lat, lon, map;

  /*******************
  LOCATION AND MAPPING
  *******************/

  // Use HTML5 GeoLocation to get lat/long
  var getLocation = function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(getAddress);
    } else {
      updateLocationField('Geolocation not supported...');
    }
  };

  // Use GoogleMaps API to get nearest address for lat/long
  var getAddress = function(position) {
    lat =position.coords.latitude;
    lon =position.coords.longitude;

    initLeafletMap(lat, lon);

    var maps_url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lon +"&sensor=true";

    $.get(maps_url, function(data) {
      var parts   = data.results[0].address_components.slice(0,4);

      var address = "";
      $.each(parts, function(index, value) {
        if (index === 0) {
          address += value.short_name;
        } else {
          address += ", " + value.short_name;
        }
      });

      updateLocationField(address);
    })
    .fail(function() {
      updateLocationField('Cannot get location...');
    });
  };

  // Update 'location' field in UI
  var updateLocationField = function(text) {
    $('#location').html('
' + text + '
');
  };

  // Create Leaflet Map centered at user's location
  var initLeafletMap = function(lat, lon) {
    map = L.map('map', {scrollWheelZoom: false}).setView([lat, lon], 14);

    L.mapbox.tileLayer('alexnorton.h2hfjmmo', {detectRetina: true}).addTo(map);

    L.marker([lat, lon], {
      bounceOnAdd: true
    }).addTo(map);

    $('#map_btn').show();
    $('#map').css('border-style', 'solid');

    addPredictionCard();
  };

  var initFSMap = function(markers) {
    var fs_map = L.map('fs_map', {scrollWheelZoom: false}).setView([lat, lon], 14);
    L.mapbox.tileLayer('alexnorton.h2hfjmmo', {detectRetina: true}).addTo(fs_map);

    var colors = ['red', 'darkred', 'orange', 'green', 'darkgreen', 'blue', 'purple', 'darkpuple', 'cadetblue'];

    var icon_lookup = {
      'Pub': 'beer',
      'Plaza': 'leaf',
      'Café': 'coffee',
      'Fast Food': 'cutlery',
      'Grocery Store': 'shopping-cart',
      'Performing Arts': 'pencil',
      'Theater': 'smile-o'
    }

      var markerLayers = [];

    $.each(markers, function(index, value) {
      var color = colors[Math.floor(Math.random() * colors.length)];

      var redMarker = L.AwesomeMarkers.icon({
        icon: icon_lookup[value.icon],
        prefix: 'fa',
        markerColor: color
      });

      var marker = L.marker(value.points, {icon: redMarker}, {
        bounceOnAdd: true
      });
      marker.bindPopup(value.text);

        markerLayers.push(marker);
      });

      var markerLayerGroup = new L.FeatureGroup(markerLayers);
      markerLayerGroup.addTo(fs_map);
      fs_map.fitBounds(markerLayerGroup.getBounds());
  };

  getLocation();

  /***********
  ADDING CARDS
  ***********/

  var renderCards = function() {
    addTrafficCard();
    addWeatherCard();
    addFourSquareCard();
    addRoadWorksCard();
  };

  var addNewCard = function(html) {
    $('div[id=card]').last().after(html);
  };

  var addFourSquareCard = function() {
    var url = '/foursquare.json?lat=' + lat + '&long=' + lon

    $.getJSON(url, function(data) {
      var places = data.response.groups[0].items;
      var content = '

Places of interest nearby

'

      var markers = [];

      for(var i = 0; i < 5; i++) {
        var url = 'https://foursquare.com/v/' + places[i].venue.id
        content += '
' + places[i].venue.name + ' (' + places[i].venue.location.distance + 'm)
';

        var points = [places[i].venue.location.lat, places[i].venue.location.lng];
        markers.push({
          'points': points,
          'text' : places[i].venue.name,
          'icon': places[i].venue.categories[0].shortName
        })
      }

      content += '
Places Nearby
';

      content += '

';

      addNewCard(content);
      initFSMap(markers);
    });
  };

  var addTrafficCard = function() {
    var url = '/journey_times/nerarby_routes?lat=' + lat + '&long=' + lon + '&radius=10'
    $.getJSON(url, function(data) {
      var content = '

' + data.length + ' traffic reports nearby

'

      if(data[0] && data[0] > 0) {
          addMusicCard(data[0].ratio);
      } else {
          addMusicCard(1);
      }

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

        if(data[i].severity == "clear") {
          border_colour = "rgb(26, 140, 216)";
        }
        else if(data[i].severity == "normal") {
          border_colour = "rgb(50, 162, 35)";
        }
        else if(data[i].severity == "moderate") {
          border_colour = "rgb(248, 186, 55)";
        }
        else if(data[i].severity == "severe") {
          border_colour = "rgb(241, 40, 12)";
        }

        content += '
' + data[i].description + '  (' + data[i].difference + 's)
';
      };

      content += '
Traffic

';

      addNewCard(content);
    });
  };

  var addWeatherCard = function() {
    var url = 'weather/nearby_weather?lat=' + lat + '&long=' + lon
    $.getJSON(url, function(data) {
      var content = '

Local weather

'

      content += '
Now: ' + data.current_summary + ' - ' + data.current_temp + '°C, feels like ' + data.currently_feels_like + '°C
';
      content += '
Later: ' + data.next_summary + ' - ' + data.next_temp + '°C
';

      content += '
Weather

';

      addNewCard(content);
    });
  };

  var addRoadWorksCard = function() {
    var url = '/roadworks/neraby_roadworks?lat=' + lat + '&long=' + lon + '&radius=10'
    $.getJSON(url, function(data) {
      var content = '

' + data.length + ' road works nearby

'
      var border_colour;

      for(var i = 0; i < data.length; i++) {
        if(data[i].impact == "freeFlow") {
          border_colour = "rgb(50, 162, 35)";
        }
        else if(data[i].impact == "heavy") {
          border_colour = "rgb(248, 186, 55)";
        }
        else if(data[i].impact == "impossible") {
          border_colour = "rgb(241, 40, 12)";
        }

        var parts = data[i].comment.split('.');
        content += '
' + parts[0] + '
';
      };

      content += '
Road Works

';

      addNewCard(content);
    });
  };

  var addMusicCard = function(severity) {
      var embed = '';

      console.log(severity);
      var value = ((severity - 1) * 5) + 0.5;
      console.log(value);

      $.getJSON('/music/playlist.json', {
          speed: value,
          energy: value,
          danceability: 1
      }, function(data) {

          var content = '

Spotify playlist
';

          if ('songs' in data.response) {
              var tracks = []
              data.response.songs.forEach(function(song) {
                  if(song.tracks.length > 0) {
                      tracks.push(song.tracks[0].foreign_id.replace('spotify-WW:track:', ''));
                  }
              });
              var tembed = embed.replace('TRACKS', tracks.join()).replace('PREFEREDTITLE', 'Playlist');

              content += '
' + tembed + '
';

              $("#results").html(tembed);
          }

          content += 'Music
';

          addNewCard(content);
      });
  };

  var addPredictionCard = function() {
    var url = '/prediction.json?lat=' + lat + '&long=' + lon + '&radius=10'
    $.getJSON(url, function(data) {
      var content = '

' + data.description + '
Travel Prediction

'

      $('#map_wrapper').after(content);

      renderCards();
    });
  };

  /********
  LISTENERS
  ********/

  // Animate expanding the map
  $('#map_btn').click(function() {
    var height = $('#map').height();

    if (height > 170) {
      $('#map').css('height', '170px');
      $('#map_btn_wrapper').css('margin-top', '150px');
      $('#map_btn').addClass('glyphicon-chevron-down');
      $('#map_btn').removeClass('glyphicon-chevron-up');
      map.invalidateSize();
    } else {
      $('#map').css('height', '350px');
      $('#map_btn_wrapper').css('margin-top', '330px');
      $('#map_btn').addClass('glyphicon-chevron-up');
      $('#map_btn').removeClass('glyphicon-chevron-down');
      map.invalidateSize();
    }
  });
});
<|endoftext|>


<commit_before>var eos = require('end-of-stream')
var stream = require('stream')
var util = require('util')

var noop = function() {}

var onclose = function(self) {
  return function(err) {
    if (err) self.destroy(err.message === 'premature close' ? null : err)
  }
}

var Duplexify = function(writable, readable, opts) {
  if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  stream.Duplex.call(this, opts)

  this.destroyed = false
  this._destroy = !opts || opts.destroy !== false

  this._writable = null
  this._readable = null
  this._readable2 = null

  this._writeArguments = null
  this._endArguments = null

  this._forwarding = false
  this._drained = false
  this._finished = false
  this._ondrain = null
  this._onclose = onclose(this)

  if (writable) this.setWritable(writable)
  if (readable) this.setReadable(readable)
}

util.inherits(Duplexify, stream.Duplex)

Duplexify.obj = function(writable, readable, opts) {
  if (!opts) opts = {}
  opts.objectMode = true
  opts.highWaterMark = 16
  return new Duplexify(writable, readable, opts)
}

Duplexify.prototype.setReadable = function(readable) {
  this._readableClear()

  if (this.destroyed) {
    if (readable.destroy) readable.destroy()
    return
  }
  if (readable === null || readable === false) {
    this.push(null)
    return
  }

  var self = this
  var unend = eos(readable, {writable:false, readable:true}, this._onclose)

  var onreadable = function() {
    self._forward()
  }

  var onend = function() {
    self.push(null)
  }

  var clear = function() {
    self._readable2.removeListener('readable', onreadable)
    self._readable2.removeListener('end', onend)
    unend()
  }

  this._drained = true
  this._readable = readable
  this._readable2 = typeof readable.read === 'function' ? readable : new (stream.Readable)().wrap(readable)
  this._readable2.on('readable', onreadable)
  this._readable2.on('end', onend)
  this._readableClear = clear

  this._forward()
}

Duplexify.prototype.setWritable = function(writable) {
  this._writableClear()

  if (this.destroyed) {
    if (writable.destroy) writable.destroy()
    return
  }
  if (writable === null || writable === false) {
    this._finish(noop)
    return
  }

  var self = this
  var unend = eos(writable, {writable:true, readable:false}, this._onclose)

  var ondrain = function() {
    var ondrain = self._ondrain
    self._ondrain = null
    if (ondrain) ondrain()
  }

  var clear = function() {
    self._writable.removeListener('drain', ondrain)
    unend()
  }

  this._writable = writable
  this._writable.on('drain', ondrain)
  this._writableClear = clear
  ondrain()

  if (this._writeArguments) this._write.apply(this, this._writeArguments)
  if (this._endArguments) this.end.apply(this, this._endArguments)
}

Duplexify.prototype.destroy = function(err) {
  if (this.destroyed) return
  this.destroyed = true

  if (err) {
    var ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain(err)
    else this.emit('error', err)
  }

  if (this._destroy) {
    if (this._readable && this._readable.destroy) this._readable.destroy()
    if (this._writable && this._writable.destroy) this._writable.destroy()
  }

  this.emit('close')
}

Duplexify.prototype._read = function() {
  this._drained = true
  this._forward()
}

Duplexify.prototype._finish = function(cb) {
  var self = this
  var end = function() {
    stream.Writable.prototype.end.call(self, cb)
  }

  if (!this.emit('prefinish', end)) end()
}

Duplexify.prototype._forward = function() {
  if (this._forwarding || !this._readable2 || !this._drained) return
  this._forwarding = true

  var data
  while ((data = this._readable2.read()) !== null) {
    this._drained = this.push(data)
  }

  this._forwarding = false
}

Duplexify.prototype.end = function(data, enc, cb) {
  if (!this._writable) {
    this._endArguments = arguments
    return
  }

  if (typeof data === 'function') {
    enc = null
    cb = data
    data = null
  } else if (typeof enc === 'function') {
    cb = enc
    enc = null
  }

  if (data) this._writable.write(data)

  var self = this
  var end = function() {
    self._finish(cb)
  }

  if (!this._writable._writableState) {
    self._writable.end()
    end()
    return
  }

  self._writable.end(end)
}

Duplexify.prototype._write = function(data, enc, cb) {
  if (this.destroyed) return cb()

  if (!this._writable) {
    this._writeArguments = arguments
    return
  }

  if (this._writable.write(data) === false) this._ondrain = cb
  else cb()
}

Duplexify.prototype._readableClear = Duplexify.prototype._writableClear = noop

module.exports = Duplexify<commit_msg>nexttick ondrain on multi setWritable<commit_after>var eos = require('end-of-stream')
var stream = require('stream')
var util = require('util')

var noop = function() {}

var onclose = function(self) {
  return function(err) {
    if (err) self.destroy(err.message === 'premature close' ? null : err)
  }
}

var Duplexify = function(writable, readable, opts) {
  if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  stream.Duplex.call(this, opts)

  this.destroyed = false
  this._destroy = !opts || opts.destroy !== false

  this._writable = null
  this._readable = null
  this._readable2 = null

  this._writeArguments = null
  this._endArguments = null

  this._forwarding = false
  this._drained = false
  this._finished = false
  this._ondrain = null
  this._onclose = onclose(this)

  if (writable) this.setWritable(writable)
  if (readable) this.setReadable(readable)
}

util.inherits(Duplexify, stream.Duplex)

Duplexify.obj = function(writable, readable, opts) {
  if (!opts) opts = {}
  opts.objectMode = true
  opts.highWaterMark = 16
  return new Duplexify(writable, readable, opts)
}

Duplexify.prototype.setReadable = function(readable) {
  this._readableClear()

  if (this.destroyed) {
    if (readable.destroy) readable.destroy()
    return
  }
  if (readable === null || readable === false) {
    this.push(null)
    return
  }

  var self = this
  var unend = eos(readable, {writable:false, readable:true}, this._onclose)

  var onreadable = function() {
    self._forward()
  }

  var onend = function() {
    self.push(null)
  }

  var clear = function() {
    self._readable2.removeListener('readable', onreadable)
    self._readable2.removeListener('end', onend)
    unend()
  }

  this._drained = true
  this._readable = readable
  this._readable2 = typeof readable.read === 'function' ? readable : new (stream.Readable)().wrap(readable)
  this._readable2.on('readable', onreadable)
  this._readable2.on('end', onend)
  this._readableClear = clear

  this._forward()
}

Duplexify.prototype.setWritable = function(writable) {
  this._writableClear()

  if (this.destroyed) {
    if (writable.destroy) writable.destroy()
    return
  }
  if (writable === null || writable === false) {
    this._finish(noop)
    return
  }

  var self = this
  var unend = eos(writable, {writable:true, readable:false}, this._onclose)

  var ondrain = function() {
    var ondrain = self._ondrain
    self._ondrain = null
    if (ondrain) ondrain()
  }

  var clear = function() {
    self._writable.removeListener('drain', ondrain)
    unend()
  }

  this._writable = writable
  this._writable.on('drain', ondrain)
  this._writableClear = clear
  if (self._ondrain) process.nextTick(ondrain) // force a drain too avoid livelocks

  if (this._writeArguments) this._write.apply(this, this._writeArguments)
  if (this._endArguments) this.end.apply(this, this._endArguments)
}

Duplexify.prototype.destroy = function(err) {
  if (this.destroyed) return
  this.destroyed = true

  if (err) {
    var ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain(err)
    else this.emit('error', err)
  }

  if (this._destroy) {
    if (this._readable && this._readable.destroy) this._readable.destroy()
    if (this._writable && this._writable.destroy) this._writable.destroy()
  }

  this.emit('close')
}

Duplexify.prototype._read = function() {
  this._drained = true
  this._forward()
}

Duplexify.prototype._finish = function(cb) {
  var self = this
  var end = function() {
    stream.Writable.prototype.end.call(self, cb)
  }

  if (!this.emit('prefinish', end)) end()
}

Duplexify.prototype._forward = function() {
  if (this._forwarding || !this._readable2 || !this._drained) return
  this._forwarding = true

  var data
  while ((data = this._readable2.read()) !== null) {
    this._drained = this.push(data)
  }

  this._forwarding = false
}

Duplexify.prototype.end = function(data, enc, cb) {
  if (!this._writable) {
    this._endArguments = arguments
    return
  }

  if (typeof data === 'function') {
    enc = null
    cb = data
    data = null
  } else if (typeof enc === 'function') {
    cb = enc
    enc = null
  }

  if (data) this._writable.write(data)

  var self = this
  var end = function() {
    self._finish(cb)
  }

  if (!this._writable._writableState) {
    self._writable.end()
    end()
    return
  }

  self._writable.end(end)
}

Duplexify.prototype._write = function(data, enc, cb) {
  if (this.destroyed) return cb()

  if (!this._writable) {
    this._writeArguments = arguments
    return
  }

  if (this._writable.write(data) === false) this._ondrain = cb
  else cb()
}

Duplexify.prototype._readableClear = Duplexify.prototype._writableClear = noop

module.exports = Duplexify<|endoftext|>


<commit_before>//debugger;
var log = []; //Create global variable for logs.

//Global function for sending the log file to me via email.
function sendLog() {
  //debugger;
  //For now, I'll just dump the log into the console until I have email setup.
  console.log('Begin log dump...');
  for( var i = 0; i < log.length; i++ ) {
    console.log(log[i]);
  }
  console.log('...End log dump.');

  var obj = new Object();
  obj.log = log;
  $.get('/api/email/sendlog', obj, function(data) {
    console.log('Log file emailed to administrator.');
  });
}

//This function is used to detect the browser used by the website viewer.
//This data is sent in the error log in the event of an issue with the RTB form.
//Source code came from this JSFiddle: http://jsfiddle.net/VhaqM/165/
//Based on this discussion thread in Stack Overflow answer by Danail Gabenski:
//http://stackoverflow.com/questions/5916900/how-can-you-detect-the-version-of-a-browser
function detectBrowser() {
  var _browser = {};  //Used to detect the viewers browser.

  //debugger;
  var uagent = navigator.userAgent.toLowerCase(),
      match = '';

  //$("#browserResult").html("User agent string: " + uagent + "");

  _browser.chrome  = /webkit/.test(uagent)  && /chrome/.test(uagent) && !/edge/.test(uagent);
  _browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);
  _browser.msie    = /msie/.test(uagent) || /trident/.test(uagent) || /edge/.test(uagent);
  _browser.safari  = /safari/.test(uagent)  && /applewebkit/.test(uagent) && !/chrome/.test(uagent);
  _browser.opr     = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&  /chrome/.test(uagent) && /safari/.test(uagent) && /opr/.test(uagent);
  _browser.version = '';

  for (x in _browser) {
    if (_browser[x]) {

      // microsoft is "special"
      match = uagent.match(new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)"));

      if (match) {
        _browser.version = match[3];
      } else {
        match = uagent.match(new RegExp("rv:([0-9]+)"));
        _browser.version = match ? match[1] : "";
      }

      //$("#browserResult").append("
The browser is " + (x === "opr" ? "Opera" : x) +
      //  " v. " + (_browser.version ? _browser.version : "N/A") + "");
      var browserStr = (x === "opr" ? "Opera" : x);
      var browserVersion = (_browser.version ? _browser.version : "N/A");
      log.push('Browser: '+browserStr+' v. '+browserVersion);
      log.push('Operating system: '+navigator.platform);
      //console.log('Browser: '+browserStr+' v. '+browserVersion);
      //console.log('Operating system: '+navigator.platform);
      break;
    }
  }
  _browser.opera = _browser.opr;
  delete _browser.opr;
}<commit_msg>Developing email API and sendlog to use it.<commit_after>//debugger;
var log = []; //Create global variable for logs.

//Global function for sending the log file to me via email.
function sendLog() {
  //debugger;
  //For now, I'll just dump the log into the console until I have email setup.
  console.log('Begin log dump...');
  for( var i = 0; i < log.length; i++ ) {
    console.log(log[i]);
  }
  console.log('...End log dump.');

  var obj = new Object();
  obj.log = log;
  $.get('/api/email/sendlog', obj, function(data) {
    console.log('Log file emailed to administrator.');
  })
  .fail(function( jqxhr, textStatus, error ) {
    debugger;

    var err = textStatus + ", " + error;

    try {
      if(jqxhr.responseJSON.detail == "invalid csrf") {
        global.modalView.errorModal('Update failed due to a bad CSRF token. Please log out and back in to refresh your CSRF token.');
        return;
      } else {
        global.modalView.errorModal("Request failed because of: "+error+'. Error Message: '+jqxhr.responseText);
        console.log( "Request Failed: " + error );
        console.error('Error message: '+jqxhr.responseText);
      }
    } catch(err) {
      console.error('Error trying to retrieve JSON data from server response.');
    }
  });
}

//This function is used to detect the browser used by the website viewer.
//This data is sent in the error log in the event of an issue with the RTB form.
//Source code came from this JSFiddle: http://jsfiddle.net/VhaqM/165/
//Based on this discussion thread in Stack Overflow answer by Danail Gabenski:
//http://stackoverflow.com/questions/5916900/how-can-you-detect-the-version-of-a-browser
function detectBrowser() {
  var _browser = {};  //Used to detect the viewers browser.

  //debugger;
  var uagent = navigator.userAgent.toLowerCase(),
      match = '';

  //$("#browserResult").html("User agent string: " + uagent + "");

  _browser.chrome  = /webkit/.test(uagent)  && /chrome/.test(uagent) && !/edge/.test(uagent);
  _browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);
  _browser.msie    = /msie/.test(uagent) || /trident/.test(uagent) || /edge/.test(uagent);
  _browser.safari  = /safari/.test(uagent)  && /applewebkit/.test(uagent) && !/chrome/.test(uagent);
  _browser.opr     = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&  /chrome/.test(uagent) && /safari/.test(uagent) && /opr/.test(uagent);
  _browser.version = '';

  for (x in _browser) {
    if (_browser[x]) {

      // microsoft is "special"
      match = uagent.match(new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)"));

      if (match) {
        _browser.version = match[3];
      } else {
        match = uagent.match(new RegExp("rv:([0-9]+)"));
        _browser.version = match ? match[1] : "";
      }

      //$("#browserResult").append("
The browser is " + (x === "opr" ? "Opera" : x) +
      //  " v. " + (_browser.version ? _browser.version : "N/A") + "");
      var browserStr = (x === "opr" ? "Opera" : x);
      var browserVersion = (_browser.version ? _browser.version : "N/A");
      log.push('Browser: '+browserStr+' v. '+browserVersion);
      log.push('Operating system: '+navigator.platform);
      //console.log('Browser: '+browserStr+' v. '+browserVersion);
      //console.log('Operating system: '+navigator.platform);
      break;
    }
  }
  _browser.opera = _browser.opr;
  delete _browser.opr;
}<|endoftext|>


<commit_before>var PLUGIN_NAME, actions, createId, plugin;

PLUGIN_NAME = 'fission-localstorage';

createId = function() {
  var machine, pid, timestamp;
  timestamp = new Date().getTime();
  machine = Math.floor(Math.random() * 16777216);
  pid = Math.floor(Math.random() * 32767);
  return "00000000".substr(0, 8 - timestamp.length) + timestamp + "000000".substr(0, 6 - machine.length) + machine + "0000".substr(0, 4 - pid.length) + pid;
};

actions = {
  store: function() {
    var store;
    store = window.localStorage;
    if (!store) {
      throw "" + PLUGIN_NAME + ": localStorage not supported by Browser";
    }
    console.log(store);
    return store;
  },
  serialize: function(model) {
    return JSON.stringify(model);
  },
  deserialize: function(model) {
    return JSON.parse(model);
  },
  find: function(model, opts) {
    console.log(model)
    console.log(opts.collection)
    return this.deserialize(this.store().getItem("" + opts.collection + "-" + model.id));
  }
};

plugin = {
  create: function(model, opts) {
    if (model.id == null) {
      model.id = createId();
    }
    actions.store().setItem("" + opts.collection + "-" + model.id, actions.serialize(model));
    return actions.find(model, opts);
  },
  readAll: function(model, opts) {
    //actions.store().forEach(item) {
    //}
  },
  read: function(model, opts) {
    console.log(actions.find(model, opts))
    return actions.find(model, opts);
  },
  update: function(model, opts) {
    return this.create(model, opts);
  },
  "delete": function(model, opts) {
    return actions.store().removeItem("" + opts.collection + "-" + model.id);
  }
};

module.exports = function(method, model, options, cb) {
  console.log(method, model, options)
  var run;
  if (plugin[method] == null) {
    throw "" + PLUGIN_NAME + ": undefined method: " + method;
  }
  if (model == null) {
    throw "" + PLUGIN_NAME + ": model is required";
  }

  if (!model.id) {
    method = 'readAll';
  }

  //if (options.collection == null) {
  //  throw "" + PLUGIN_NAME + ": options.collection is required";
  //}
  options.collection = 'todoz'
  run = plugin[method](model, options);
  if (cb) {
    return cb(run);
  }
  return run;
};
<commit_msg>rebuild, fixes #1<commit_after>/*globals window,module*/
'use strict';

var PLUGIN_NAME = 'fission-sync-localstorage';

var createId = function() {
  var timestamp = new Date().getTime();
  var machine = Math.floor(Math.random() * 16777216);
  var pid = Math.floor(Math.random() * 32767);
  return '00000000'.substr(0, 8 - timestamp.length) + timestamp + '000000'.substr(0, 6 - machine.length) + machine + '0000'.substr(0, 4 - pid.length) + pid;
};

var actions = {
  store: function() {
    var store;
    store = window.localStorage;
    if (!store) {
      throw PLUGIN_NAME + ': localStorage not supported by Browser';
    }
    return store;
  },
  serialize: function(model) {
    return JSON.stringify(model);
  },
  deserialize: function(model) {
    return JSON.parse(model);
  },
  find: function(model) {
    return this.deserialize(this.store().getItem(model.url + '/' + model.id));
  }
};

var plugin = {
  create: function(model, cb) {
    if (!model.id) {
      model.id = createId();
    }
    if (model.url.indexOf(model.id) > -1) {
      model.url = model.url.replace('/'+model.id, '');
    }
    model._values.url = model.url;
    model._values.id = model.id;

    actions.store().setItem(model.url + '/' + model.id, actions.serialize(model._values));
    if (cb) {
      return cb(null, actions.find(model));
    }
    return actions.find(model);
  },
  readAll: function(model, cb) {
    var items = [];
    var count = 0;
    for (var i in actions.store()) {
      count ++;
      var item = actions.store().getItem(i);
      item = actions.deserialize(item);
      if (item.url === model.url) {
        items.push(item);
      }
      if (count === actions.store().length) {
        return cb(null, items);
      }
    }
  },
  read: function(model, cb) {
    return cb(null, actions.find(model));
  },
  update: function(model, cb) {
    var item = this.create(model);
    return cb(null, item);
  },
  'delete': function(model, cb) {
    if (model.url.indexOf(model.id) === -1) {
      model.url = model.url + '/'+model.id;
    }
    actions.store().removeItem(model.url);
    return cb(null, null);
  }
};

module.exports = function(method, model, options) {

  if (!plugin[method]) {
    throw PLUGIN_NAME + ': undefined method: ' + method;
  }
  if (!model) {
    throw PLUGIN_NAME + ': model is required';
  }
  if (!model.url) {
    throw PLUGIN_NAME + ': model.url is required to be set to the collection name';
  }

  if (!model.id && method === 'read') {
    method = 'readAll';
  }

  model.url = model.url;
  if (typeof model.url === 'function') {
    model.url = model.url();
  }

  plugin[method](model, function(err, data) {
    if (err) {
      return options.error(data);
    }
    return options.success(data);
  });

};
<|endoftext|>


<commit_before>"use strict";

exports.CcdaParserStream = require('./lib/parser');
<commit_msg>fix: exported objects udated<commit_after>"use strict";

module.exports = require('./lib/parser');
<|endoftext|>


<commit_before><commit_msg>Deleted autogenerated file<commit_after><|endoftext|>


<commit_before>if(process.env.NODE_COV) {
	exports = module.exports = require('./lib-cov/lego.js');
}
else {
	exports = module.exports = require('./lib/lego.js');
}
<commit_msg>fixes main entry point<commit_after>if(process.env.NODE_COV) {
	exports = module.exports = require('./lib-cov/index.js');
}
else {
	exports = module.exports = require('./lib/index.js');
}
<|endoftext|>


<commit_before>/*
Name:         cloudsight
Description:  Node.js module to access CloudSight API methods
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.con/fvdm/nodejs-cloudsight
Feedback:     https://github.con/fvdm/nodejs-cloudsight/issues
License:      Unlicense (Public Domain, see LICENSE file)
*/

var httpreq = require ('httpreq');

var config = {
  apikey: null,
  endpoint: null,
  timeout: null
};

/**
 * Communication
 *
 * @param {object} props
 * @param {string} [props.method=GET] - GET or POST
 * @param {string) props.path - i.e. /image_requests/token
 * @param {object} [props.data] - Data fields to send
 * @param {string} [props.endpoint=config.endpoint] - API endpoint override
 * @param {number} [props.timeout=config.timeout] - Request timeout override
 * @param {function} callback - Process response
 * @returns {void}
 */

function talk (props, callback) {
  var options = {
    url: config.endpoint + props.path,
    method: props.method || 'GET',
    parameters: props.data || null,
    timeout: props.timeout || config.timeout,
    headers: {
      'Accept': 'application/json',
      'Authorization': 'CloudSight ' + config.apikey,
      'User-Agent': 'cloudsight.js (https://github.com/fvdm/nodejs-cloudsight)'
    }
  };

  httpreq.doRequest (options, function (err, res) {
    var data = res && res.body || '';
    var code = res && res.statusCode || null;
    var error = null;

    // request error
    if (err) {
      error = err;
      error.statusCode = code;
      callback (error);
      return;
    }

    // http error
    if (code && code >= 300) {
      error = new Error ('HTTP error');
      error.statusCode = code;
      error.body = data;
      callback (error);
      return;
    }

    // parse body
    try {
      data = JSON.parse (data);
    } catch (e) {
      error = e;
      error.statusCode = code;
      error.body = data;
      callback (error);
      return;
    }

    // API error
    if (data.error) {
      error = new Error ('API error');
      error.statusCode = code;
      error.error = data.error;
      callback (error);
      return;
    }

    // all good
    callback (null, data);
  });
}

/**
 * Get result data for image
 *
 * @param {string} token - Image token
 * @param {function} callback
 * @returns {void}
 */

function imageResponses (token, callback) {
  var options = {
    method: 'GET',
    path: '/image_responses/' + token
  };

  talk (options, callback);
}

/**
 * Check status at preferred interval
 *
 * @param {string} token - Image token
 * @param {function} callback
 * @returns {void}
 */

function pollStatus (token, callback) {
  imageResponses (token, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    if (data.status === 'not completed') {
      setTimeout (function () {
        pollStatus (token, callback);
      }, 1000);
    } else {
      callback (null, data);
    }
  });
}

/**
 * Send an image for processing
 *
 * @param {object} props - See README.md
 * @param {boolean} [polling=false] - Callback only when results are ready
 * @param {function} callback - Callback response
 * @returns {void}
 */

function imageRequests (props, polling, callback) {
  var options = {
    method: 'POST',
    path: '/image_requests',
    data: props
  };

  talk (options, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    if (polling && data.token) {
      setTimeout (function () {
        pollStatus (data.token, callback);
      }, 4000);

      return;
    }

    callback (null, data);
  });
}

/**
 * Module config and defaults
 *
 * @param {object} conf
 * @param {string} conf.apikey - Account API key
 * @param {string} [conf.endpoint] - Override API endpoint
 * @param {number} [conf.timeout=5000] - Override request timeout
 * @returns {object} - Module methods
 */

module.exports = function (conf) {
  config.apikey = conf.apikey || null;
  config.endpoint = conf.endpoint || 'https://api.cloudsightapi.com';
  config.timeout = conf.timeout || 5000;

  return {
    request: imageRequests,
    response: imageResponses
  };
};
<commit_msg>Wrap fieldnames, set default values<commit_after>/*
Name:         cloudsight
Description:  Node.js module to access CloudSight API methods
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.con/fvdm/nodejs-cloudsight
Feedback:     https://github.con/fvdm/nodejs-cloudsight/issues
License:      Unlicense (Public Domain, see LICENSE file)
*/

var httpreq = require ('httpreq');

var config = {
  apikey: null,
  endpoint: null,
  timeout: null
};

/**
 * GUID generator
 *
 * @returns {string}
 */

function guidGenerator () {
  function S4 (times, prefix) {
    var str = '';
    var i;

    for (i = times || 1; i > 0; i--) {
      str += String (prefix);
      str += parseInt (((Math.random () + 1) * 0x10000), 10) .toString (16) .substring (1);
    }

    return str;
  };

  return (S4 (2) + S4 (4, '-') + S4 (2));
}

/**
 * Communication
 *
 * @param {object} props
 * @param {string} [props.method=GET] - GET or POST
 * @param {string) props.path - i.e. /image_requests/token
 * @param {object} [props.data] - Data fields to send
 * @param {string} [props.endpoint=config.endpoint] - API endpoint override
 * @param {number} [props.timeout=config.timeout] - Request timeout override
 * @param {function} callback - Process response
 * @returns {void}
 */

function talk (props, callback) {
  var options = {
    url: config.endpoint + props.path,
    method: props.method || 'GET',
    parameters: props.data || null,
    timeout: props.timeout || config.timeout,
    headers: {
      'Accept': 'application/json',
      'Authorization': 'CloudSight ' + config.apikey,
      'User-Agent': 'cloudsight.js (https://github.com/fvdm/nodejs-cloudsight)'
    }
  };

  httpreq.doRequest (options, function (err, res) {
    var data = res && res.body || '';
    var code = res && res.statusCode || null;
    var error = null;

    // request error
    if (err) {
      error = err;
      error.statusCode = code;
      callback (error);
      return;
    }

    // http error
    if (code && code >= 300) {
      error = new Error ('HTTP error');
      error.statusCode = code;
      error.body = data;
      callback (error);
      return;
    }

    // parse body
    try {
      data = JSON.parse (data);
    } catch (e) {
      error = e;
      error.statusCode = code;
      error.body = data;
      callback (error);
      return;
    }

    // API error
    if (data.error) {
      error = new Error ('API error');
      error.statusCode = code;
      error.error = data.error;
      callback (error);
      return;
    }

    // all good
    callback (null, data);
  });
}

/**
 * Get result data for image
 *
 * @param {string} token - Image token
 * @param {function} callback
 * @returns {void}
 */

function imageResponses (token, callback) {
  var options = {
    method: 'GET',
    path: '/image_responses/' + token
  };

  talk (options, callback);
}

/**
 * Check status at preferred interval
 *
 * @param {string} token - Image token
 * @param {function} callback
 * @returns {void}
 */

function pollStatus (token, callback) {
  imageResponses (token, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    if (data.status === 'not completed') {
      setTimeout (function () {
        pollStatus (token, callback);
      }, 1000);
    } else {
      callback (null, data);
    }
  });
}

/**
 * Send an image for processing
 *
 * @param {object} props - See README.md
 * @param {boolean} [polling=false] - Callback only when results are ready
 * @param {function} callback - Callback response
 * @returns {void}
 */

function imageRequests (props, polling, callback) {
  var options = {
    method: 'POST',
    path: '/image_requests',
    data: {}
  };

  var keys = Object.keys (props);
  var i;

  props.locale = props.locale || 'en-US';
  props.language = props.language || 'en';
  props.device_id = props.device_id || guidGenerator ();

  for (i = 0; i < keys.length; i++) {
    options.data ['image_request[' + keys [i] + ']'] = props [keys [i]];
  }

  talk (options, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    if (polling && data.token) {
      setTimeout (function () {
        pollStatus (data.token, callback);
      }, 4000);

      return;
    }

    callback (null, data);
  });
}

/**
 * Module config and defaults
 *
 * @param {object} conf
 * @param {string} conf.apikey - Account API key
 * @param {string} [conf.endpoint] - Override API endpoint
 * @param {number} [conf.timeout=5000] - Override request timeout
 * @returns {object} - Module methods
 */

module.exports = function (conf) {
  config.apikey = conf.apikey || null;
  config.endpoint = conf.endpoint || 'https://api.cloudsightapi.com';
  config.timeout = conf.timeout || 5000;

  return {
    request: imageRequests,
    response: imageResponses
  };
};
<|endoftext|>


<commit_before>
var init = {
  lat: 39.908715,
  lng: 116.3973889,
  zoom: function() {
    var match = location.href.match(/zoom=(\d+)/);
    return match != null ? parseInt(match[1]) : 14
  },
  center: function() {
    var match = location.href.match(/center=([\d.]+),([\d.]+)/);
    if(match != null) {
      return new google.maps.LatLng(
        parseFloat(match[1]), parseFloat(match[2]));
    } else {
      return new google.maps.LatLng(init.lat, init.lng);
    }
  }
};

var map, geocoder, marker;
var mapDiv, addInput;
var selectedNote = null;

var uiState = {
  "loading" : {
    "load-icon" : true
  },
  "selection" : {
    "notes" : true,
    "save-button" : true
  },
  "success" : {
    "success-message" : true
  },
  "error" : {
    "error-message" : true
  },
}

function initialize() {
  var options = {
    center: init.center(),
    zoom: init.zoom()
  };

  mapDiv = document.getElementById("map-canvas");
  addInput = document.getElementById("address");

  map = new google.maps.Map(mapDiv, options);
  geocoder = new google.maps.Geocoder();
  marker = new google.maps.Marker({
    map: map,
    animation: google.maps.Animation.DROP
  });
  $('#address').keydown(function(event) {
    if(event.keyCode == 13) {
      search();
    }
  });
}

function updateUI(state) {
  var allElements = ["notes", "save-button", "load-icon",
    "success-message", "error-message"];
  var meta = uiState[state];
  for(var i = 0; i < allElements.length; i++) {
    var id = allElements[i];
    if(meta[id] === true) {
      $("#" + id).show();
    } else {
      $("#" + id).hide();
    }
  }
}

function getBackURL() {
  var center = map.getCenter();
  var zoom = map.getZoom();
  var lat = center.nb;
  var lng = center.ob;
  return window.location.origin +
    "?center=" + lat + "," + lng + "&zoom=" + zoom;
}

function updateMap(center) {
  map.setCenter(center);
  marker.setPosition(map.getCenter());
  //marker.setAnimation(google.maps.Animation.DROP);
}

function search() {
  var address = addInput.value;
  if(address.trim() !== "") {
    geocoder.geocode( { "address": address }, function(data, status) {
      if(status == google.maps.GeocoderStatus.OK) {
        var loc = data[0].geometry.location;
        updateMap(loc);
      } else {
        alert("Location not found!");
      }
    });
  }
}

function popupSaveDialog() {
  updateUI("loading");

  $("#myModal").modal("show");

  $.ajax({
    url: "/api/notes",
    dataType: "json"
  })
  .done(function(data) {
    var notes = data.notes;
    var htmlCodes = [];

    for(var i = 0; i < notes.length; i++) {
      var note = notes[i];
      htmlCodes.push('' +
        note.title + '');
    }

    $("#note-list").html(htmlCodes.join(""));
    updateUI("selection");
  })
  .fail(function(xhr) {
    if(xhr.status == 401) {
      window.location.href = "oauth/request_token?back_url=" +
        encodeURIComponent(getBackURL());
    }
  });
}

function selectNote(note) {
  if(selectedNote != note) {
    if(selectedNote != null) {
      selectedNote.classList.remove("active");
    }
    selectedNote = note;
    selectedNote.classList.add("active");
  }
}

function resetSelectedNote() {
  if(selectedNote != null) {
    selectedNote.classList.remove("active");
    selectedNote = null;
  }
}

function save() {
  var center = map.getCenter();
  var data = {
    zoom: map.getZoom(),
    lat: center.nb,
    lng: center.ob
  }

  updateUI("loading");

  if(selectedNote == null) {
    var noteName = $("#new-note-name").val();
    data.note_name = encodeURIComponent(noteName);

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/api/notes",
      data: data
    })
    .done(function(data) {
      updateUI("success");
      $("#note-link").attr("href", data.note_url);
    })
    .fail(function(xhr) {
      updateUI("error");
    });
  } else {
    $.ajax({
      type: "PUT",
      dataType: "json",
      url: "/api/notes/" + selectedNote.id,
      data: data
    })
    .done(function(data){
      updateUI("success");
      $("#note-link").attr("href", data.note_url);
    })
    .fail(function(xhr){
      updateUI("error");
    });
  }
}
<commit_msg>draw a rectangle in the map center to show the valid clipped area<commit_after>
var init = {
  lat: 39.908715,
  lng: 116.3973889,
  zoom: function() {
    var match = location.href.match(/zoom=(\d+)/);
    return match != null ? parseInt(match[1]) : 14
  },
  center: function() {
    var match = location.href.match(/center=([\d.]+),([\d.]+)/);
    if(match != null) {
      return new google.maps.LatLng(
        parseFloat(match[1]), parseFloat(match[2]));
    } else {
      return new google.maps.LatLng(init.lat, init.lng);
    }
  }
};

var map, geocoder, marker, clippedArea;
var mapDiv, addInput;
var selectedNote = null;

var uiState = {
  "loading" : {
    "load-icon" : true
  },
  "selection" : {
    "notes" : true,
    "save-button" : true
  },
  "success" : {
    "success-message" : true
  },
  "error" : {
    "error-message" : true
  },
}

function initialize() {
  var options = {
    center: init.center(),
    zoom: init.zoom()
  };

  mapDiv = document.getElementById("map-canvas");
  addInput = document.getElementById("address");

  map = new google.maps.Map(mapDiv, options);
  geocoder = new google.maps.Geocoder();
  marker = new google.maps.Marker({
    map: map,
    animation: google.maps.Animation.DROP
  });

  clippedArea = new google.maps.Rectangle();

  google.maps.event.addListener(map, 'zoom_changed', function() {
    clippedArea.setOptions(rectOptions());
  });

  google.maps.event.addListener(map, 'center_changed', function() {
    clippedArea.setOptions(rectOptions());
  });

  $('#address').keydown(function(event) {
    if(event.keyCode == 13) {
      search();
    }
  });
}

function rectOptions() {
  return {
    strokeOpacity: 0,
    fillColor: '#FF0000',
    fillOpacity: 0.15,
    map: map,
    bounds: clippedBounds()
  }
}

function clippedBounds() {
  var proj = map.getProjection();
  var center = proj.fromLatLngToPoint(map.getCenter());

  var scale = Math.pow(2, map.getZoom());
  var tl = new google.maps.Point(
    center.x - 300/scale,
    center.y - 225/scale);
  var br = new google.maps.Point(
    center.x + 300/scale,
    center.y + 225/scale);

  return new google.maps.LatLngBounds(
    proj.fromPointToLatLng(tl),
    proj.fromPointToLatLng(br)
  );
}

function updateUI(state) {
  var allElements = ["notes", "save-button", "load-icon",
    "success-message", "error-message"];
  var meta = uiState[state];
  for(var i = 0; i < allElements.length; i++) {
    var id = allElements[i];
    if(meta[id] === true) {
      $("#" + id).show();
    } else {
      $("#" + id).hide();
    }
  }
}

function getBackURL() {
  var center = map.getCenter();
  var zoom = map.getZoom();
  var lat = center.nb;
  var lng = center.ob;
  return window.location.origin +
    "?center=" + lat + "," + lng + "&zoom=" + zoom;
}

function updateMap(center) {
  map.setCenter(center);
  marker.setPosition(map.getCenter());
  //marker.setAnimation(google.maps.Animation.DROP);
}

function search() {
  var address = addInput.value;
  if(address.trim() !== "") {
    geocoder.geocode( { "address": address }, function(data, status) {
      if(status == google.maps.GeocoderStatus.OK) {
        var loc = data[0].geometry.location;
        updateMap(loc);
      } else {
        alert("Location not found!");
      }
    });
  }
}

function popupSaveDialog() {
  updateUI("loading");

  $("#myModal").modal("show");

  $.ajax({
    url: "/api/notes",
    dataType: "json"
  })
  .done(function(data) {
    var notes = data.notes;
    var htmlCodes = [];

    for(var i = 0; i < notes.length; i++) {
      var note = notes[i];
      htmlCodes.push('' +
        note.title + '');
    }

    $("#note-list").html(htmlCodes.join(""));
    updateUI("selection");
  })
  .fail(function(xhr) {
    if(xhr.status == 401) {
      window.location.href = "oauth/request_token?back_url=" +
        encodeURIComponent(getBackURL());
    }
  });
}

function selectNote(note) {
  if(selectedNote != note) {
    if(selectedNote != null) {
      selectedNote.classList.remove("active");
    }
    selectedNote = note;
    selectedNote.classList.add("active");
  }
}

function resetSelectedNote() {
  if(selectedNote != null) {
    selectedNote.classList.remove("active");
    selectedNote = null;
  }
}

function save() {
  var center = map.getCenter();
  var data = {
    zoom: map.getZoom(),
    lat: center.nb,
    lng: center.ob
  }

  updateUI("loading");

  if(selectedNote == null) {
    var noteName = $("#new-note-name").val();
    data.note_name = encodeURIComponent(noteName);

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/api/notes",
      data: data
    })
    .done(function(data) {
      updateUI("success");
      $("#note-link").attr("href", data.note_url);
    })
    .fail(function(xhr) {
      updateUI("error");
    });
  } else {
    $.ajax({
      type: "PUT",
      dataType: "json",
      url: "/api/notes/" + selectedNote.id,
      data: data
    })
    .done(function(data){
      updateUI("success");
      $("#note-link").attr("href", data.note_url);
    })
    .fail(function(xhr){
      updateUI("error");
    });
  }
}
<|endoftext|>


<commit_before>var floor = Math.floor;

function clamp(min, max, v) {
    if (v < min) return min;
    if (v > max) return max;
    return v;
}

module.exports = function(audioContext, opts) {

    opts = opts || {};

    var bufferSize      = opts.bufferSize || 4096,
        channelCount    = opts.channelCount || 2,
        bits            = clamp(1, Infinity, (opts.bits || 8) | 0),
        normFreq        = clamp(0, 1, opts.frequency || 1),
        step            = 2 * Math.pow(0.5, bits),
        invStep         = 1 / step,
        phasor          = 0,
        last            = 0;

    var processor = audioContext.createScriptProcessor(bufferSize, channelCount, channelCount);

    processor.onaudioprocess = function(evt) {

        var ib = evt.inputBuffer,
            ob = evt.outputBuffer;

        for (var i = 0; i < channelCount; ++i) {

            var id = ib.getChannelData(i),
                od = ob.getChannelData(i);

            for (var s = 0, l = ob.length; s < l; ++s) {
                phasor += normFreq;
                if (phasor > 1) {
                    phasor -= 1;
                    last = step * floor((id[s] * invStep) + 0.5);
                }
                od[s] = last;
            }

        }

    }

    return processor;

}<commit_msg>use >= 1 for sample and hold check<commit_after>var floor = Math.floor;

function clamp(min, max, v) {
    if (v < min) return min;
    if (v > max) return max;
    return v;
}

module.exports = function(audioContext, opts) {

    opts = opts || {};

    var bufferSize      = opts.bufferSize || 4096,
        channelCount    = opts.channelCount || 2,
        bits            = clamp(1, Infinity, (opts.bits || 8) | 0),
        normFreq        = clamp(0, 1, opts.frequency || 1),
        step            = 2 * Math.pow(0.5, bits),
        invStep         = 1 / step,
        phasor          = 0,
        last            = 0;

    var processor = audioContext.createScriptProcessor(bufferSize, channelCount, channelCount);

    processor.onaudioprocess = function(evt) {

        var ib = evt.inputBuffer,
            ob = evt.outputBuffer;

        for (var i = 0; i < channelCount; ++i) {

            var id = ib.getChannelData(i),
                od = ob.getChannelData(i);

            for (var s = 0, l = ob.length; s < l; ++s) {
                phasor += normFreq;
                if (phasor >= 1) {
                    phasor -= 1;
                    last = step * floor((id[s] * invStep) + 0.5);
                }
                od[s] = last;
            }

        }

    }

    return processor;

}<|endoftext|>


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

var testCount = 0,
    failCount = 0,
    totalTime = 0;

function runTests(test) {
    var begin = Date.now();
    //read files, load them, run them
    fs.readdirSync(test.dir)
        .map(function(file) {
            if (file[0] === ".") return false;
            return require(test.dir + file);
        })
        .forEach(function(file) {
            if (file === false) return;
            var second = false,
                failed = false,
                start = Date.now();
            took = 0;

            console.log("Testing:", file.name);

            test.test(file, function(err, dom) {
                if (err) console.log("Handler error:", err);
                took += Date.now() - start;

                var expected = JSON.stringify(file.expected, null, 2),
                    got = JSON.stringify(dom, null, 2);
                if (expected !== got) {
                    failed = true;
                    console.log("Expected", expected, "Got", got, second);
                }

                start = Date.now();

                if (second) {
                    testCount += 1;
                    if (failed) failCount += 1;

                    console.log(
                        "[" + file.name + "]:",
                        failed ? "failed" : "passed",
                        "(took",
                        took,
                        "ms)"
                    );
                } else second = true;
            });
        });
    var took = Date.now() - begin;
    totalTime += took;
    console.log(test.dir, "took", took);
}

//run all tests
["./01-html.js", "./02-feed.js", "./03-events.js", "./04-dom_utils.js"]
    .map(require)
    .forEach(runTests);

//log the results
console.log("Total time:", totalTime);
console.log("Total tests:", testCount);
console.log("Failed tests:", failCount);
<commit_msg>Throw if there was an error<commit_after>var fs = require("fs");

var testCount = 0,
    failCount = 0,
    totalTime = 0;

function runTests(test) {
    var begin = Date.now();
    //read files, load them, run them
    fs.readdirSync(test.dir)
        .map(function(file) {
            if (file[0] === ".") return false;
            return require(test.dir + file);
        })
        .forEach(function(file) {
            if (file === false) return;
            var second = false,
                failed = false,
                start = Date.now();
            took = 0;

            console.log("Testing:", file.name);

            test.test(file, function(err, dom) {
                if (err) console.log("Handler error:", err);
                took += Date.now() - start;

                var expected = JSON.stringify(file.expected, null, 2),
                    got = JSON.stringify(dom, null, 2);
                if (expected !== got) {
                    failed = true;
                    console.log("Expected", expected, "Got", got, second);
                }

                start = Date.now();

                if (second) {
                    testCount += 1;
                    if (failed) failCount += 1;

                    console.log(
                        "[" + file.name + "]:",
                        failed ? "failed" : "passed",
                        "(took",
                        took,
                        "ms)"
                    );
                } else second = true;
            });
        });
    var took = Date.now() - begin;
    totalTime += took;
    console.log(test.dir, "took", took);
}

//run all tests
["./01-html.js", "./02-feed.js", "./03-events.js", "./04-dom_utils.js"]
    .map(require)
    .forEach(runTests);

//log the results
console.log("Total time:", totalTime);
console.log("Total tests:", testCount);
console.log("Failed tests:", failCount);

if (failCount !== 0) {
    throw Error("Encountered " + failCount + " errors!");
}
<|endoftext|>


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

var normalize = path.normalize;

var ABS = '://';
var ONE = '/';

function join (parts) {
  return parts.join(ONE);
}

function valid (url) {
  var schemes = url.split(ABS);
  var base = schemes.shift( );
  var tail = schemes.shift( );
  var parts = (tail || '').split(ONE);
  var host = parts.shift( );
  var begin = base + ABS + host;
  var end = normalize(join(parts));
  if (parts.length == 1) {
    end = parts[0];
  }
  return [begin, end];
}

function urlize (head) {
  var tail = Array.prototype.slice.call(arguments, 1);
  var end = '';
  if (tail.length > 0) { end = normalize(join(tail)); }
  if (end[0] == '.') { end = ONE + end; };
  return join(valid(head + end));
}

module.exports = function wrap ( ) {
  var original = urlize.apply(null, arguments);
  var result = new String(original);
  function base ( ) {
    var r = valid(original.toString( )).shift( );
    return r;
  }
  function quine (op) {
    var parts = Array.prototype.slice.call(arguments);
    if (!op) { parts.unshift(original); }
    if (parts[0] == ONE || (op && op[0] == ONE)) { parts.unshift(base( )); }
    if (parts[0].split(ABS).length == 1)
      parts.unshift(original);
    return wrap.apply(null, parts);
  }

  result.urlize = quine;
  return result;
}
<commit_msg>tweak variable name/magic string<commit_after>var path = require('path');

var normalize = path.normalize;

var ABS = '://';
var ONE = '/';
var DOT = '.';

function join (parts) {
  return parts.join(ONE);
}

function valid (url) {
  var schemes = url.split(ABS);
  var base = schemes.shift( );
  var tail = schemes.shift( );
  var parts = (tail || '').split(ONE);
  var host = parts.shift( );
  var begin = base + ABS + host;
  var end = normalize(join(parts));
  if (parts.length == 1) {
    end = parts[0];
  }
  return [begin, end];
}

function urlize (head) {
  var tail = Array.prototype.slice.call(arguments, 1);
  var end = '';
  if (tail.length > 0) { end = normalize(join(tail)); }
  if (end[0] == DOT) { end = ONE + end; };
  return join(valid(head + end));
}

module.exports = function wrap ( ) {
  var original = urlize.apply(null, arguments);
  var result = new String(original);
  function base ( ) {
    var r = valid(original.toString( )).shift( );
    return r;
  }
  function quine (op) {
    var parts = Array.prototype.slice.call(arguments);
    if (!op) { parts.unshift(original); }
    if (parts[0] == ONE || (op && op[0] == ONE)) { parts.unshift(base( )); }
    if (parts[0].split(ABS).length == 1)
      parts.unshift(original);
    return wrap.apply(null, parts);
  }

  result.urlize = quine;
  return result;
}
<|endoftext|>


<commit_before>// create a map in the "map" div, set the view to a given place and zoom
var map = L.map('map').setView([51.505, -0.09], 13);
var plottedPolyline;
var currentMarkers = new Object();

// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

$('').click(function(){
	id = $(this).data('sochi-id')
	getMarkerData(id);
});

function getMarkerData(id)
{
	$.get('/api/XXX/' + id, createMarkerFromJson, 'json').done(function(){});
}

function createMarkerFromJson(obj, ajaxStatus)
{
	customIcon = createCustomIcon(obj);
	L.marker(obj.data.latLng, {icon: customIcon}).addTo(map)

	currentMarkers[obj.data.id] = obj.data.latLng;

	addMarkerToRoute();
}

function addMarkerToRoute() {
	plottedPolyline = L.Polyline.Plotter(currentMarkers,{weight: 5}).addTo(map);
}

function createCustomIcon(obj) {
	var customIcon = L.icon({
	    iconUrl: obj.data.flag,

	    iconSize:     [38, 95], // size of the icon
	    shadowSize:   [50, 64], // size of the shadow
	    iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
	    shadowAnchor: [4, 62],  // the same for the shadow
	    popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
	});

	return customIcon;
}<commit_msg>added additional marker funcs<commit_after>// create a map in the "map" div, set the view to a given place and zoom
var map = L.map('map').setView([51.505, -0.09], 13);
var plottedPolyline;
var currentMarkers = new Object();

// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

$('').click(function(){
	id = $(this).data('sochi-id')
	getMarkerData(id);
});

function getMarkerData(id)
{
	$.get('/api/XXX/' + id, createMarkerFromJson, 'json').done(function(){getMarkerDataCallback();});
}

function createMarkerFromJson(obj, ajaxStatus)
{
	customIcon = createCustomIcon(obj);
	L.marker(obj.data.latLng, {icon: customIcon}).addTo(map).bindPopup("I am a green leaf.");;
	currentMarkers[obj.data.id] = obj.data.latLng;

	addMarkerToRoute();
}

function createPopupMarkup(obj) {
	popupHtml=document.createElement('DIV');

	$(popupHtml).append(obj.data.name);
}

function addMarkerToRoute() {
	plottedPolyline = L.Polyline.Plotter(currentMarkers,{weight: 5}).addTo(map);
}

function createCustomIcon(obj) {
	var customIcon = L.icon({
	    iconUrl: obj.data.flag,

	    iconSize:     [38, 95], // size of the icon
	    shadowSize:   [50, 64], // size of the shadow
	    iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
	    shadowAnchor: [4, 62],  // the same for the shadow
	    popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
	});

	return customIcon;
}

function getMarkerDataCallback() {

}<|endoftext|>


<commit_before>var expect = require("expect.js");

var HTMLHint = require("../../../index").HTMLHint;

var ruldId = 'vertical-containers-acceessibility',
    ruleOptions = {};

ruleOptions[ruldId] = true;

describe('Rules: ' + ruldId, function () {

    it('div with id "user" without "setRoleTabList" binding should result in an error', function () {
        var code = '

';
        var messages = HTMLHint.verify(code, ruleOptions);
        expect(messages.length).to.be(1);
        expect(messages[0].rule.id).to.be(ruldId);
        expect(messages[0].line).to.be(1);
        expect(messages[0].col).to.be(1);
    });

    it('div with id "user" without "setRoleTabList" binding should not result in an error', function () {
        var code = '

';
        var messages = HTMLHint.verify(code, ruleOptions);
        expect(messages.length).to.be(0);
    });

});<commit_msg>another fix in spec title<commit_after>var expect = require("expect.js");

var HTMLHint = require("../../../index").HTMLHint;

var ruldId = 'vertical-containers-acceessibility',
    ruleOptions = {};

ruleOptions[ruldId] = true;

describe('Rules: ' + ruldId, function () {

    it('div with id "user" without "setRoleTabList" binding should result in an error', function () {
        var code = '

';
        var messages = HTMLHint.verify(code, ruleOptions);
        expect(messages.length).to.be(1);
        expect(messages[0].rule.id).to.be(ruldId);
        expect(messages[0].line).to.be(1);
        expect(messages[0].col).to.be(1);
    });

    it('div with id "user" with "setRoleTabList" binding should not result in an error', function () {
        var code = '

';
        var messages = HTMLHint.verify(code, ruleOptions);
        expect(messages.length).to.be(0);
    });

});<|endoftext|>


<commit_before>var inside = require('turf-inside');

/**
 * Calculates the average value of a field for a set of {@link Point} features within a set of {@link Polygon} features.
 *
 * @module turf/average
 * @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
 * @param {FeatureCollection} points a FeatureCollection of {@link Point} features
 * @param {string} field the field in the `points` features from which to pull values to average
 * @param {string} outputField the field in the `polygons` FeatureCollection to put results of the averages
 * @return {FeatureCollection} a FeatureCollection of {@link Polygon} features with the value of `outField` set to the calculated average
 * @example
 * var polygons = turf.featurecollection([
 *  turf.polygon([[
 *    [10.666351, 59.890659],
 *    [10.666351, 59.936784],
 *    [10.762481, 59.936784],
 *    [10.762481, 59.890659],
 *    [10.666351, 59.890659]
 *  ]]),
 *  turf.polygon([[
 *    [10.764541, 59.889281],
 *    [10.764541, 59.937128],
 *    [10.866165, 59.937128],
 *    [10.866165, 59.889281],
 *    [10.764541, 59.889281]
 *  ]])
 * ]);
 * var points = turf.featurecollection([
 *  turf.point([10.724029, 59.926807], {population: 200}),
 *  turf.point([10.715789, 59.904778], {population: 600}),
 *  turf.point([10.746002, 59.908566], {population: 100}),
 *  turf.point([10.806427, 59.908910], {population: 200}),
 *  turf.point([10.79544, 59.931624], {population: 300})
 * ]);
 *
 * var averaged = turf.average(
 *  polygons, points, 'population', 'pop_avg');
 *
 * var result = turf.featurecollection(
 *  points.features.concat(averaged.features));
 *
 * //=result
 */
module.exports = function(polyFC, ptFC, inField, outField, done){
  polyFC.features.forEach(function(poly){
    if(!poly.properties) poly.properties = {};
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) values.push(pt.properties[inField]);
    });
    poly.properties[outField] = average(values);
  });

  return polyFC;
}

function average(values) {
  var sum = 0;
  for (var i = 0; i < values.length; i++) {
    sum += values[i];
  }
  return sum / values.length;
}
<commit_msg>Switch example to geojson primitives<commit_after>var inside = require('turf-inside');

/**
 * Calculates the average value of a field for a set of {@link Point} features within a set of {@link Polygon} features.
 *
 * @module turf/average
 * @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
 * @param {FeatureCollection} points a FeatureCollection of {@link Point} features
 * @param {string} field the field in the `points` features from which to pull values to average
 * @param {string} outputField the field in the `polygons` FeatureCollection to put results of the averages
 * @return {FeatureCollection} a FeatureCollection of {@link Polygon} features with the value of `outField` set to the calculated average
 * @example
* var polygons = {
 *   "type": "FeatureCollection",
 *   "features": [
 *     {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Polygon",
 *         "coordinates": [[
 *           [10.666351, 59.890659],
 *           [10.666351, 59.936784],
 *           [10.762481, 59.936784],
 *           [10.762481, 59.890659],
 *           [10.666351, 59.890659]
 *         ]]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Polygon",
 *         "coordinates": [[
 *           [10.764541, 59.889281],
 *           [10.764541, 59.937128],
 *           [10.866165, 59.937128],
 *           [10.866165, 59.889281],
 *           [10.764541, 59.889281]
 *         ]]
 *       }
 *     }
 *   ]
 * };
 * var points = {
 *   "type": "FeatureCollection",
 *   "features": [
 *     {
 *       "type": "Feature",
 *       "properties": {
 *         "population": 200
 *       },
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [10.724029, 59.926807]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {
 *         "population": 600
 *       },
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [10.715789, 59.904778]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {
 *         "population": 100
 *       },
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [10.746002, 59.908566]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {
 *         "population": 200
 *       },
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [10.806427, 59.908910]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {
 *         "population": 300
 *       },
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [10.79544, 59.931624]
 *       }
 *     }
 *   ]
 * };
 *
 * var averaged = turf.average(
 *  polygons, points, 'population', 'pop_avg');
 *
 * var resultFeatures = points.features.concat(
 *   averaged.features);
 * var result = {
 *   "type": "FeatureCollection",
 *   "features": resultFeatures
 * };
 *
 * //=result
 */
module.exports = function(polyFC, ptFC, inField, outField, done){
  polyFC.features.forEach(function(poly){
    if(!poly.properties) poly.properties = {};
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) values.push(pt.properties[inField]);
    });
    poly.properties[outField] = average(values);
  });

  return polyFC;
}

function average(values) {
  var sum = 0;
  for (var i = 0; i < values.length; i++) {
    sum += values[i];
  }
  return sum / values.length;
}
<|endoftext|>


<commit_before>$(function() {

  // Instances
  App.users = new App.Users;

  App.posts = new App.Posts;

  App.tags = new App.Tags;

  App.session = new App.Session;

  App.settings = new App.Settings;

  App.postForm = new App.FormView({
    name: 'posts',
    collection: App.posts,
    fields: {
      title: {type: 'string', label: 'Title'},
      summary: {type: 'text', label: 'Summary'},
      body: {type: 'text', label: 'Body'},
      published: {type: 'boolean', label: 'Published'}
    }
  });

  App.userForm = new App.FormView({
    name: 'users',
    collection: App.users,
    fields: {
      username: {type: 'string', label: 'Username'},
      firstname: {type: 'string', label: 'First name'},
      lastname: {type: 'string', label: 'Last name'},
      email: {type: 'string', label: 'Email'},
      isStaff: {type: 'boolean', label: 'Is staff'}
    }
  });

  App.settingsForm = new App.FormView({
    name: 'settings',
    model: App.settings,
    fields: {
      SITE_TITLE: {type: 'string', label: 'Site title'},
      DB: {type: 'string', label: 'Database'},
      TIME_ZONE: {type: 'string', label: 'Time zone'},
      SITE_URL: {type: 'string', label: 'Site url'},
      POSTS_BY_PAGE: {type: 'int', label: 'Post by page'}
    }
  });

  App.tagForm = new App.FormView({
    name: 'tags',
    collection: App.tags,
    fields: {
      title: {type: 'string', label: 'Title'}
    }
  });

  App.postsView = new App.ListView({
    collection: App.posts,
    name: 'posts',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Created at', 'value': 'created_at', 'type': 'date'},
      {'label': 'Published', 'value': 'published', 'type': 'bool'}
    ]
  });

  App.tagsView = new App.ListView({
    collection: App.tags,
    name: 'tags',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Posts', 'value': 'count'}
    ]
  });

  App.usersView = new App.ListView({
    collection: App.users,
    name: 'users',
    columns: [
      {'label': 'Username', 'value': 'username'},
      {'label': 'Created at', 'value': 'created_at', 'type': 'date'},
      {'label': 'Is staff', 'value': 'isStaff', 'type': 'bool'}
    ]
  });

  App.tagEditorView = new App.TagEditorView({
    view: App.postForm
  });

  App.userView = new App.UserView({
    model: App.session
  });

  App.menuView = new App.MenuView;

  App.dashboardView = new App.DashBoardView;

  App.alertView = new App.AlertView;

  App.region = new App.Region;

  App.router = new App.Router;

  // Router
  App.router.on('all', function routeAll(route) {
    var name = route.split(':')[1];
    if(name) {
      App.menuView.select(name);
    }
  });

  App.postForm.construct();
  App.userForm.construct();
  App.tagForm.construct();
  App.settingsForm.construct();
  Backbone.history.start();
  App.session.fetch();
  App.settings.fetch();
});<commit_msg>Patch Zepto with simply-deferred<commit_after>$(function() {
  Deferred.installInto(Zepto);

  // Instances
  App.users = new App.Users;

  App.posts = new App.Posts;

  App.tags = new App.Tags;

  App.session = new App.Session;

  App.settings = new App.Settings;

  App.postForm = new App.FormView({
    name: 'posts',
    collection: App.posts,
    fields: {
      title: {type: 'string', label: 'Title'},
      summary: {type: 'text', label: 'Summary'},
      body: {type: 'text', label: 'Body'},
      published: {type: 'boolean', label: 'Published'}
    }
  });

  App.userForm = new App.FormView({
    name: 'users',
    collection: App.users,
    fields: {
      username: {type: 'string', label: 'Username'},
      firstname: {type: 'string', label: 'First name'},
      lastname: {type: 'string', label: 'Last name'},
      email: {type: 'string', label: 'Email'},
      isStaff: {type: 'boolean', label: 'Is staff'}
    }
  });

  App.settingsForm = new App.FormView({
    name: 'settings',
    model: App.settings,
    fields: {
      SITE_TITLE: {type: 'string', label: 'Site title'},
      DB: {type: 'string', label: 'Database'},
      TIME_ZONE: {type: 'string', label: 'Time zone'},
      SITE_URL: {type: 'string', label: 'Site url'},
      POSTS_BY_PAGE: {type: 'int', label: 'Post by page'}
    }
  });

  App.tagForm = new App.FormView({
    name: 'tags',
    collection: App.tags,
    fields: {
      title: {type: 'string', label: 'Title'}
    }
  });

  App.postsView = new App.ListView({
    collection: App.posts,
    name: 'posts',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Created at', 'value': 'created_at', 'type': 'date'},
      {'label': 'Published', 'value': 'published', 'type': 'bool'}
    ]
  });

  App.tagsView = new App.ListView({
    collection: App.tags,
    name: 'tags',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Posts', 'value': 'count'}
    ]
  });

  App.usersView = new App.ListView({
    collection: App.users,
    name: 'users',
    columns: [
      {'label': 'Username', 'value': 'username'},
      {'label': 'Created at', 'value': 'created_at', 'type': 'date'},
      {'label': 'Is staff', 'value': 'isStaff', 'type': 'bool'}
    ]
  });

  App.tagEditorView = new App.TagEditorView({
    view: App.postForm
  });

  App.userView = new App.UserView({
    model: App.session
  });

  App.menuView = new App.MenuView;

  App.dashboardView = new App.DashBoardView;

  App.alertView = new App.AlertView;

  App.region = new App.Region;

  App.router = new App.Router;

  // Router
  App.router.on('all', function routeAll(route) {
    var name = route.split(':')[1];
    if(name) {
      App.menuView.select(name);
    }
  });

  App.postForm.construct();
  App.userForm.construct();
  App.tagForm.construct();
  App.settingsForm.construct();
  Backbone.history.start();
  App.session.fetch();
  App.settings.fetch();
});<|endoftext|>