<commit_before>var map, featureList, stationsGeoJson, stationSearch = [];

/*************/
/* functions */
/*************/

function onMapClick(evt) {
    var latlon = evt.latlng;
    var lat = latlon.lat;
    var lon = latlon.lng;

    var pt = turf.point([lon, lat]);
    var unit = 'kilometers';
    var radius = 25;
    var buffered = turf.buffer(pt, radius, unit);

    var circle = L.circle([lat, lon], radius * 1000, {
      stroke: true,
      color: "#000",
      opacity: 0.75,
      weight: 2,
      fillColor: "#555555",
      fillOpacity: 0.5
    });
    bufferedLayer.clearLayers().addLayer(circle);
    var fc = turf.featurecollection(stations);
    var ptsWithin = turf.within(stationsGeoJson, buffered);

    var content = 'Within a ' + radius + ' km radius from ' +
      '(' + lat.toFixed(5) + ',' + lon.toFixed(5) + ')
' +
      'There is ' + ptsWithin.features.length + ' stations

' +
      '<button id="clear-btn" type="button" class="btn btn-default">Clear</button>';

    //$("#feature-info").html(content);
    //$("#feature-info-wrapper").show();

    highlight.clearLayers();
    for (var i = 0; i < ptsWithin.features.length; i++) {
      highlight.addLayer(L.circleMarker([ptsWithin.features[i].geometry.coordinates[1], ptsWithin.features[i].geometry.coordinates[0]], highlightStyle));
    }

    $("#clear-btn").click(function() {
      $("#feature-info-wrapper").hide();
      highlight.clearLayers();
      bufferedLayer.clearLayers();
    });
  } //end function onMapClick

function sizeLayerControl() {
  $(".leaflet-control-layers").css("max-height", $("#map").height() - 50);
}

function clearHighlight() {
  highlight.clearLayers();
  bufferedLayer.clearLayers();
}

function sidebarClick(id) {
  var layer = markers.getLayer(id);
  map.setView([layer.getLatLng().lat, layer.getLatLng().lng], 17);
  layer.fire("click");
  /* Hide sidebar and go to the map on small screens */
  if (document.body.clientWidth <= 767) {
    $("#sidebar").hide();
    map.invalidateSize();
  }
}

function syncSidebar() {
  /* Empty sidebar features */
  $("#feature-list tbody").empty();
  /* Loop through stationss layer and add only features which are in the map bounds */
  stations.eachLayer(function(layer) {
    if (map.getBounds().contains(layer.getLatLng())) {
      $("#feature-list tbody").append(getFeatureListContent(layer));
    }

  });
  /* Update list.js featureList */
  featureList = new List("features", {
    valueNames: ["feature-name"]
  });
  featureList.sort("feature-name", {
    order: "asc"
  });
}

function getFeatureListContent(layer) {
  var name = layer.feature.properties.nom_porteur;
  if(layer.feature.properties.nom_station !== '' ) {
    name = name + ' ' +layer.feature.properties.nom_station;
  }
  return '
		' + name +
    '
';
}

/***************/
/* wire events */
/***************/
$(window).resize(function() {
  sizeLayerControl();
});

$(document).on("click", ".feature-row", function(e) {
  $(document).off("mouseout", ".feature-row", clearHighlight);
  sidebarClick(parseInt($(this).attr("id"), 10));
});

$(document).on("mouseover", ".feature-row", function(e) {
  highlight.clearLayers().addLayer(L.circleMarker([$(this).attr("lat"), $(this).attr("lng")], highlightStyle));
});

$(document).on("mouseout", ".feature-row", clearHighlight);

$("#about-btn").click(function() {
  $("#aboutModal").modal("show");
  $(".navbar-collapse.in").collapse("hide");
  return false;
});

$("#list-btn").click(function() {
  $('#sidebar').toggle();
  map.invalidateSize();
  return false;
});

$("#nav-btn").click(function() {
  $(".navbar-collapse").collapse("toggle");
  return false;
});

$("#sidebar-toggle-btn").click(function() {
  $("#sidebar").toggle();
  map.invalidateSize();
  return false;
});

$("#sidebar-hide-btn").click(function() {
  $('#sidebar').hide();
  map.invalidateSize();
});

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

/* Prevent hitting enter from refreshing the page */
$("#searchbox").keypress(function (e) {
  if (e.which === 13) {
    e.preventDefault();
  }
});

$("#featureModal").on("hidden.bs.modal", function (e) {
  $(document).on("mouseout", ".feature-row", clearHighlight);
});

/*******************/
/* let's do maps ! */
/*******************/

/* Overlay Layers */
var highlight = L.geoJson(null);
var highlightStyle = {
  stroke: false,
  fillColor: "#00FFFF",
  fillOpacity: 0.7,
  radius: 10
};

var bufferedLayer = L.layerGroup(null);

var markers = new L.MarkerClusterGroup({
  spiderfyOnMaxZoom: true,
  showCoverageOnHover: false,
  zoomToBoundsOnClick: true,
  disableClusteringAtZoom: 15
});

var stations = L.geoJson(null, {
  pointToLayer: function(feature, latlng) {
    return L.marker(latlng, {
      icon: L.AwesomeMarkers.icon({
        icon: 'plug',
        prefix: 'fa',
        markerColor: 'green'
      }),
      title: feature.properties.nom_station,
      riseOnHover: true
    });
  },
  onEachFeature: function(feature, layer) {
    if (feature.properties) {
      // var content = "
" + "
Name	" + feature.properties.nom_station + "
" + "
Holder	" + feature.properties.nom_porteur + "
" +
      //   "
Address	" + feature.properties.adresse_station + "
" + "
";
      var content = "

";
      var out = [];
      //var regexp = new RegExp('^http');
      var value;
      if (feature.properties) {
        for (var key in feature.properties) {
          out.push("
" + key + "	" + feature.properties[key]);
        }
        content = content + out.join("
") + "

";
        layer.bindPopup(content);
      }
      layer.on({
        click: function(e) {
          // $("#feature-title").html(feature.properties.nom_station);
          // $("#feature-info").html(content);
          // $("#featureModal").modal("show");
          highlight.clearLayers().addLayer(L.circleMarker([feature.geometry.coordinates[1], feature.geometry.coordinates[0]], highlightStyle));
        }
      });
      $("#feature-list tbody").append(getFeatureListContent(layer));
      stationSearch.push({
        name: layer.feature.properties.nom_station,
        address: layer.feature.properties.adresse_station,
        source: "Stations",
        id: L.stamp(layer),
        lat: layer.feature.geometry.coordinates[1],
        lng: layer.feature.geometry.coordinates[0]
      });
    }
  }
});
$.getJSON("data/evse.geojson", function(data) {
  stations.addData(data);
  markers.addLayer(stations);
  stationsGeoJson = data;
});

var topo = L.esri.basemapLayer('Topographic', {
  detectRetina: true
});

var lat = 46.6;
var lng = 2.3;
var zoom = 6;

map = L.map('leaflet-map', {
  center: [lat, lng],
  zoom: zoom,
  defaultExtentControl: true,
  layers: [topo, markers, highlight, bufferedLayer]
});

L.control.locate().addTo(map);

// add geocoder
var searchControl = new L.esri.Geocoding.Controls.Geosearch().addTo(map);
searchControl.on('results', function(data) {
  var result = data.results[0];
  map.panTo(result.latlng);
  L.popup()
    .setLatLng(result.latlng)
    .setContent(result.text)
    .openOn(map);
});
/////////////////

/* Filter sidebar feature list to only show features in current map bounds */
map.on("moveend", function (e) {
  syncSidebar();
});

map.on('click', onMapClick);

$(document).one("ajaxStop", function() {
  $("#loading").hide();
  sizeLayerControl();
  //map.fitBounds(stations.getBounds());

  featureList = new List("features", {valueNames: ["feature-name"]});
  featureList.sort("feature-name", {order:"asc"});

  var stationsBH = new Bloodhound({
    name: "Stations",
    datumTokenizer: function (d) {
      return Bloodhound.tokenizers.whitespace(d.name);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: stationSearch,
    limit: 10
  });

  stationsBH.initialize();

  /* instantiate the typeahead UI */
  $("#searchbox").typeahead({
    minLength: 3,
    highlight: true,
    hint: false
  }, {
    name: "Stations",
    displayKey: "name",
    source: stationsBH.ttAdapter(),
    templates: {
      header: "
 Stations
",
      suggestion: Handlebars.compile(["{{name}}
 {{address}}"].join(""))
    }
  }).on("typeahead:selected", function(obj, datum) {
    if (datum.source === "Stations") {
      map.setView([datum.lat, datum.lng], 17);
      if (map._layers[datum.id]) {
        map._layers[datum.id].fire("click");
      }
    }
    if ($(".navbar-collapse").height() > 50) {
      $(".navbar-collapse").collapse("hide");
    }
  }).on("typeahead:opened", function() {
    $(".navbar-collapse.in").css("max-height", $(document).height() - $(".navbar-header").height());
    $(".navbar-collapse.in").css("height", $(document).height() - $(".navbar-header").height());
  }).on("typeahead:closed", function() {
    $(".navbar-collapse.in").css("max-height", "");
    $(".navbar-collapse.in").css("height", "");
  });
  $(".twitter-typeahead").css("position", "static");
  $(".twitter-typeahead").css("display", "block");

});

// Leaflet patch to make layer control scrollable on touch browsers
// var container = $(".leaflet-control-layers")[0];
// if (!L.Browser.touch) {
//   L.DomEvent
//     .disableClickPropagation(container)
//     .disableScrollPropagation(container);
// } else {
//   L.DomEvent.disableClickPropagation(container);
// }
<commit_msg>typehead with porteur<commit_after>var map, featureList, stationsGeoJson, stationSearch = [];

/*************/
/* functions */
/*************/

function onMapClick(evt) {
    var latlon = evt.latlng;
    var lat = latlon.lat;
    var lon = latlon.lng;

    var pt = turf.point([lon, lat]);
    var unit = 'kilometers';
    var radius = 25;
    var buffered = turf.buffer(pt, radius, unit);

    var circle = L.circle([lat, lon], radius * 1000, {
      stroke: true,
      color: "#000",
      opacity: 0.75,
      weight: 2,
      fillColor: "#555555",
      fillOpacity: 0.5
    });
    bufferedLayer.clearLayers().addLayer(circle);
    var fc = turf.featurecollection(stations);
    var ptsWithin = turf.within(stationsGeoJson, buffered);

    var content = 'Within a ' + radius + ' km radius from ' +
      '(' + lat.toFixed(5) + ',' + lon.toFixed(5) + ')
' +
      'There is ' + ptsWithin.features.length + ' stations

' +
      '<button id="clear-btn" type="button" class="btn btn-default">Clear</button>';

    //$("#feature-info").html(content);
    //$("#feature-info-wrapper").show();

    highlight.clearLayers();
    for (var i = 0; i < ptsWithin.features.length; i++) {
      highlight.addLayer(L.circleMarker([ptsWithin.features[i].geometry.coordinates[1], ptsWithin.features[i].geometry.coordinates[0]], highlightStyle));
    }

    $("#clear-btn").click(function() {
      $("#feature-info-wrapper").hide();
      highlight.clearLayers();
      bufferedLayer.clearLayers();
    });
  } //end function onMapClick

function sizeLayerControl() {
  $(".leaflet-control-layers").css("max-height", $("#map").height() - 50);
}

function clearHighlight() {
  highlight.clearLayers();
  bufferedLayer.clearLayers();
}

function sidebarClick(id) {
  var layer = markers.getLayer(id);
  map.setView([layer.getLatLng().lat, layer.getLatLng().lng], 17);
  layer.fire("click");
  /* Hide sidebar and go to the map on small screens */
  if (document.body.clientWidth <= 767) {
    $("#sidebar").hide();
    map.invalidateSize();
  }
}

function syncSidebar() {
  /* Empty sidebar features */
  $("#feature-list tbody").empty();
  /* Loop through stationss layer and add only features which are in the map bounds */
  stations.eachLayer(function(layer) {
    if (map.getBounds().contains(layer.getLatLng())) {
      $("#feature-list tbody").append(getFeatureListContent(layer));
    }
  });
  /* Update list.js featureList */
  featureList = new List("features", {
    valueNames: ["feature-name"]
  });
  featureList.sort("feature-name", {
    order: "asc"
  });
}

function getFeatureListContent(layer) {
  var name = layer.feature.properties.nom_porteur;
  if (layer.feature.properties.nom_station !== '') {
    name = name + ' ' + layer.feature.properties.nom_station;
  }
  return '
		' + name + '
';
}

/***************/
/* wire events */
/***************/
$(window).resize(function() {
  sizeLayerControl();
});

$(document).on("click", ".feature-row", function(e) {
  $(document).off("mouseout", ".feature-row", clearHighlight);
  sidebarClick(parseInt($(this).attr("id"), 10));
});

$(document).on("mouseover", ".feature-row", function(e) {
  highlight.clearLayers().addLayer(L.circleMarker([$(this).attr("lat"), $(this).attr("lng")], highlightStyle));
});

$(document).on("mouseout", ".feature-row", clearHighlight);

$("#about-btn").click(function() {
  $("#aboutModal").modal("show");
  $(".navbar-collapse.in").collapse("hide");
  return false;
});

$("#list-btn").click(function() {
  $('#sidebar').toggle();
  map.invalidateSize();
  return false;
});

$("#nav-btn").click(function() {
  $(".navbar-collapse").collapse("toggle");
  return false;
});

$("#sidebar-toggle-btn").click(function() {
  $("#sidebar").toggle();
  map.invalidateSize();
  return false;
});

$("#sidebar-hide-btn").click(function() {
  $('#sidebar').hide();
  map.invalidateSize();
});

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

/* Prevent hitting enter from refreshing the page */
$("#searchbox").keypress(function(e) {
  if (e.which === 13) {
    e.preventDefault();
  }
});

$("#featureModal").on("hidden.bs.modal", function(e) {
  $(document).on("mouseout", ".feature-row", clearHighlight);
});

/*******************/
/* let's do maps ! */
/*******************/

/* Overlay Layers */
var highlight = L.geoJson(null);
var highlightStyle = {
  stroke: false,
  fillColor: "#00FFFF",
  fillOpacity: 0.7,
  radius: 10
};

var bufferedLayer = L.layerGroup(null);

var markers = new L.MarkerClusterGroup({
  spiderfyOnMaxZoom: true,
  showCoverageOnHover: false,
  zoomToBoundsOnClick: true,
  disableClusteringAtZoom: 15
});

var stations = L.geoJson(null, {
  pointToLayer: function(feature, latlng) {
    return L.marker(latlng, {
      icon: L.AwesomeMarkers.icon({
        icon: 'plug',
        prefix: 'fa',
        markerColor: 'green'
      }),
      title: feature.properties.nom_station,
      riseOnHover: true
    });
  },
  onEachFeature: function(feature, layer) {
    if (feature.properties) {
      // var content = "
" + "
Name	" + feature.properties.nom_station + "
" + "
Holder	" + feature.properties.nom_porteur + "
" +
      //   "
Address	" + feature.properties.adresse_station + "
" + "
";
      var content = "

"; // defini ici opur etre utilise dans layer.on(click)
      var out = [];
      var value;
      if (feature.properties) {
        for (var key in feature.properties) {
          out.push("
" + key + "	" + feature.properties[key]);
        }
        content = content + out.join("
") + "

";
        layer.bindPopup(content);
      }
      layer.on({
        click: function(e) {
          // $("#feature-title").html(feature.properties.nom_station);
          // $("#feature-info").html(content);
          // $("#featureModal").modal("show");
          highlight.clearLayers().addLayer(L.circleMarker([feature.geometry.coordinates[1], feature.geometry.coordinates[0]], highlightStyle));
        }
      });
      $("#feature-list tbody").append(getFeatureListContent(layer));
      stationSearch.push({
        name: layer.feature.properties.nom_porteur  + ' ' + layer.feature.properties.nom_station,
        address: layer.feature.properties.adresse_station,
        source: "Stations",
        id: L.stamp(layer),
        lat: layer.feature.geometry.coordinates[1],
        lng: layer.feature.geometry.coordinates[0]
      });
    }
  }
});
$.getJSON("data/evse.geojson", function(data) {
  stations.addData(data);
  markers.addLayer(stations);
  stationsGeoJson = data;
});

var topo = L.esri.basemapLayer('Topographic', {
  detectRetina: true
});

var lat = 46.6;
var lng = 2.3;
var zoom = 6;

map = L.map('leaflet-map', {
  center: [lat, lng],
  zoom: zoom,
  defaultExtentControl: true,
  layers: [topo, markers, highlight, bufferedLayer]
});

L.control.locate().addTo(map);

// add geocoder
var searchControl = new L.esri.Geocoding.Controls.Geosearch().addTo(map);
searchControl.on('results', function(data) {
  var result = data.results[0];
  map.panTo(result.latlng);
  L.popup()
    .setLatLng(result.latlng)
    .setContent(result.text)
    .openOn(map);
});
/////////////////

/* Filter sidebar feature list to only show features in current map bounds */
map.on("moveend", function(e) {
  syncSidebar();
});

map.on('click', onMapClick);

$(document).one("ajaxStop", function() {
  $("#loading").hide();
  sizeLayerControl();
  //map.fitBounds(stations.getBounds());

  featureList = new List("features", {
    valueNames: ["feature-name"]
  });
  featureList.sort("feature-name", {
    order: "asc"
  });

  var stationsBH = new Bloodhound({
    name: "Stations",
    datumTokenizer: function(d) {
      return Bloodhound.tokenizers.whitespace(d.name);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: stationSearch,
    limit: 10
  });

  stationsBH.initialize();

  /* instantiate the typeahead UI */
  $("#searchbox").typeahead({
    minLength: 3,
    highlight: true,
    hint: false
  }, {
    name: "Stations",
    displayKey: "name",
    source: stationsBH.ttAdapter(),
    templates: {
      header: "
 Stations
",
      suggestion: Handlebars.compile(["{{name}}
 {{address}}"].join(""))
    }
  }).on("typeahead:selected", function(obj, datum) {
    if (datum.source === "Stations") {
      map.setView([datum.lat, datum.lng], 17);
      if (map._layers[datum.id]) {
        map._layers[datum.id].fire("click");
      }
    }
    if ($(".navbar-collapse").height() > 50) {
      $(".navbar-collapse").collapse("hide");
    }
  }).on("typeahead:opened", function() {
    $(".navbar-collapse.in").css("max-height", $(document).height() - $(".navbar-header").height());
    $(".navbar-collapse.in").css("height", $(document).height() - $(".navbar-header").height());
  }).on("typeahead:closed", function() {
    $(".navbar-collapse.in").css("max-height", "");
    $(".navbar-collapse.in").css("height", "");
  });
  $(".twitter-typeahead").css("position", "static");
  $(".twitter-typeahead").css("display", "block");

});
<|endoftext|>


<commit_before>var generators = require('yeoman-generator')

module.exports = generators.Base.extend({

  initializing: function () {
    this.pkg = require('../../package.json')
  },

  prompting: function () {
    var done = this.async()
    this.prompt([{
      type    : 'input',
      name    : 'apiName',
      message : 'Your API name',
      default : this.appname
    },{
      type    : 'input',
      name    : 'authorName',
      message : 'Author name',
      default : 'John Doe'
    },{
      type    : 'input',
      name    : 'authorEmail',
      message : 'Author email',
      default : 'developer@example.com'
    }], function (answers) {
      this.props = answers
      done()
    }.bind(this))
  },

  writing: {
    app: function () {

      var context = {
        API_NAME: this.props.apiName,
        AUTHOR_NAME: this.props.authorName,
        AUTHOR_EMAIL: this.props.authorEmail
      }

      this.fs.copyTpl(
        this.templatePath('package.json'),
        this.destinationPath('package.json'),
        context
      )

      this.fs.copy(
        this.templatePath('db-*'),
        this.destinationPath('.')
      )

      this.copy('test.js')
      this.copy('README.md', 'README.md', context)

      this.directory('src')
      this.directory('migrations')
      this.directory('test')
    },

    configfiles: function () {
      this.copy('_gitignore', '.gitignore')
      this.copy('_env', '.env')
      this.copy('_env-test', '.env-test')
      this.copy('_env', '.env.example')
      this.copy('_travis.yml', '.travis.yml')
      this.copy('.editorconfig')
      this.copy('.eslintrc.json')
    }
  }
})
<commit_msg>Remember author name and email parameters<commit_after>var generators = require('yeoman-generator')

module.exports = generators.Base.extend({

  initializing: function () {
    this.pkg = require('../../package.json')
  },

  prompting: function () {
    var done = this.async()
    this.prompt([{
      type    : 'input',
      name    : 'apiName',
      message : 'Your API name',
      default : this.appname
    },{
      type    : 'input',
      name    : 'authorName',
      message : 'Author name',
      default : 'John Doe',
      store   : true
    },{
      type    : 'input',
      name    : 'authorEmail',
      message : 'Author email',
      default : 'developer@example.com',
      store   : true
    }], function (answers) {
      this.props = answers
      done()
    }.bind(this))
  },

  writing: {
    app: function () {

      var context = {
        API_NAME: this.props.apiName,
        AUTHOR_NAME: this.props.authorName,
        AUTHOR_EMAIL: this.props.authorEmail
      }

      this.fs.copyTpl(
        this.templatePath('package.json'),
        this.destinationPath('package.json'),
        context
      )

      this.fs.copy(
        this.templatePath('db-*'),
        this.destinationPath('.')
      )

      this.copy('test.js')
      this.copy('README.md', 'README.md', context)

      this.directory('src')
      this.directory('migrations')
      this.directory('test')
    },

    configfiles: function () {
      this.copy('_gitignore', '.gitignore')
      this.copy('_env', '.env')
      this.copy('_env-test', '.env-test')
      this.copy('_env', '.env.example')
      this.copy('_travis.yml', '.travis.yml')
      this.copy('.editorconfig')
      this.copy('.eslintrc.json')
    }
  }
})
<|endoftext|>


<commit_before>
//
// cmd like
//   { action: "actionname", "source":"whofrom",target:"who against"}
//

var heads = {
    "hamlet":{x:660,y:253},
    "gertrude":{x:480,y:230},
    "ophelia":{x:130,y:280},
    "claudius":{x:300,y:260}

}
var courseFood = {
    "first":"soup",
    "second":"salad",
    "main":"meat"
};

function showState(cmd){
    console.log("in art showState");
    console.log(cmd);
}

function showAction(cmd){
    console.log("in art showAction");
    console.log(cmd);
    if (cmd.target == "all") return;  // temporary hack to enable testing
    if(cmd.actiontype == "dagger"){
        throwSomething("dagger",true,heads[cmd.source].x,heads[cmd.source].y,heads[cmd.target].x,heads[cmd.target].y);
    }
    if(cmd.actiontype == "heart"){
        throwSomething("heart",false,heads[cmd.source].x,heads[cmd.source].y,heads[cmd.target].x,heads[cmd.target].y);
    }
    //speak, source, topic
}

function throwSomething(thing,rotate,sourceX,sourceY,targetX,targetY){

        var $dagger = $("

");
        //which way to point the dagger based on who is sitting left or right
        //transform:rotate(210deg);
        if(rotate && sourceX != targetX){
            var rotation = 270;
            if(sourceX > targetX) rotation = 90;
            $dagger.css("transform","rotate("+rotation+"deg)");
        }
        $dagger.css("left",sourceX+"px");
        $dagger.css("top",sourceY+"px");
        $("#stage").append($dagger);
        $dagger.animate({"top":targetY,"left":targetX},2000,"linear",function(){
            $(this).remove()
        });

}

function displayCourse(courseName){
    $(".food").remove();

    var foodName = courseFood[courseName];
    var $stage = $("#stage");
    for(name in heads){
        var $npcplate = $(".plate."+name);
        var $food = $("

");
        console.log($npcplate.css("top"));
        $food.css("top",$npcplate.css("top"));
        $food.css("left",$npcplate.css("left"));
        $stage.append($food);

    }
    var $playerplate = $(".plate.player");
    var $food = $("

");
            $food.css("top",$playerplate.css("top"));
        $food.css("left",$playerplate.css("left"));
        $stage.append($food);

        $food.click(clickStage);

}

var responses = ["angry","conf","excited","neutral","susp"];

function displaySpeech(who,topic){
    var $balloon = $('
');
    var $img = $('');
    $balloon.append($img);

    for(var i = 0; i < responses.length; i++){
        var r = responses[i];
        var $res = $("

");

        $res.click(clickResponse)
        $balloon.append($res);
    }

    $("#stage").append($balloon);

                   /*

*/
}

function clickResponse(){

}

function clickStage(e){
    alert("class:"+$(this).attr("class")+"\nid:"+$(this).attr('id'));

}

<commit_msg>clickevent<commit_after>
//
// cmd like
//   { action: "actionname", "source":"whofrom",target:"who against"}
//

var heads = {
    "hamlet":{x:660,y:253},
    "gertrude":{x:480,y:230},
    "ophelia":{x:130,y:280},
    "claudius":{x:300,y:260}

}
var courseFood = {
    "first":"soup",
    "second":"salad",
    "main":"meat"
};

function showState(cmd){
    console.log("in art showState");
    console.log(cmd);
}

function showAction(cmd){
    console.log("in art showAction");
    console.log(cmd);
    if (cmd.target == "all") return;  // temporary hack to enable testing
    if(cmd.actiontype == "dagger"){
        throwSomething("dagger",true,heads[cmd.source].x,heads[cmd.source].y,heads[cmd.target].x,heads[cmd.target].y);
    }
    if(cmd.actiontype == "heart"){
        throwSomething("heart",false,heads[cmd.source].x,heads[cmd.source].y,heads[cmd.target].x,heads[cmd.target].y);
    }
    //speak, source, topic
}

function throwSomething(thing,rotate,sourceX,sourceY,targetX,targetY){

        var $dagger = $("

");
        //which way to point the dagger based on who is sitting left or right
        //transform:rotate(210deg);
        if(rotate && sourceX != targetX){
            var rotation = 270;
            if(sourceX > targetX) rotation = 90;
            $dagger.css("transform","rotate("+rotation+"deg)");
        }
        $dagger.css("left",sourceX+"px");
        $dagger.css("top",sourceY+"px");
        $("#stage").append($dagger);
        $dagger.animate({"top":targetY,"left":targetX},2000,"linear",function(){
            $(this).remove()
        });

}

function displayCourse(courseName){
    $(".food").remove();

    var foodName = courseFood[courseName];
    var $stage = $("#stage");
    for(name in heads){
        var $npcplate = $(".plate."+name);
        var $food = $("

");
        console.log($npcplate.css("top"));
        $food.css("top",$npcplate.css("top"));
        $food.css("left",$npcplate.css("left"));
        $stage.append($food);

    }
    var $playerplate = $(".plate.player");
    var $food = $("

");
            $food.css("top",$playerplate.css("top"));
        $food.css("left",$playerplate.css("left"));
        $stage.append($food);

        $food.click(clickStage);

}

var responses = ["angry","conf","excited","neutral","susp"];

function displaySpeech(who,topic){
    var $balloon = $('
');
    var $img = $('');
    $balloon.append($img);

    for(var i = 0; i < responses.length; i++){
        var r = responses[i];
        var $res = $("

");

        $res.click(clickResponse)
        $balloon.append($res);
    }

    $("#stage").append($balloon);

                   /*

*/
}

function clickResponse(){

}

function clickStage(e){
    var cssClass = $(this).attr("class");
    var playerIdx = cssClass.lastIndexOf("player");
    if (playerIdx > 0) {
	GLOBALS.player.perform(cssClass.substring(0, playerIdx).trimRight());
    }
}

<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var normalizeUrl = require('normalize-url');
var mkdirp = require('mkdirp');

module.exports = yeoman.generators.Base.extend({
	prompting: function () {
		var done = this.async();

		var prompts = [{
			message: 'Please enter the name of the framework:',
			name: 'framework'
		}, {
			message: 'Please enter your name:',
			name: 'authorName',
			store: true
		}, {
			message: 'Please enter the URL of your website:',
			name: 'authorSite',
			store: true,
			filter: function (val) {
				return normalizeUrl(val);
			}
		}];

		this.prompt(prompts, function (props) {
			mkdirp('js');
			mkdirp('css');

			['readme.md', 'index.html', 'js/app.js', 'css/app.css'].forEach(function (file) {
				this.fs.copyTpl(this.templatePath(file), this.destinationPath(file), props);
			}.bind(this));

			this.fs.copy(this.templatePath('_package.json'), this.destinationPath('package.json'));

			done();
		}.bind(this));
	},

	install: function () {
		this.installDependencies({
			bower: false,
			skipInstall: this.options['skip-install']
		});
	}
});
<commit_msg>Require necessary options<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var normalizeUrl = require('normalize-url');
var mkdirp = require('mkdirp');

module.exports = yeoman.generators.Base.extend({
	prompting: function () {
		var done = this.async();

		var prompts = [{
			message: 'Please enter the name of the framework:',
			name: 'framework',
			validate: function (val) {
				return val.length > 0 ? true : 'A framework name is required';
			}
		}, {
			message: 'Please enter your name:',
			name: 'authorName',
			store: true,
			validate: function (val) {
				return val.length > 0 ? true : 'An author name is required';
			}
		}, {
			message: 'Please enter the URL of your website:',
			name: 'authorSite',
			store: true,
			validate: function (val) {
				return val.length > 0 ? true : 'An author site is required';
			},
			filter: function (val) {
				return normalizeUrl(val);
			}
		}];

		this.prompt(prompts, function (props) {
			mkdirp('js');
			mkdirp('css');

			['readme.md', 'index.html', 'js/app.js', 'css/app.css'].forEach(function (file) {
				this.fs.copyTpl(this.templatePath(file), this.destinationPath(file), props);
			}.bind(this));

			this.fs.copy(this.templatePath('_package.json'), this.destinationPath('package.json'));

			done();
		}.bind(this));
	},

	install: function () {
		this.installDependencies({
			bower: false,
			skipInstall: this.options['skip-install']
		});
	}
});
<|endoftext|>


<commit_before>'use strict';

const yeoman = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');

module.exports = yeoman.Base.extend({
  prompting: function() {

    this.log(yosay(`Welcome to the awe-inspiring ${chalk.red('generator-angular2-module')} generator!`));

    // TODO - auto generate these answers

    const required = val => !!val;

    const prompts = [{
      type: 'input',
      name: 'githubUsername',
      message: 'What is the github project organisation or username?',
      validate: required
    }, {
      type: 'input',
      name: 'githubRepoName',
      message: 'What is the github repository name?',
      default: this.appname
    }, {
      type: 'input',
      name: 'npmModuleName',
      message: 'What is the npm module name?',
      default: this.appname
    }, {
      type: 'input',
      name: 'moduleGlobal',
      message: 'What should the module be exported as on the window for users not using module bundlers?',
      validate: required
    }, {
      type: 'input',
      name: 'projectTitle',
      message: 'What is the human readable project title?',
      default: this.appname
    }, {
      type: 'input',
      name: 'projectDescription',
      message: 'What is the project description?'
    }, {
      type: 'input',
      name: 'authorName',
      message: 'What is the author name?'
    }];

    return this.prompt(prompts).then(props => {
      this.props = props;
    });
  },

  writing: function() {

    const folders = ['demo', 'src', 'test'];
    folders.forEach(folder => {
      this.fs.copyTpl(
        this.templatePath(`${folder}/**`),
        this.destinationPath(folder),
        this.props
      );
    });

    const files = [
      '.editorconfig',
      '.gitignore',
      '.travis.yml',
      'karma.conf.js',
      'LICENSE',
      'package.json',
      'README.md',
      'tsconfig.json',
      'tslint.json',
      'typedoc.json',
      'typings.json',
      'webpack.config.dist.js',
      'webpack.config.js'
    ];
    files.forEach(file => {
      this.fs.copyTpl(
        this.templatePath(file),
        this.destinationPath(file),
        this.props
      );
    });

    this.fs.copyTpl(
      this.templatePath('module-entry.ts'),
      this.destinationPath(`${this.props.npmModuleName}.ts`),
      this.props
    );

  },

  install: function() {
    this.npmInstall();
  }
});
<commit_msg>Use installDependencies instead of direct npm install<commit_after>'use strict';

const yeoman = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');

module.exports = yeoman.Base.extend({
  prompting: function() {

    this.log(yosay(`Welcome to the awe-inspiring ${chalk.red('generator-angular2-module')} generator!`));

    // TODO - auto generate these answers

    const required = val => !!val;

    const prompts = [{
      type: 'input',
      name: 'githubUsername',
      message: 'What is the github project organisation or username?',
      validate: required
    }, {
      type: 'input',
      name: 'githubRepoName',
      message: 'What is the github repository name?',
      default: this.appname
    }, {
      type: 'input',
      name: 'npmModuleName',
      message: 'What is the npm module name?',
      default: this.appname
    }, {
      type: 'input',
      name: 'moduleGlobal',
      message: 'What should the module be exported as on the window for users not using module bundlers?',
      validate: required
    }, {
      type: 'input',
      name: 'projectTitle',
      message: 'What is the human readable project title?',
      default: this.appname
    }, {
      type: 'input',
      name: 'projectDescription',
      message: 'What is the project description?'
    }, {
      type: 'input',
      name: 'authorName',
      message: 'What is the author name?'
    }];

    return this.prompt(prompts).then(props => {
      this.props = props;
    });
  },

  writing: function() {

    const folders = ['demo', 'src', 'test'];
    folders.forEach(folder => {
      this.fs.copyTpl(
        this.templatePath(`${folder}/**`),
        this.destinationPath(folder),
        this.props
      );
    });

    const files = [
      '.editorconfig',
      '.gitignore',
      '.travis.yml',
      'karma.conf.js',
      'LICENSE',
      'package.json',
      'README.md',
      'tsconfig.json',
      'tslint.json',
      'typedoc.json',
      'typings.json',
      'webpack.config.dist.js',
      'webpack.config.js'
    ];
    files.forEach(file => {
      this.fs.copyTpl(
        this.templatePath(file),
        this.destinationPath(file),
        this.props
      );
    });

    this.fs.copyTpl(
      this.templatePath('module-entry.ts'),
      this.destinationPath(`${this.props.npmModuleName}.ts`),
      this.props
    );

  },

  install: function() {
    this.installDependencies({bower: false});
  }
});
<|endoftext|>


<commit_before>define("ace/snippets/javascript",["require","exports","module"],function(e,t,n){"use strict";t.snippetText='# Prototype\nsnippet proto\n	${1:class_name}.prototype.${2:method_name} = function(${3:first_argument}) {\n		${4:// body...}\n	};\n# Function\nsnippet fun\n	function ${1?:function_name}(${2:argument}) {\n		${3:// body...}\n	}\n# Anonymous Function\nregex /((=)\\s*|(:)\\s*|(\\()|\\b)/f/(\\))?/\nsnippet f\n	function${M1?: ${1:functionName}}($2) {\n		${0:$TM_SELECTED_TEXT}\n	}${M2?;}${M3?,}${M4?)}\n# Immediate function\ntrigger \\(?f\\(\nendTrigger \\)?\nsnippet f(\n	(function(${1}) {\n		${0:${TM_SELECTED_TEXT:/* code */}}\n	}(${1}));\n# if\nsnippet if\n	if (${1:true}) {\n		${0}\n	}\n# if ... else\nsnippet ife\n	if (${1:true}) {\n		${2}\n	} else {\n		${0}\n	}\n# tertiary conditional\nsnippet ter\n	${1:/* condition */} ? ${2:a} : ${3:b}\n# switch\nsnippet switch\n	switch (${1:expression}) {\n		case \'${3:case}\':\n			${4:// code}\n			break;\n		${5}\n		default:\n			${2:// code}\n	}\n# case\nsnippet case\n	case \'${1:case}\':\n		${2:// code}\n		break;\n	${3}\n\n# while (...) {...}\nsnippet wh\n	while (${1:/* condition */}) {\n		${0:/* code */}\n	}\n# try\nsnippet try\n	try {\n		${0:/* code */}\n	} catch (e) {}\n# do...while\nsnippet do\n	do {\n		${2:/* code */}\n	} while (${1:/* condition */});\n# Object Method\nsnippet :f\nregex /([,{[])|^\\s*/:f/\n	${1:method_name}: function(${2:attribute}) {\n		${0}\n	}${3:,}\n# setTimeout function\nsnippet setTimeout\nregex /\\b/st|timeout|setTimeo?u?t?/\n	setTimeout(function() {${3:$TM_SELECTED_TEXT}}, ${1:10});\n# Get Elements\nsnippet gett\n	getElementsBy${1:TagName}(\'${2}\')${3}\n# Get Element\nsnippet get\n	getElementBy${1:Id}(\'${2}\')${3}\n# console.log (Firebug)\nsnippet cl\n	console.log(${1});\n# return\nsnippet ret\n	return ${1:result}\n# for (property in object ) { ... }\nsnippet fori\n	for (var ${1:prop} in ${2:Things}) {\n		${0:$2[$1]}\n	}\n# hasOwnProperty\nsnippet has\n	hasOwnProperty(${1})\n# docstring\nsnippet /**\n	/**\n	 * ${1:description}\n	 *\n	 */\nsnippet @par\nregex /^\\s*\\*\\s*/@(para?m?)?/\n	@param {${1:type}} ${2:name} ${3:description}\nsnippet @ret\n	@return {${1:type}} ${2:description}\n# JSON.parse\nsnippet jsonp\n	JSON.parse(${1:jstr});\n# JSON.stringify\nsnippet jsons\n	JSON.stringify(${1:object});\n# self-defining function\nsnippet sdf\n	var ${1:function_name} = function(${2:argument}) {\n		${3:// initial code ...}\n\n		$1 = function($2) {\n			${4:// main code}\n		};\n	}\n# singleton\nsnippet sing\n	function ${1:Singleton} (${2:argument}) {\n		// the cached instance\n		var instance;\n\n		// rewrite the constructor\n		$1 = function $1($2) {\n			return instance;\n		};\n		\n		// carry over the prototype properties\n		$1.prototype = this;\n\n		// the instance\n		instance = new $1();\n\n		// reset the constructor pointer\n		instance.constructor = $1;\n\n		${3:// code ...}\n\n		return instance;\n	}\n# class\nsnippet class\nregex /^\\s*/clas{0,2}/\n	var ${1:class} = function(${20}) {\n		$40$0\n	};\n	\n	(function() {\n		${60:this.prop = ""}\n	}).call(${1:class}.prototype);\n	\n	exports.${1:class} = ${1:class};\n# \nsnippet for-\n	for (var ${1:i} = ${2:Things}.length; ${1:i}--; ) {\n		${0:${2:Things}[${1:i}];}\n	}\n# for (...) {...}\nsnippet for\n	for (var ${1:i} = 0; $1 < ${2:Things}.length; $1++) {\n		${3:$2[$1]}$0\n	}\n# for (...) {...} (Improved Native For-Loop)\nsnippet forr\n	for (var ${1:i} = ${2:Things}.length - 1; $1 >= 0; $1--) {\n		${3:$2[$1]}$0\n	}\n\n\n#modules\nsnippet def\n	define(function(require, exports, module) {\n	"use strict";\n	var ${1/.*\\///} = require("${1}");\n	\n	$TM_SELECTED_TEXT\n	});\nsnippet req\nguard ^\\s*\n	var ${1/.*\\///} = require("${1}");\n	$0\nsnippet requ\nguard ^\\s*\n	var ${1/.*\\/(.)/\\u$1/} = require("${1}").${1/.*\\/(.)/\\u$1/};\n	$0\n',t.scope="javascript"})<commit_msg>Update public/libs/bower_components/ace-builds/src-min/snippets/javascript.js<commit_after><|endoftext|>


<commit_before>"use strict";

import $ from "jquery";
import d3 from "d3";

// We define these up here so we can re-use them for updating
// the bubble chart once it has been created.
var svg, bubble, text;
var color = d3.scale.category20c();

// Util for getting the duration based on what has been selected
var getDuration = function() {
    var checkedDuration = $("#duration input[type=radio]:checked").val();

    return checkedDuration === "all" ? 0 : 1;
};

var durationRadioButtons = $("#duration input[type=radio][name=duration]");

var getNbaStatsAPI = function() {
    // Although we specify a Season, that doesn't matter since IsOnlyCurrentSeason is set
    // to 0, meaning the Season is ignored. We have to specify a Season otherwise we get
    // an error from the API.
    return "http://stats.nba.com/stats/commonallplayers/?LeagueID=00&Season=2014-15&IsOnlyCurrentSeason=" + getDuration();
};

var updateBubbleChart = function(data) {
    var formattedData = bubble.nodes(data).filter(d => { return !d.children; });

    var node = svg.selectAll(".node")
        .data(formattedData);

    // Capture enter selection
    var nodeEnter = node.enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", d => { return "translate(" + d.x + "," + d.y + ")"; });

    // Re-use enter selection for circles
    nodeEnter
        .append("circle")
        .attr("r", d => { return d.r; })
        .style("fill", (d, i) => { return color(i); });

    // Re-use enter selection for text
    text
        .data(formattedData)
        .text(d => {
            var threshold = getDuration() === 0 ? 15 : 2;
            if (d.value > threshold) { return d.name; }
        });

    node.select("circle")
        .transition().duration(1000)
        .attr("r", d => {
            return d.r;
        })
        .style("fill", (d, i) => {
            return color(i);
        });

    node.transition().attr("class", "node")
        .attr("transform", d => {
            return "translate(" + d.x + "," + d.y + ")";
        });

    node.exit().remove();
};

var renderBubbleChart = function(data) {
    var diameter = 680;

    bubble = d3.layout.pack()
        .sort(null)
        .size([diameter, diameter])
        .padding(1.5);

    svg = d3.select("#bubble-chart").append("svg")
        .attr("width", diameter)
        .attr("height", diameter)
        .attr("class", "bubble");

    var node = svg.selectAll(".node")
      .data(bubble.nodes(data).filter(d => { return !d.children; }))
      .enter().append("g")
        .attr("class", "node")
        .attr("transform", d => { return "translate(" + d.x + "," + d.y + ")"; });

    node.append("circle")
      .attr("r", d => { return d.r; })
      .style("fill", d => { return color(d.name); });

    text = node.append("text")
      .attr("dy", ".3em")
      .attr("class", "bubble-text")
      .style("text-anchor", "middle")
      .text(d => {
        // Define a threshold for when to add some text to a bubble; with
        // all time names, we need to bump this up otherwise we will have
        // way too much text flying around in the UI.
        var threshold = getDuration() === 0 ? 15 : 2;

        if (d.value > threshold) { return d.name; }
      });

    d3.select(document.frameElement).style("height", diameter + "px");
};

var formatData = function(data) {
    var formattedData = [];

    Object.keys(data).forEach(key => {
        formattedData.push({
            name: key,
            value: data[key]
        });
    });

    return formattedData;
};

var getMostPupularNames = function(data) {
    var allPlayers = data.resultSets[0].rowSet;
    var mostPopularNames = {};

    allPlayers.forEach(player => {
        var playerFirstName = player[1].split(", ")[1];

        if (mostPopularNames.hasOwnProperty(playerFirstName)) {
            mostPopularNames[playerFirstName] += 1;
        } else {
            mostPopularNames[playerFirstName] = 1;
        }
    });

    return formatData(mostPopularNames);
};

var makeRequestAndRenderBubbleChart = function(renderFunction) {
    var nbaStatsAPI = getNbaStatsAPI();

    $.ajax(nbaStatsAPI, {
        dataType: "jsonp"
    })
    .done(function(data) {
        renderFunction({ children: getMostPupularNames(data) });
    });
};

var onDurationChange = function() {
    makeRequestAndRenderBubbleChart(updateBubbleChart);
};

// when the duration is changed, we will want to re-render
durationRadioButtons.change(onDurationChange);

makeRequestAndRenderBubbleChart(renderBubbleChart);<commit_msg>Add a cheeky little tooltip<commit_after>"use strict";

import $ from "jquery";
import d3 from "d3";

// We define these up here so we can re-use them for updating
// the bubble chart once it has been created.
var svg, bubble, text, tooltip;
var color = d3.scale.category20c();

// Util for getting the duration based on what has been selected
var getDuration = function() {
    var checkedDuration = $("#duration input[type=radio]:checked").val();

    return checkedDuration === "all" ? 0 : 1;
};

var durationRadioButtons = $("#duration input[type=radio][name=duration]");

var getNbaStatsAPI = function() {
    // Although we specify a Season, that doesn't matter since IsOnlyCurrentSeason is set
    // to 0, meaning the Season is ignored. We have to specify a Season otherwise we get
    // an error from the API.
    return "http://stats.nba.com/stats/commonallplayers/?LeagueID=00&Season=2014-15&IsOnlyCurrentSeason=" + getDuration();
};

var updateBubbleChart = function(data) {
    var formattedData = bubble.nodes(data).filter(d => { return !d.children; });

    var node = svg.selectAll(".node")
        .data(formattedData);

    // Capture enter selection
    var nodeEnter = node.enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", d => { return "translate(" + d.x + "," + d.y + ")"; });

    // Re-use enter selection for circles
    nodeEnter
        .append("circle")
        .attr("r", d => { return d.r; })
        .style("fill", (d, i) => { return color(i); });

    // Re-use enter selection for text
    text
        .data(formattedData)
        .text(d => {
            var threshold = getDuration() === 0 ? 15 : 2;
            if (d.value > threshold) { return d.name; }
        });

    node.select("circle")
        .transition().duration(1000)
        .attr("r", d => {
            return d.r;
        })
        .style("fill", (d, i) => {
            return color(i);
        });

    node.transition().attr("class", "node")
        .attr("transform", d => {
            return "translate(" + d.x + "," + d.y + ")";
        });

    node.exit().remove();
};

var renderBubbleChart = function(data) {
    var diameter = 680;

    bubble = d3.layout.pack()
        .sort(null)
        .size([diameter, diameter])
        .padding(1.5);

    svg = d3.select("#bubble-chart").append("svg")
        .attr("width", diameter)
        .attr("height", diameter)
        .attr("class", "bubble");

    var node = svg.selectAll(".node")
      .data(bubble.nodes(data).filter(d => { return !d.children; }))
      .enter().append("g")
        .attr("class", "node")
        .attr("transform", d => { return "translate(" + d.x + "," + d.y + ")"; });

    node.append("circle")
      .attr("r", d => { return d.r; })
      .style("fill", d => { return color(d.name); })
      .on("mouseover", d => {
            return tooltip
                .style("visibility", "visible")
                .text(d.name + "(" + d.value + ")");
      })
      .on("mousemove", _ => { return tooltip.style("top", (event.pageY - 10)+ "px").style("left",(event.pageX + 10) + "px"); })
      .on("mouseout", _ => { return tooltip.style("visibility", "hidden"); });

    text = node.append("text")
      .attr("dy", ".3em")
      .attr("class", "bubble-text")
      .style("text-anchor", "middle")
      .style("pointer-events", "none")
      .text(d => {
        // Define a threshold for when to add some text to a bubble; with
        // all time names, we need to bump this up otherwise we will have
        // way too much text flying around in the UI.
        var threshold = getDuration() === 0 ? 15 : 2;

        if (d.value > threshold) { return d.name; }
      });

    tooltip = d3.select("#bubble-chart")
      .append("div")
      .style("position", "absolute")
      .style("z-index", "10")
      .style("visibility", "hidden");

    d3.select(document.frameElement).style("height", diameter + "px");
};

var formatData = function(data) {
    var formattedData = [];

    Object.keys(data).forEach(key => {
        formattedData.push({
            name: key,
            value: data[key]
        });
    });

    return formattedData;
};

var getMostPupularNames = function(data) {
    var allPlayers = data.resultSets[0].rowSet;
    var mostPopularNames = {};

    allPlayers.forEach(player => {
        var playerFirstName = player[1].split(", ")[1];

        if (mostPopularNames.hasOwnProperty(playerFirstName)) {
            mostPopularNames[playerFirstName] += 1;
        } else {
            mostPopularNames[playerFirstName] = 1;
        }
    });

    return formatData(mostPopularNames);
};

var makeRequestAndRenderBubbleChart = function(renderFunction) {
    var nbaStatsAPI = getNbaStatsAPI();

    $.ajax(nbaStatsAPI, {
        dataType: "jsonp"
    })
    .done(function(data) {
        renderFunction({ children: getMostPupularNames(data) });
    });
};

var onDurationChange = function() {
    makeRequestAndRenderBubbleChart(updateBubbleChart);
};

// when the duration is changed, we will want to re-render
durationRadioButtons.change(onDurationChange);

makeRequestAndRenderBubbleChart(renderBubbleChart);<|endoftext|>


<commit_before>ace.define("ace/mode/clojure_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var ClojureHighlightRules = function() {

    var builtinFunctions = (
        '* *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* ' +
        '*command-line-args* *compile-files* *compile-path* *e *err* *file* ' +
        '*flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* ' +
        '*print-dup* *print-length* *print-level* *print-meta* *print-readably* ' +
        '*read-eval* *source-path* *use-context-classloader* ' +
        '*warn-on-reflection* + - -> ->> .. / < <= = ' +
        '== > > >= >= accessor aclone ' +
        'add-classpath add-watch agent agent-errors aget alength alias all-ns ' +
        'alter alter-meta! alter-var-root amap ancestors and apply areduce ' +
        'array-map aset aset-boolean aset-byte aset-char aset-double aset-float ' +
        'aset-int aset-long aset-short assert assoc assoc! assoc-in associative? ' +
        'atom await await-for await1 bases bean bigdec bigint binding bit-and ' +
        'bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left ' +
        'bit-shift-right bit-test bit-xor boolean boolean-array booleans ' +
        'bound-fn bound-fn* butlast byte byte-array bytes cast char char-array ' +
        'char-escape-string char-name-string char? chars chunk chunk-append ' +
        'chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? ' +
        'class class? clear-agent-errors clojure-version coll? comment commute ' +
        'comp comparator compare compare-and-set! compile complement concat cond ' +
        'condp conj conj! cons constantly construct-proxy contains? count ' +
        'counted? create-ns create-struct cycle dec decimal? declare definline ' +
        'defmacro defmethod defmulti defn defn- defonce defstruct delay delay? ' +
        'deliver deref derive descendants destructure disj disj! dissoc dissoc! ' +
        'distinct distinct? doall doc dorun doseq dosync dotimes doto double ' +
        'double-array doubles drop drop-last drop-while empty empty? ensure ' +
        'enumeration-seq eval even? every? false? ffirst file-seq filter find ' +
        'find-doc find-ns find-var first float float-array float? floats flush ' +
        'fn fn? fnext for force format future future-call future-cancel ' +
        'future-cancelled? future-done? future? gen-class gen-interface gensym ' +
        'get get-in get-method get-proxy-class get-thread-bindings get-validator ' +
        'hash hash-map hash-set identical? identity if-let if-not ifn? import ' +
        'in-ns inc init-proxy instance? int int-array integer? interleave intern ' +
        'interpose into into-array ints io! isa? iterate iterator-seq juxt key ' +
        'keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list ' +
        'list* list? load load-file load-reader load-string loaded-libs locking ' +
        'long long-array longs loop macroexpand macroexpand-1 make-array ' +
        'make-hierarchy map map? mapcat max max-key memfn memoize merge ' +
        'merge-with meta method-sig methods min min-key mod name namespace neg? ' +
        'newline next nfirst nil? nnext not not-any? not-empty not-every? not= ' +
        'ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ' +
        'ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? ' +
        'or parents partial partition pcalls peek persistent! pmap pop pop! ' +
        'pop-thread-bindings pos? pr pr-str prefer-method prefers ' +
        'primitives-classnames print print-ctor print-doc print-dup print-method ' +
        'print-namespace-doc print-simple print-special-doc print-str printf ' +
        'println println-str prn prn-str promise proxy proxy-call-with-super ' +
        'proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot ' +
        'rand rand-int range ratio? rational? rationalize re-find re-groups ' +
        're-matcher re-matches re-pattern re-seq read read-line read-string ' +
        'reduce ref ref-history-count ref-max-history ref-min-history ref-set ' +
        'refer refer-clojure release-pending-sends rem remove remove-method ' +
        'remove-ns remove-watch repeat repeatedly replace replicate require ' +
        'reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq ' +
        'rsubseq second select-keys send send-off seq seq? seque sequence ' +
        'sequential? set set-validator! set? short short-array shorts ' +
        'shutdown-agents slurp some sort sort-by sorted-map sorted-map-by ' +
        'sorted-set sorted-set-by sorted? special-form-anchor special-symbol? ' +
        'split-at split-with str stream? string? struct struct-map subs subseq ' +
        'subvec supers swap! symbol symbol? sync syntax-symbol-anchor take ' +
        'take-last take-nth take-while test the-ns time to-array to-array-2d ' +
        'trampoline transient tree-seq true? type unchecked-add unchecked-dec ' +
        'unchecked-divide unchecked-inc unchecked-multiply unchecked-negate ' +
        'unchecked-remainder unchecked-subtract underive unquote ' +
        'unquote-splicing update-in update-proxy use val vals var-get var-set ' +
        'var? vary-meta vec vector vector? when when-first when-let when-not ' +
        'while with-bindings with-bindings* with-in-str with-loading-context ' +
        'with-local-vars with-meta with-open with-out-str with-precision xml-seq ' +
        'zero? zipmap'
    );

    var keywords = ('throw try var ' +
        'def do fn if let loop monitor-enter monitor-exit new quote recur set!'
    );

    var buildinConstants = ("true false nil");

    var keywordMapper = this.createKeywordMapper({
        "keyword": keywords,
        "constant.language": buildinConstants,
        "support.function": builtinFunctions
    }, "identifier", false, " ");

    this.$rules = {
        "start" : [
            {
                token : "comment",
                regex : ";.*$"
            }, {
                token : "keyword", //parens
                regex : "[\\(|\\)]"
            }, {
                token : "keyword", //lists
                regex : "[\\'\\(]"
            }, {
                token : "keyword", //vectors
                regex : "[\\[|\\]]"
            }, {
                token : "keyword", //sets and maps
                regex : "[\\{|\\}|\\#\\{|\\#\\}]"
            }, {
                    token : "keyword", // ampersands
                    regex : '[\\&]'
            }, {
                    token : "keyword", // metadata
                    regex : '[\\#\\^\\{]'
            }, {
                    token : "keyword", // anonymous fn syntactic sugar
                    regex : '[\\%]'
            }, {
                    token : "keyword", // deref reader macro
                    regex : '[@]'
            }, {
                token : "constant.numeric", // hex
                regex : "0[xX][0-9a-fA-F]+\\b"
            }, {
                token : "constant.numeric", // float
                regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
            }, {
                token : "constant.language",
                regex : '[!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+||=|!=|<=|>=|<>|<|>|!|&&]'
            }, {
                token : keywordMapper,
                regex : "[a-zA-Z_$][a-zA-Z0-9_$\\-]*\\b"
            }, {
                token : "string", // single line
                regex : '"',
                next: "string"
            }, {
                token : "constant", // symbol
                regex : /:[^()\[\]{}'"\^%`,;\s]+/
            }, {
                token : "string.regexp", //Regular Expressions
                regex : '/#"(?:\\.|(?:\\\")|[^\""\n])*"/g'
            }

        ],
        "string" : [
            {
                token : "constant.language.escape",
                regex : "\\\\.|\\\\$"
            }, {
                token : "string",
                regex : '[^"\\\\]+'
            }, {
                token : "string",
                regex : '"',
                next : "start"
            }
        ]
    };
};

oop.inherits(ClojureHighlightRules, TextHighlightRules);

exports.ClojureHighlightRules = ClojureHighlightRules;
});

ace.define("ace/mode/matching_parens_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";

var Range = require("../range").Range;

var MatchingParensOutdent = function() {};

(function() {

    this.checkOutdent = function(line, input) {
        if (! /^\s+$/.test(line))
            return false;

        return /^\s*\)/.test(input);
    };

    this.autoOutdent = function(doc, row) {
        var line = doc.getLine(row);
        var match = line.match(/^(\s*\))/);

        if (!match) return 0;

        var column = match[1].length;
        var openBracePos = doc.findMatchingBracket({row: row, column: column});

        if (!openBracePos || openBracePos.row == row) return 0;

        var indent = this.$getIndent(doc.getLine(openBracePos.row));
        doc.replace(new Range(row, 0, row, column-1), indent);
    };

    this.$getIndent = function(line) {
        var match = line.match(/^(\s+)/);
        if (match) {
            return match[1];
        }

        return "";
    };

}).call(MatchingParensOutdent.prototype);

exports.MatchingParensOutdent = MatchingParensOutdent;
});

ace.define("ace/mode/clojure",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/clojure_highlight_rules","ace/mode/matching_parens_outdent"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var ClojureHighlightRules = require("./clojure_highlight_rules").ClojureHighlightRules;
var MatchingParensOutdent = require("./matching_parens_outdent").MatchingParensOutdent;

var Mode = function() {
    this.HighlightRules = ClojureHighlightRules;
    this.$outdent = new MatchingParensOutdent();
};
oop.inherits(Mode, TextMode);

(function() {

    this.lineCommentStart = ";";
    this.minorIndentFunctions = ["defn", "defn-", "defmacro", "def", "deftest", "testing"];

    this.$toIndent = function(str) {
        return str.split('').map(function(ch) {
            if (/\s/.exec(ch)) {
                return ch;
            } else {
                return ' ';
            }
        }).join('');
    };

    this.$calculateIndent = function(line, tab) {
        var baseIndent = this.$getIndent(line);
        var delta = 0;
        var isParen, ch;
        for (var i = line.length - 1; i >= 0; i--) {
            ch = line[i];
            if (ch === '(') {
                delta--;
                isParen = true;
            } else if (ch === '(' || ch === '[' || ch === '{') {
                delta--;
                isParen = false;
            } else if (ch === ')' || ch === ']' || ch === '}') {
                delta++;
            }
            if (delta < 0) {
                break;
            }
        }
        if (delta < 0 && isParen) {
            i += 1;
            var iBefore = i;
            var fn = '';
            while (true) {
                ch = line[i];
                if (ch === ' ' || ch === '\t') {
                    if(this.minorIndentFunctions.indexOf(fn) !== -1) {
                        return this.$toIndent(line.substring(0, iBefore - 1) + tab);
                    } else {
                        return this.$toIndent(line.substring(0, i + 1));
                    }
                } else if (ch === undefined) {
                    return this.$toIndent(line.substring(0, iBefore - 1) + tab);
                }
                fn += line[i];
                i++;
            }
        } else if(delta < 0 && !isParen) {
            return this.$toIndent(line.substring(0, i+1));
        } else if(delta > 0) {
            baseIndent = baseIndent.substring(0, baseIndent.length - tab.length);
            return baseIndent;
        } else {
            return baseIndent;
        }
    };

    this.getNextLineIndent = function(state, line, tab) {
        return this.$calculateIndent(line, tab);
    };

    this.checkOutdent = function(state, line, input) {
        return this.$outdent.checkOutdent(line, input);
    };

    this.autoOutdent = function(state, doc, row) {
        this.$outdent.autoOutdent(doc, row);
    };

    this.$id = "ace/mode/clojure";
}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>Update public/libs/bower_components/ace-builds/src-noconflict/mode-clojure.js<commit_after><|endoftext|>


<commit_before>// @flow
import React from 'react';
import { compose, withState, lifecycle } from 'recompose';
import { fetchApi } from '@ncigdc/utils/ajax';
import { Row, Column } from '@ncigdc/uikit/Flex';
import FrequentMutationsContainer from '@ncigdc/components/FrequentMutationsContainer';

const styles = {
  heading: {
    flexGrow: 1,
    fontSize: '2rem',
    marginBottom: 7,
    marginTop: 7,
  },
  card: {
    backgroundColor: 'white',
  },
};

const initialState = {
  loading: true,
};

export default
compose(
  withState('selectedSurvivalData', 'setSelectedSurvivalData', {}),
  withState('state', 'setState', initialState),
  lifecycle({
    async componentDidMount() {
      const data1 = await fetchApi(
        'analysis/mutated_cases_count_by_project',
        { headers: { 'Content-Type': 'application/json' } }
      );

      const numCasesAggByProject = data1.aggregations.projects.buckets.reduce((acc, b) => {
        acc[b.key] = b.case_summary.case_with_ssm.doc_count;
        return acc;
      }, {});

      const data4 = await fetchApi(
        'analysis/survival',
        { headers: { 'Content-Type': 'application/json' } }
      );

      const survivalData = data4;

      this.props.setState(s => ({
        ...s,
        loading: false,
        numCasesAggByProject,
        survivalData,
      }));
    }
  })
)(({
  state,
  setSelectedSurvivalData,
  selectedSurvivalData,
  totalNumCases,
  projectId = '',
  ...props
}) => {
  const survivalData = {
    legend: '',
    rawData: selectedSurvivalData.rawData || state.survivalData,
  };

  return (
    <Column style={styles.card}>

        Somatic Mutations

      <FrequentMutationsContainer
        numCasesAggByProject={state.numCasesAggByProject}
        totalNumCases={totalNumCases}
        projectId={projectId}
        api={API}
        width={window.innerWidth}
        showSurvivalPlot
      />
    </Column>
  )
})
<commit_msg>:fix: not broken<commit_after>// @flow
import React from 'react';
import { compose, withState, lifecycle } from 'recompose';
import { fetchApi } from '@ncigdc/utils/ajax';
import { Column } from '@ncigdc/uikit/Flex';
import FrequentMutationsContainer from '@ncigdc/components/FrequentMutationsContainer';

const styles = {
  heading: {
    flexGrow: 1,
    fontSize: '2rem',
    marginBottom: 7,
    marginTop: 7,
  },
  card: {
    backgroundColor: 'white',
  },
};

const initialState = {
  loading: true,
};

export default
compose(
  withState('selectedSurvivalData', 'setSelectedSurvivalData', {}),
  withState('state', 'setState', initialState),
  lifecycle({
    async componentDidMount() {
      const data1 = await fetchApi(
        'analysis/mutated_cases_count_by_project',
        { headers: { 'Content-Type': 'application/json' } }
      );

      const numCasesAggByProject = data1.aggregations.projects.buckets.reduce((acc, b) => {
        acc[b.key] = b.case_summary.case_with_ssm.doc_count;
        return acc;
      }, {});

      const data4 = await fetchApi(
        'analysis/survival',
        { headers: { 'Content-Type': 'application/json' } }
      );

      const survivalData = data4;

      this.props.setState(s => ({
        ...s,
        loading: false,
        numCasesAggByProject,
        survivalData,
      }));
    },
  })
)(({
  state,
  totalNumCases,
  projectId = '',
  ...props
}) => (
  <Column style={styles.card}>

        Somatic Mutations

    <FrequentMutationsContainer
      numCasesAggByProject={state.numCasesAggByProject}
      totalNumCases={totalNumCases}
      projectId={projectId}
      defaultSurvivalRawData={state.survivalData}
      defaultSurvivalLegend={''}
      api={API}
      width={window.innerWidth}
      showSurvivalPlot
    />
  </Column>
));
<|endoftext|>


<commit_before>const gulp = require('gulp')
const fs = require('fs')
const request = require('request')
const jimp = require('jimp')

const configPath = process.cwd() + '/data/config.json'
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'))
const methode = config.copy.methode
const imageSizes = [ 640, 1280, 1920 ]
const imageDirectory = 'assets/methode/'
let imagesToDownload = []
let firstAdSlotted = false

const getImageDirectory = () => {
	const dir = methode.imageDirectory || ''
	const finalDir = dir ? `${dir}/` : dir

}

const createPicturefill = ({ name, extension, caption }) => {
	const srcset = methode.imageLibrary === 'picturefill' ? 'srcset' : 'data-srcset'
	const lazyload = methode.imageLibrary === 'picturefill' ? '' : 'lazyload'
	const defaultSrc = `${imageDirectory}${name}placeholder.${extension}`

	const getPath = (sz) => `${imageDirectory}${name}${sz}.${extension}`
	const getSource = (src, mq) => `<source ${srcset}='${src}' media='(min-width:${mq}px)'>`
	const reversed = imageSizes.map(i => i).reverse()

	return `
		<picture>

			${
				reversed.map((sz, index) => {
					const src = getPath(sz)
					const mq = index < reversed.length - 1
						? Math.floor(reversed[index + 1] / 1.5)
						: 1
					return getSource(src, mq)
				}).join('')
			}

		</picture>
	`.trim()
}

const createFigureSource = ({ name, extension, caption }) => {

	if (methode.imageLibrary) {
		return createPicturefill({ name, extension, caption })
	}
	// plain old image default
	const src = `${imageDirectory}${name}${imageSizes[imageSizes.length - 1]}.${extension}`
	return `<img src='${src}' alt='${caption}' />`
}

const getImageInfo = (imagePath) => {
	const imageFull = imagePath.substr(imagePath.lastIndexOf('/') + 1)
	const imageSplit = imageFull.split('.')
	const name = `${imageSplit[0]}_apps_w_`
	const extension = imageSplit[1]
	return { name, extension }
}

const replaceMethodeImageSize = ({ imagePath, imageSize }) =>
	imagePath.replace(/image_(.+\d)w/g, `image_${imageSize}w`)

const replaceLocalImageSize = ({ imagePath, imageSize }) =>
	imagePath.replace(/_apps_w_(.+\d)\./g, `_apps_w_${imageSize}.`)

const createFigure = ({ href, credit, caption, alt }) => {
	const imagePath = href.split('?')[0]
	const { name, extension } = getImageInfo(imagePath)

	// start generating markup
	const src = createFigureSource({ name, extension, caption })

	// add to download queue
	const imageSize = 1920
	const url = `http:${replaceMethodeImageSize({ imagePath, imageSize })}`
	const filename = `${name}${imageSize}.${extension}`

	imagesToDownload.push({ url, filename })

	return `

			${src}
			${credit}

${caption}

	`.trim()
}

const cleanP = (content) => {
	// check for graphic partial first
	if (content.match(/{{graphic:(.*)}}/)) {
		return content.replace(/{{graphic:(.*)}}/, (match, name, index) =>
			`{{> graphic/${name.trim()} }}`
		)
	}

	const stripped = content
		.replace(//g, '') // remove spans
		.replace(/<\/span>/g, '')
		.replace(//g, '') // remove bolds
		.replace(/<\/b>/g, '')

	// hr
	if (stripped.match(/(\*\s*){3}/)) return '
'
	//subhed
	if (stripped.match(/subhead>/)) {
		return stripped.replace(/<subhead(.*?)>/g, "
")
		.replace(/<\/subhead>/g, '
')
	}

	return stripped.length ? `<p class='methode-graf'>${stripped}</p>` : ''
}

const createContentMarkup = (item) => {
	const types = {
		p: ({ content }) => cleanP(content),
		image: ({ href, credit, caption, alt }) => createFigure({ href, credit, caption, alt }),
		subhead: ({ content }) => {
			return `<h3 class='section-hed miller-banner-regular'>${content}</h3>`
		},
		ad: () => {
			firstAdSlotted = true
			return `{{#if meta.ads}}{{> base/base-ad-slot}}{{/if}}`
		},
	}

	if (item.type === 'ad' && firstAdSlotted) return ''
	return types[item.type](item)
}

const createHTML = (stories) =>
	stories.map((story, index) => {
		const { content } = story.body
		// go thru item in content and create the proper markup
		return `

				${content.map(createContentMarkup).join('\n')}

		`
	}).join('')

const writeHTML = (html) =>
	fs.writeFileSync('src/html/partials/graphic/methode.hbs', html)

const resizeImage = ({ path, resolve, reject }) => {
	console.log('resizing image...')
	// create smaller versions of each image
	const promises = imageSizes.map(imageSize =>
		new Promise((res, rej) => {
			const out = replaceLocalImageSize({ imagePath: path, imageSize })
			jimp.read(path).then(image =>
		    	image
		    	.resize(imageSize, jimp.AUTO)
				.write(out, res)
			).catch(err => rej(err))
		})
	)

	promises.push(
		new Promise((res, rej) => {
			const imageSize = 20
			const out = replaceLocalImageSize({ imagePath: path, imageSize: 'placeholder' })
			jimp.read(path).then(image =>
		    	image
		    	.blur(40)
		    	.resize(imageSize, jimp.AUTO)
				.write(out, res)
			).catch(err => rej(err))
		})
	)

	Promise.all(promises)
		.then(result => resolve(result))
		.catch(error => reject(error))
}

const downloadImages = (cb) => {
	const promises = imagesToDownload.map(image =>
		new Promise((resolve, reject) => {
			const { url, filename } = image
			const path = `src/${imageDirectory}${filename}`
			try {
				const exists = fs.lstatSync(path)
				resolve()
			} catch (e) {
				console.log(`downloading: ${url}`)
				request(url, {encoding: 'binary'}, (error, response, body) => {
					if (error) reject(error)
					else {
						fs.writeFile(path, body, 'binary', (err) => {
							if (err) reject(err)
							else resizeImage({ path, resolve, reject })
						})
					}
				})
			}
		})
	)

	Promise.all(promises)
		.then(result => cb())
		.catch(error => {
			console.log(error)
			cb()
		})
}

const fetchMethode = (cb) => {
	const base = 'http://prdedit.bostonglobe.com/eom/SysConfig/WebPortal/BostonGlobe/precursor/template/api_redirect.jsp?path=/'
	const promises = methode.story.map(story =>
		new Promise((resolve, reject) => {
			const url = `${base}${story.path}`
			console.log('fetching story data:', url)
			request(url, (error, response, body) => {
				if (!error && response.statusCode === 200) {
					resolve({...story, body: JSON.parse(body)})
				} else {
					reject(error)
				}
			})
		})
	)

	Promise.all(promises)
		.then(results => {
			const html = createHTML(results)
			writeHTML(html)
			downloadImages(cb)
		})
		.catch(error => {
			console.error(error)
			cb()
		})
}

gulp.task('fetch-methode', (cb) => {
	if (methode.story.length) fetchMethode(cb)
	else {
		console.error('No methode story in config')
		cb()
	}
})
<commit_msg>bug fix for items on fetch-methode<commit_after>const gulp = require('gulp')
const fs = require('fs')
const request = require('request')
const jimp = require('jimp')

const configPath = process.cwd() + '/data/config.json'
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'))
const methode = config.copy.methode
const imageSizes = [ 640, 1280, 1920 ]
const imageDirectory = 'assets/methode/'
let imagesToDownload = []
let firstAdSlotted = false

const getImageDirectory = () => {
	const dir = methode.imageDirectory || ''
	const finalDir = dir ? `${dir}/` : dir

}

const createPicturefill = ({ name, extension, caption }) => {
	const srcset = methode.imageLibrary === 'picturefill' ? 'srcset' : 'data-srcset'
	const lazyload = methode.imageLibrary === 'picturefill' ? '' : 'lazyload'
	const defaultSrc = `${imageDirectory}${name}placeholder.${extension}`

	const getPath = (sz) => `${imageDirectory}${name}${sz}.${extension}`
	const getSource = (src, mq) => `<source ${srcset}='${src}' media='(min-width:${mq}px)'>`
	const reversed = imageSizes.map(i => i).reverse()

	return `
		<picture>

			${
				reversed.map((sz, index) => {
					const src = getPath(sz)
					const mq = index < reversed.length - 1
						? Math.floor(reversed[index + 1] / 1.5)
						: 1
					return getSource(src, mq)
				}).join('')
			}

		</picture>
	`.trim()
}

const createFigureSource = ({ name, extension, caption }) => {

	if (methode.imageLibrary) {
		return createPicturefill({ name, extension, caption })
	}
	// plain old image default
	const src = `${imageDirectory}${name}${imageSizes[imageSizes.length - 1]}.${extension}`
	return `<img src='${src}' alt='${caption}' />`
}

const getImageInfo = (imagePath) => {
	const imageFull = imagePath.substr(imagePath.lastIndexOf('/') + 1)
	const imageSplit = imageFull.split('.')
	const name = `${imageSplit[0]}_apps_w_`
	const extension = imageSplit[1]
	return { name, extension }
}

const replaceMethodeImageSize = ({ imagePath, imageSize }) =>
	imagePath.replace(/image_(.+\d)w/g, `image_${imageSize}w`)

const replaceLocalImageSize = ({ imagePath, imageSize }) =>
	imagePath.replace(/_apps_w_(.+\d)\./g, `_apps_w_${imageSize}.`)

const createFigure = ({ href, credit, caption, alt }) => {
	const imagePath = href.split('?')[0]
	const { name, extension } = getImageInfo(imagePath)

	// start generating markup
	const src = createFigureSource({ name, extension, caption })

	// add to download queue
	const imageSize = 1920
	const url = `http:${replaceMethodeImageSize({ imagePath, imageSize })}`
	const filename = `${name}${imageSize}.${extension}`

	imagesToDownload.push({ url, filename })

	return `

			${src}
			${credit}

${caption}

	`.trim()
}

const cleanP = (content) => {
	// check for graphic partial first
	if (content.match(/{{graphic:(.*)}}/)) {
		return content.replace(/{{graphic:(.*)}}/, (match, name, index) =>
			`{{> graphic/${name.trim()} }}`
		)
	}

	const stripped = content
		.replace(//g, '') // remove spans
		.replace(/<\/span>/g, '')
		.replace(//g, '') // remove bolds
		.replace(/<\/b>/g, '')

	// hr
	if (stripped.match(/(\*\s*){3}/)) return '
'
	//subhed
	if (stripped.match(/subhead>/)) {
		return stripped.replace(/<subhead(.*?)>/g, "
")
		.replace(/<\/subhead>/g, '
')
	}

	return stripped.length ? `<p class='methode-graf'>${stripped}</p>` : ''
}

const createContentMarkup = (item) => {
	const types = {
		p: ({ content }) => cleanP(content),
		image: ({ href, credit, caption, alt }) => createFigure({ href, credit, caption, alt }),
		subhead: ({ content }) => {
			return `<h3 class='section-hed miller-banner-regular'>${content}</h3>`
		},
		ad: () => {
			firstAdSlotted = true
			return `{{#if meta.ads}}{{> base/base-ad-slot}}{{/if}}`
		},
	}

	if (item.type === 'ad' && firstAdSlotted) return ''
	return types[item.type] ? types[item.type](item) : ''
}

const createHTML = (stories) =>
	stories.map((story, index) => {
		const { content } = story.body
		// go thru item in content and create the proper markup
		return `

				${content.map(createContentMarkup).join('\n')}

		`
	}).join('')

const writeHTML = (html) =>
	fs.writeFileSync('src/html/partials/graphic/methode.hbs', html)

const resizeImage = ({ path, resolve, reject }) => {
	console.log('resizing image...')
	// create smaller versions of each image
	const promises = imageSizes.map(imageSize =>
		new Promise((res, rej) => {
			const out = replaceLocalImageSize({ imagePath: path, imageSize })
			jimp.read(path).then(image =>
		    	image
		    	.resize(imageSize, jimp.AUTO)
				.write(out, res)
			).catch(err => rej(err))
		})
	)

	promises.push(
		new Promise((res, rej) => {
			const imageSize = 20
			const out = replaceLocalImageSize({ imagePath: path, imageSize: 'placeholder' })
			jimp.read(path).then(image =>
		    	image
		    	.blur(40)
		    	.resize(imageSize, jimp.AUTO)
				.write(out, res)
			).catch(err => rej(err))
		})
	)

	Promise.all(promises)
		.then(result => resolve(result))
		.catch(error => reject(error))
}

const downloadImages = (cb) => {
	const promises = imagesToDownload.map(image =>
		new Promise((resolve, reject) => {
			const { url, filename } = image
			const path = `src/${imageDirectory}${filename}`
			try {
				const exists = fs.lstatSync(path)
				resolve()
			} catch (e) {
				console.log(`downloading: ${url}`)
				request(url, {encoding: 'binary'}, (error, response, body) => {
					if (error) reject(error)
					else {
						fs.writeFile(path, body, 'binary', (err) => {
							if (err) reject(err)
							else resizeImage({ path, resolve, reject })
						})
					}
				})
			}
		})
	)

	Promise.all(promises)
		.then(result => cb())
		.catch(error => {
			console.log(error)
			cb()
		})
}

const fetchMethode = (cb) => {
	const base = 'http://prdedit.bostonglobe.com/eom/SysConfig/WebPortal/BostonGlobe/precursor/template/api_redirect.jsp?path=/'
	const promises = methode.story.map(story =>
		new Promise((resolve, reject) => {
			const url = `${base}${story.path}`
			console.log('fetching story data:', url)
			request(url, (error, response, body) => {
				if (!error && response.statusCode === 200) {
					resolve({...story, body: JSON.parse(body)})
				} else {
					reject(error)
				}
			})
		})
	)

	Promise.all(promises)
		.then(results => {
			const html = createHTML(results)
			writeHTML(html)
			downloadImages(cb)
		})
		.catch(error => {
			console.error(error)
			cb()
		})
}

gulp.task('fetch-methode', (cb) => {
	if (methode.story.length) fetchMethode(cb)
	else {
		console.error('No methode story in config')
		cb()
	}
})
<|endoftext|>


<commit_before>'use strict';

var fs                  = require ('fs');
var mongoose            = require ('mongoose');
var Project             = require ('../controllers/project.controller');
var OrganizationController = require ('../../../organizations/server/controllers/organization.controller');
var PhaseController 	= require ('../../../phases/server/controllers/phase.controller');
var Model               = mongoose.model ('Project');
var Phase               = mongoose.model ('Phase');
var Organization        = mongoose.model ('Organization');
var CSVParse            = require ('csv-parse');

// -------------------------------------------------------------------------
//
// This does a whole complicated mess of crap in loading up projects, should
// probably be in its own controller as it doesnt really follow the usual
// patterns, but it may also only be required for a short time, so its fine
// here for now.
//
// -------------------------------------------------------------------------
module.exports = function(file, req, res) {
	return new Promise (function (resolve, reject) {
		var params = req.url.split("/");
		var projectType = params[params.length-1]; // Last param is project type
		// console.log("projectType:",params[params.length-1]);
		var doPhaseWork = function(project, phase) {
			var finalPhaseCode = phase.toLowerCase().replace (/\W+/g,'-');
			var stopProcessing = false;
			// Add the phase to the project, and return this as it's going to be
			// the last task in the chain.  This assumed the phase code being
			// passed in is actually correct - ensure import data has the right name
			// in order to generate the phase-code correctly.
			return new Promise(function (rs,rj) {
				if (finalPhaseCode === "pre-submission") {
					stopProcessing = true;
					return project;
				} else {
					(new Project(req.user)).addPhase(project, "pre-ea")
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "pre-ea") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "pre-app");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "pre-app") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "evaluation");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "evaluation") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "application-review");
						}
					})
					.then(function (p) {
						console.log("FUCK:",finalPhaseCode);
						if (stopProcessing || finalPhaseCode === "application-review") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "decision");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "decision") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "post-certification");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "post-certification") {
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "completed");
						}
					})
					.then(function (p) {
						rs(p);
					});
				}
			});
		};
		var doOrgWork = function(proponent, project) {
			return new Promise(function(rs, rj) {
				Organization.findOne ({name:proponent.name}, function (err, result) {
					if (result === null) {
						// Create it
						var o = new OrganizationController(req.user);
						o.newDocument(proponent)
						.then ( o.create )
						.then (function (org) {
							// Assign the org to the project, and save it.  Resolve this request as
							// being done.
							project.proponent = org;
							project.status = "In Progress";
							project.save().then(rs, rj);
						});
					} else {
						// Same as above, but the update version.
						project.proponent = result;
						project.status = "In Progress";
						project.save().then(rs, rj);
					}
				});
			});
		};
		var doProjectWork = function(item, query) {
			return new Promise(function (rs, rj) {
				Model.findOne(query, function (err, doc) {
					var p = new Project(req.user);
					if (doc === null) {
						p.newDocument(item)
						.then(p.create)
						.then(function (proj) {
							p.submit(proj).then(function (newP) {
								// Project has been created, now to set things and resolve the project back
								// to the caller.
								if(item.isPublished === "TRUE") {
									p.publish(newP, true).then(rs, rj);
								} else {
									rs(newP);
								}
							});
						});
					} else {
						p.update(doc, item).then(rs, rj);
					}
				});
			});
		};
		// Now parse and go through this thing.
		fs.readFile(file.path, 'utf8', function(err, data) {
			if (err) {
				//
				// cc: added the return here otherwise the rest of this will execute regardless of the resolve
				//
				return reject("err:"+err);
			}
			// console.log("FILE DATA:",data);
			var colArray = "";
			if (projectType === "eao") {
				colArray = ['id','Stream','ProjectName','Proponent','Region','description','locSpatial','locDescription','provincialED','federalED','investment','projectCreateDate','projectDescriptionLivingData','projectNotes','projectURL','investmentNotes','lat','long','constructionjobs','constructionjobsNotes','operatingjobs','operatingjobsNotes','projectType','sector','phase','currentPhaseTypeActivity','eaActive','CEAAInvolvement','eaIssues','eaNotes','responsibleEPD','phoneEPD','emailEPD','projectLead','projectLeadPhone','projectLeadEmail','projectAnalyst','projectAssistant','administrativeAssistant','CELead','CELeadPhone','CELeadEmail','teamNotes', 'isPublished'];
			} else {
				colArray = ['id','ProjectName','Proponent','Ownership','type', 'lat','long','Status','Commodity','Region','TailingsImpoundments','description'];
			}
			var parse = new CSVParse(data, {delimiter: ',', columns: colArray}, function(err, output){
				// Skip this many rows
				var length = Object.keys(output).length;
				var projectProcessed = 0;
				// console.log("length",length);
				var promises = [];
				Object.keys(output).forEach(function(key, index) {
					if (index > 0) {
						var row = output[key];
						var id = 0;
						if (!isNaN(row.id)) {
							id = parseInt(row.id);
						}
						var newObj = null;
						var newProponent = {
							name: row.Proponent
						};
						var query = {epicProjectID: id};
						if (projectType === "mem") {
							query = { memPermitID: row.id };
							newObj = {
								memPermitID			: row.id,
								ownership 			: row.Ownership,
								commodity 			: row.Commodity,
								tailingsImpoundments: row.TailingsImpoundments,
								roles 				: ['mem', 'public'],
								read 				: ['public'],
								submit 				: ['mem'],
								type 				: row.type
							};
						} else {
							query = { epicProjectID: parseInt(row.id) };
							newObj = {
								epicProjectID 	: id,
								name 			: row.ProjectName,
								shortName 		: row.ProjectName.toLowerCase ().replace(/\//g,'-').replace (' ', '-').substr (0, row.ProjectName.length+1),
								roles 			: ['eao', 'public'],
								read 			: ['public'],
								submit 			: ['eao'],
								description 	: row.description,
								region 			: row.Region.toLowerCase ().replace(' region',''),
								sector 			: row.sector,
								locSpatial 		: row.locSpatial,
								location 		: row.locDescription,
								lat 			: row.lat,
								lon 			: row.long,
								provElecDist 	: row.provincialED,
								fedElecDist 	: row.federalED,
								projectNotes 	: row.projectNotes,
								type 			: row.projectType,
								intake: {
									constructionjobs 		: row.constructionjobs,
									constructionjobsNotes 	: row.constructionjobsNotes,
									operatingjobs 			: row.operatingjobs,
									operatingjobsNotes 		: row.operatingjobsNotes,
									investment 				: row.investment,
									investmentNotes 		: row.investmentNotes
								},
								eaActive 				: row.eaActive,
								CEAAInvolvement 		: row.CEAAInvolvement,
								eaIssues 				: row.eaIssues,
								eaNotes 				: row.eaNotes,
								responsibleEPD 			: row.responsibleEPD,
								responsibleEPDPhone		: row.phoneEPD,
								responsibleEPDEmail 	: row.emailEPD,
								projectLead 			: row.projectLead,
								projectLeadPhone		: row.projectLeadPhone,
								projectLeadEmail 		: row.projectLeadEmail,
								projectAnalyst 			: row.projectAnalyst,
								projectAssistant 		: row.projectAssistant,
								administrativeAssistant : row.administrativeAssistant,
								CELead 					: row.CELead,
								CELeadPhone				: row.CELeadPhone,
								CELeadEmail				: row.CELeadEmail,
								teamNotes				: row.teamNotes,
								isPublished				: row.isPublished,
								epicStream 				: row.Stream
							};
						}
						promises.push({obj: newObj, query: query, proponent: newProponent, phase: row.phase});
					}
				});

				Promise.resolve ()
				.then (function () {
					return promises.reduce (function (current, item) {
						return current.then (function () {
							// console.log ('++ add phase ', code);
							return doProjectWork(item.obj, item.query)
							//
							// Sequential reduction of work moving from the tail of the original promise
							// array to the head, by returning a promise for the next 'then' clause each time
							// until the final doPhaseWork completes.  Only then will this promise reduction
							// finally resolve for the .then of the original resolving Promise.resolve().
							//
							.then(function (project) {
								return doOrgWork(item.proponent, project);
							})
							.then(function (org) {
								return doPhaseWork(org, item.phase);
							});
						});
					}, Promise.resolve());
				})
				.then (resolve, reject);
			}); // CSV Parse
		}); // Read File
	});
};

<commit_msg>remove console.log<commit_after>'use strict';

var fs                  = require ('fs');
var mongoose            = require ('mongoose');
var Project             = require ('../controllers/project.controller');
var OrganizationController = require ('../../../organizations/server/controllers/organization.controller');
var PhaseController 	= require ('../../../phases/server/controllers/phase.controller');
var Model               = mongoose.model ('Project');
var Phase               = mongoose.model ('Phase');
var Organization        = mongoose.model ('Organization');
var CSVParse            = require ('csv-parse');

// -------------------------------------------------------------------------
//
// This does a whole complicated mess of crap in loading up projects, should
// probably be in its own controller as it doesnt really follow the usual
// patterns, but it may also only be required for a short time, so its fine
// here for now.
//
// -------------------------------------------------------------------------
module.exports = function(file, req, res) {
	return new Promise (function (resolve, reject) {
		var params = req.url.split("/");
		var projectType = params[params.length-1]; // Last param is project type
		// console.log("projectType:",params[params.length-1]);
		var doPhaseWork = function(project, phase) {
			var finalPhaseCode = phase.toLowerCase().replace (/\W+/g,'-');
			var stopProcessing = false;
			// Add the phase to the project, and return this as it's going to be
			// the last task in the chain.  This assumed the phase code being
			// passed in is actually correct - ensure import data has the right name
			// in order to generate the phase-code correctly.
			return new Promise(function (rs,rj) {
				if (finalPhaseCode === "pre-submission") {
					stopProcessing = true;
					return project;
				} else {
					(new Project(req.user)).addPhase(project, "pre-ea")
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "pre-ea") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "pre-app");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "pre-app") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "evaluation");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "evaluation") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "application-review");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "application-review") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "decision");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "decision") {
							stopProcessing = true;
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "post-certification");
						}
					})
					.then(function (p) {
						if (stopProcessing || finalPhaseCode === "post-certification") {
							return p;
						} else {
							return (new Project(req.user)).addPhase(project, "completed");
						}
					})
					.then(function (p) {
						rs(p);
					});
				}
			});
		};
		var doOrgWork = function(proponent, project) {
			return new Promise(function(rs, rj) {
				Organization.findOne ({name:proponent.name}, function (err, result) {
					if (result === null) {
						// Create it
						var o = new OrganizationController(req.user);
						o.newDocument(proponent)
						.then ( o.create )
						.then (function (org) {
							// Assign the org to the project, and save it.  Resolve this request as
							// being done.
							project.proponent = org;
							project.status = "In Progress";
							project.save().then(rs, rj);
						});
					} else {
						// Same as above, but the update version.
						project.proponent = result;
						project.status = "In Progress";
						project.save().then(rs, rj);
					}
				});
			});
		};
		var doProjectWork = function(item, query) {
			return new Promise(function (rs, rj) {
				Model.findOne(query, function (err, doc) {
					var p = new Project(req.user);
					if (doc === null) {
						p.newDocument(item)
						.then(p.create)
						.then(function (proj) {
							p.submit(proj).then(function (newP) {
								// Project has been created, now to set things and resolve the project back
								// to the caller.
								if(item.isPublished === "TRUE") {
									p.publish(newP, true).then(rs, rj);
								} else {
									rs(newP);
								}
							});
						});
					} else {
						p.update(doc, item).then(rs, rj);
					}
				});
			});
		};
		// Now parse and go through this thing.
		fs.readFile(file.path, 'utf8', function(err, data) {
			if (err) {
				//
				// cc: added the return here otherwise the rest of this will execute regardless of the resolve
				//
				return reject("err:"+err);
			}
			// console.log("FILE DATA:",data);
			var colArray = "";
			if (projectType === "eao") {
				colArray = ['id','Stream','ProjectName','Proponent','Region','description','locSpatial','locDescription','provincialED','federalED','investment','projectCreateDate','projectDescriptionLivingData','projectNotes','projectURL','investmentNotes','lat','long','constructionjobs','constructionjobsNotes','operatingjobs','operatingjobsNotes','projectType','sector','phase','currentPhaseTypeActivity','eaActive','CEAAInvolvement','eaIssues','eaNotes','responsibleEPD','phoneEPD','emailEPD','projectLead','projectLeadPhone','projectLeadEmail','projectAnalyst','projectAssistant','administrativeAssistant','CELead','CELeadPhone','CELeadEmail','teamNotes', 'isPublished'];
			} else {
				colArray = ['id','ProjectName','Proponent','Ownership','type', 'lat','long','Status','Commodity','Region','TailingsImpoundments','description'];
			}
			var parse = new CSVParse(data, {delimiter: ',', columns: colArray}, function(err, output){
				// Skip this many rows
				var length = Object.keys(output).length;
				var projectProcessed = 0;
				// console.log("length",length);
				var promises = [];
				Object.keys(output).forEach(function(key, index) {
					if (index > 0) {
						var row = output[key];
						var id = 0;
						if (!isNaN(row.id)) {
							id = parseInt(row.id);
						}
						var newObj = null;
						var newProponent = {
							name: row.Proponent
						};
						var query = {epicProjectID: id};
						if (projectType === "mem") {
							query = { memPermitID: row.id };
							newObj = {
								memPermitID			: row.id,
								ownership 			: row.Ownership,
								commodity 			: row.Commodity,
								tailingsImpoundments: row.TailingsImpoundments,
								roles 				: ['mem', 'public'],
								read 				: ['public'],
								submit 				: ['mem'],
								type 				: row.type
							};
						} else {
							query = { epicProjectID: parseInt(row.id) };
							newObj = {
								epicProjectID 	: id,
								name 			: row.ProjectName,
								shortName 		: row.ProjectName.toLowerCase ().replace(/\//g,'-').replace (' ', '-').substr (0, row.ProjectName.length+1),
								roles 			: ['eao', 'public'],
								read 			: ['public'],
								submit 			: ['eao'],
								description 	: row.description,
								region 			: row.Region.toLowerCase ().replace(' region',''),
								sector 			: row.sector,
								locSpatial 		: row.locSpatial,
								location 		: row.locDescription,
								lat 			: row.lat,
								lon 			: row.long,
								provElecDist 	: row.provincialED,
								fedElecDist 	: row.federalED,
								projectNotes 	: row.projectNotes,
								type 			: row.projectType,
								intake: {
									constructionjobs 		: row.constructionjobs,
									constructionjobsNotes 	: row.constructionjobsNotes,
									operatingjobs 			: row.operatingjobs,
									operatingjobsNotes 		: row.operatingjobsNotes,
									investment 				: row.investment,
									investmentNotes 		: row.investmentNotes
								},
								eaActive 				: row.eaActive,
								CEAAInvolvement 		: row.CEAAInvolvement,
								eaIssues 				: row.eaIssues,
								eaNotes 				: row.eaNotes,
								responsibleEPD 			: row.responsibleEPD,
								responsibleEPDPhone		: row.phoneEPD,
								responsibleEPDEmail 	: row.emailEPD,
								projectLead 			: row.projectLead,
								projectLeadPhone		: row.projectLeadPhone,
								projectLeadEmail 		: row.projectLeadEmail,
								projectAnalyst 			: row.projectAnalyst,
								projectAssistant 		: row.projectAssistant,
								administrativeAssistant : row.administrativeAssistant,
								CELead 					: row.CELead,
								CELeadPhone				: row.CELeadPhone,
								CELeadEmail				: row.CELeadEmail,
								teamNotes				: row.teamNotes,
								isPublished				: row.isPublished,
								epicStream 				: row.Stream
							};
						}
						promises.push({obj: newObj, query: query, proponent: newProponent, phase: row.phase});
					}
				});

				Promise.resolve ()
				.then (function () {
					return promises.reduce (function (current, item) {
						return current.then (function () {
							// console.log ('++ add phase ', code);
							return doProjectWork(item.obj, item.query)
							//
							// Sequential reduction of work moving from the tail of the original promise
							// array to the head, by returning a promise for the next 'then' clause each time
							// until the final doPhaseWork completes.  Only then will this promise reduction
							// finally resolve for the .then of the original resolving Promise.resolve().
							//
							.then(function (project) {
								return doOrgWork(item.proponent, project);
							})
							.then(function (org) {
								return doPhaseWork(org, item.phase);
							});
						});
					}, Promise.resolve());
				})
				.then (resolve, reject);
			}); // CSV Parse
		}); // Read File
	});
};

<|endoftext|>