<commit_before>var mapContainer = $("#map"),
    map,
    start_year = 2010,
    start_month = 8,
    priceContainer = $("#price-chart");

var states = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
// event info
var type = ['Decriminalization Laws', 'Medical Cannabis Laws',
            'Both Medical and Decriminalization Laws', 'Legalized Cannabis'];

var curr_events;
var events = [
     // events that happened before 2010
     { date: new Date(2000, 1, 1), state: 'ME',  fillKey: type[2], description: 'It removes state-level criminal penalties on the use, possession and cultivation of marijuana by patients who possess an oral or written "professional opinion" from their physician that he or she "might benefit from the medical use of marijuana"', latitude: 45.167, longitude: -69.051, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'CA',  fillKey: type[2], description: '', latitude: 36.93, longitude: -119.86, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NV',  fillKey: type[2], description: '', latitude: 39.89, longitude: -116.87, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'OR',  fillKey: type[2], description: '', latitude: 43.967, longitude: -120.591, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NM',  fillKey: type[1], description: '', latitude: 34.61, longitude: -105.98, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MT',  fillKey: type[1], description: '', latitude: 46.99, longitude: -109.89, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NE',  fillKey: type[0], description: '', latitude: 41.39, longitude: -99.52, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MN',  fillKey: type[0], description: '', latitude: 46.12, longitude: -94.64, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'AK',  fillKey: type[2], description: '', latitude: 65.62, longitude: -150.14, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'HI',  fillKey: type[1], description: '', latitude: 21.02, longitude: -157.08, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MI',  fillKey: type[0], description: '', latitude: 32.82, longitude: -89.74, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NY',  fillKey: type[0], description: '', latitude: 43.17, longitude: -75.74, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MI',  fillKey: type[1], description: '', latitude: 43.30, longitude: -84.49, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NC',  fillKey: type[0], description: '', latitude: 35.88, longitude: -79.09, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'OH',  fillKey: type[0], description: '', latitude: 40.41, longitude: -82.75, radius: 5
  }, {
    date: new Date(2010, 0, 11),
    state: 'NJ',
    fillKey: type[1],
    description: 'New Jersey Becomes 14th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 39.367,
    longitude: -74.751,
    radius: 5
  }, {
    date: new Date(2010, 10, 2),
    state: 'AZ',
    fillKey: type[1],
    description: 'Arizona Becomes 15th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 34.251,
    longitude: -111.785,
    radius: 5
  }, {
    date: new Date(2011, 4, 13),
    state: 'DE',
    fillKey: type[1],
    description: 'May 13, 2011 - Delaware Becomes 16th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 38.891,
    longitude: -75.410,
    radius: 5
  }, {
    date: new Date(2011, 6, 1),
    state: 'CT',
    fillKey: type[0],
    description: 'Gov. Dan Malloy signed legislation into law ‘decriminalizing’ the possession of small, personal use amounts of marijuana by adults',
    latitude: 41.67,
    longitude: -72.721,
    radius: 5
  }, {
    date: new Date(2012, 4, 31),
    state: 'CT',
    fillKey: type[1],
    description: 'Connecticut Becomes 17th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 41.67,
    longitude: -72.721,
    radius: 5
  }, {
    date: new Date(2012, 10, 6),
    state: 'MA',
    fillKey: type[1],
    description: 'Massachusetts Becomes 18th state to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 42.407,
    longitude: -72.465,
    radius: 5
  }, {
    date: new Date(2012, 11, 1),
    state: 'CO',
    fillKey: type[3],
    description: ' Fifty-five percent of Colorado voters approved Amendment 64, which legalizes the adult personal use of cannabis',
    latitude: 39.095,
    longitude: -105.776,
    radius: 5
  }, {
    date: new Date(2012, 11, 1),
    state: 'WA',
    fillKey: type[3],
    description: 'Fifty-six percent of voters approved Initiative 502, permitting an adult to possess up to one-ounce of cannabis for their own personal use in private',
    latitude: 47.338,
    longitude: -120.014,
    radius: 5
  }, {
    date: new Date(2013, 6, 1),
    state: 'NH',
    fillKey: type[1],
    description: 'New Hampshire Becomes 19th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 43.357,
    longitude: -71.589,
    radius: 5
  }, {
    date: new Date(2013, 7, 1),
    state: 'IL',
    fillKey: type[1],
    description: 'Illinois Becomes 20th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 40.245,
    longitude: -89.472,
    radius: 5
  }
];

// map drawing taken care of by datamaps: http://datamaps.github.io/
function drawMap() {
  mapContainer.empty();

  map = new Datamap({
    element: mapContainer[0],
    scope: 'usa',
    fills: {
      defaultFill: '#eeeeee',
      'Decriminalization Laws': '#F0AD4E',
      'Medical Cannabis Laws': '#D9534F',
      'Both Medical and Decriminalization Laws': '#5BC0DE',
      'Legalized Cannabis': '#886AB5'
    }
  });
}

function drawEvents() {
  var curr_date = new Date(start_year, start_month + parseInt(timeSlider.val()));
  curr_events = events.filter(function(e) { if (e.date <= curr_date) return e });

  // bubbles for key events based on current year
  map.bubbles(curr_events, {
    borderWidth: 0,
    fillOpacity: 1,
    //highlightOnHover: false,
  });
}

function colorMap() {
  var date = new Date(start_year, start_month + parseInt($("#time-slider").val())),
      year = date.getFullYear(),
      month = date.getMonth() + 1,
      quality = $("#quality-menu").val();

  d3.json("/data/averages/" + year + "/" + month + ".json", function(error, json) {
    if (error) return console.warn(error);

    var color = d3.scale.linear()
      .domain([0, 35])
      .range(["#FCF8E3", "#84C569"]);

    var choropleth = { };

    $.each(states, function(i, state) {
      choropleth[state] = "#eeeeee";
    });

    $.each(json, function(i, row) {
      if (quality == "high" && row.value.high_avg) {
        choropleth[row._id] = color(row.value.high_avg);
      } else if (quality == "medium" && row.value.mid_avg) {
        choropleth[row._id] = color(row.value.mid_avg);
      } else if (quality == "low" && row.value.low_avg) {
        choropleth[row._id] = color(row.value.low_avg);
      } else {
        choropleth[row._id] = "#eeeeee";
      }
    });

    map.updateChoropleth(choropleth);
  });
}

function trendChart() {
  var margin = {top: 20, right: 20, bottom: 30, left: 50},
      width = 850 - margin.left - margin.right,
      height = 200 - margin.top - margin.bottom,
      trends;

  var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;

  var x = d3.time.scale()
      .range([0, width]);
  var y = d3.scale.linear()
      .range([height, 0]);
  var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom");
  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left")
      .ticks(5);

  var line = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.val); });

  var svg = d3.select(mapContainer[0]).append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  // just get US data for now
  d3.json("/data/us.json", function(error, json) {
    if (error) return console.warn(error);

    trends = json.trends;
    trends.forEach(function(d) {
      d.date = parseDate(d.date);
      d.val = +d.val;
    });

    x.domain(d3.extent(trends, function(d) { return d.date; }));
    y.domain([0,100]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("x", 50)
        .attr("dy", ".71em")
        .style("text-anchor", "center")
        .text("Google Trends");

    svg.append("path")
        .datum(trends)
        .attr("class", "line")
        .attr("d", line(trends));
  });
}

// lazy responsive map hack
/*$(window).resize(function() {
  drawMap();
})*/

// form field listeners
// TODO: change what bubbles are shown according to active date
var timeSlider = $("#time-slider"),
    qualityMenu = $("#quality-menu"),
    timeBack = $("#time-back"),
    timePlay = $("#time-play"),
    timeNext = $("#time-next"),
    currentDate = $("#current-date"),
    playInterval,
    isPlaying = false;

timeSlider.on('change', updateTime);
qualityMenu.on('change', colorMap);

timeBack.on('click', function() {
  timeSlider.val(parseInt(timeSlider.val()) - 1);
  updateTime();
});

timePlay.on('click', function() {
  isPlaying = !isPlaying;

  if (!isPlaying) {
    timePlay.find('.glyphicon').removeClass('glyphicon-pause').addClass('glyphicon-play')

    clearInterval(playInterval);
  } else {
    timePlay.find('.glyphicon').removeClass('glyphicon-play').addClass('glyphicon-pause')

    nextTime();

    playInterval = setInterval(nextTime, 1000);
  }
})

timeNext.on('click', nextTime);

function nextTime() {
  timeSlider.val(parseInt(timeSlider.val()) + 1);
  updateTime();
}

function updateTime() {
  var date = new Date(start_year, start_month + parseInt($("#time-slider").val()));

  currentDate.find('.lead').html(moment(date).format('MMMM YYYY'));
  drawEvents();
  colorMap();
}

//$("#current-date-menu").on('change', colorMap, drawEvents);

// initializing code
function initialize() {
  drawMap();
  colorMap();
  drawEvents();
  trendChart();
}

initialize();
<commit_msg>put line chart on the correct div<commit_after>var mapContainer = $("#map"),
    map,
    start_year = 2010,
    start_month = 8,
    priceContainer = $("#price-chart");

var states = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
// event info
var type = ['Decriminalization Laws', 'Medical Cannabis Laws',
            'Both Medical and Decriminalization Laws', 'Legalized Cannabis'];

var curr_events;
var events = [
     // events that happened before 2010
     { date: new Date(2000, 1, 1), state: 'ME',  fillKey: type[2], description: 'It removes state-level criminal penalties on the use, possession and cultivation of marijuana by patients who possess an oral or written "professional opinion" from their physician that he or she "might benefit from the medical use of marijuana"', latitude: 45.167, longitude: -69.051, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'CA',  fillKey: type[2], description: '', latitude: 36.93, longitude: -119.86, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NV',  fillKey: type[2], description: '', latitude: 39.89, longitude: -116.87, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'OR',  fillKey: type[2], description: '', latitude: 43.967, longitude: -120.591, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NM',  fillKey: type[1], description: '', latitude: 34.61, longitude: -105.98, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MT',  fillKey: type[1], description: '', latitude: 46.99, longitude: -109.89, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NE',  fillKey: type[0], description: '', latitude: 41.39, longitude: -99.52, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MN',  fillKey: type[0], description: '', latitude: 46.12, longitude: -94.64, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'AK',  fillKey: type[2], description: '', latitude: 65.62, longitude: -150.14, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'HI',  fillKey: type[1], description: '', latitude: 21.02, longitude: -157.08, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MI',  fillKey: type[0], description: '', latitude: 32.82, longitude: -89.74, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NY',  fillKey: type[0], description: '', latitude: 43.17, longitude: -75.74, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'MI',  fillKey: type[1], description: '', latitude: 43.30, longitude: -84.49, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'NC',  fillKey: type[0], description: '', latitude: 35.88, longitude: -79.09, radius: 5
  }, { date: new Date(2000, 1, 1), state: 'OH',  fillKey: type[0], description: '', latitude: 40.41, longitude: -82.75, radius: 5
  }, {
    date: new Date(2010, 0, 11),
    state: 'NJ',
    fillKey: type[1],
    description: 'New Jersey Becomes 14th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 39.367,
    longitude: -74.751,
    radius: 5
  }, {
    date: new Date(2010, 10, 2),
    state: 'AZ',
    fillKey: type[1],
    description: 'Arizona Becomes 15th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 34.251,
    longitude: -111.785,
    radius: 5
  }, {
    date: new Date(2011, 4, 13),
    state: 'DE',
    fillKey: type[1],
    description: 'May 13, 2011 - Delaware Becomes 16th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 38.891,
    longitude: -75.410,
    radius: 5
  }, {
    date: new Date(2011, 6, 1),
    state: 'CT',
    fillKey: type[0],
    description: 'Gov. Dan Malloy signed legislation into law ‘decriminalizing’ the possession of small, personal use amounts of marijuana by adults',
    latitude: 41.67,
    longitude: -72.721,
    radius: 5
  }, {
    date: new Date(2012, 4, 31),
    state: 'CT',
    fillKey: type[1],
    description: 'Connecticut Becomes 17th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 41.67,
    longitude: -72.721,
    radius: 5
  }, {
    date: new Date(2012, 10, 6),
    state: 'MA',
    fillKey: type[1],
    description: 'Massachusetts Becomes 18th state to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 42.407,
    longitude: -72.465,
    radius: 5
  }, {
    date: new Date(2012, 11, 1),
    state: 'CO',
    fillKey: type[3],
    description: ' Fifty-five percent of Colorado voters approved Amendment 64, which legalizes the adult personal use of cannabis',
    latitude: 39.095,
    longitude: -105.776,
    radius: 5
  }, {
    date: new Date(2012, 11, 1),
    state: 'WA',
    fillKey: type[3],
    description: 'Fifty-six percent of voters approved Initiative 502, permitting an adult to possess up to one-ounce of cannabis for their own personal use in private',
    latitude: 47.338,
    longitude: -120.014,
    radius: 5
  }, {
    date: new Date(2013, 6, 1),
    state: 'NH',
    fillKey: type[1],
    description: 'New Hampshire Becomes 19th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 43.357,
    longitude: -71.589,
    radius: 5
  }, {
    date: new Date(2013, 7, 1),
    state: 'IL',
    fillKey: type[1],
    description: 'Illinois Becomes 20th State to Legalize Medical Marijuana',
    specificDate: true,
    latitude: 40.245,
    longitude: -89.472,
    radius: 5
  }
];

// map drawing taken care of by datamaps: http://datamaps.github.io/
function drawMap() {
  mapContainer.empty();

  map = new Datamap({
    element: mapContainer[0],
    scope: 'usa',
    fills: {
      defaultFill: '#eeeeee',
      'Decriminalization Laws': '#F0AD4E',
      'Medical Cannabis Laws': '#D9534F',
      'Both Medical and Decriminalization Laws': '#5BC0DE',
      'Legalized Cannabis': '#886AB5'
    }
  });
}

function drawEvents() {
  var curr_date = new Date(start_year, start_month + parseInt(timeSlider.val()));
  curr_events = events.filter(function(e) { if (e.date <= curr_date) return e });

  // bubbles for key events based on current year
  map.bubbles(curr_events, {
    borderWidth: 0,
    fillOpacity: 1,
    //highlightOnHover: false,
  });
}

function colorMap() {
  var date = new Date(start_year, start_month + parseInt($("#time-slider").val())),
      year = date.getFullYear(),
      month = date.getMonth() + 1,
      quality = $("#quality-menu").val();

  d3.json("/data/averages/" + year + "/" + month + ".json", function(error, json) {
    if (error) return console.warn(error);

    var color = d3.scale.linear()
      .domain([0, 35])
      .range(["#FCF8E3", "#84C569"]);

    var choropleth = { };

    $.each(states, function(i, state) {
      choropleth[state] = "#eeeeee";
    });

    $.each(json, function(i, row) {
      if (quality == "high" && row.value.high_avg) {
        choropleth[row._id] = color(row.value.high_avg);
      } else if (quality == "medium" && row.value.mid_avg) {
        choropleth[row._id] = color(row.value.mid_avg);
      } else if (quality == "low" && row.value.low_avg) {
        choropleth[row._id] = color(row.value.low_avg);
      } else {
        choropleth[row._id] = "#eeeeee";
      }
    });

    map.updateChoropleth(choropleth);
  });
}

function trendChart() {
  var margin = {top: 20, right: 20, bottom: 30, left: 50},
      width = 850 - margin.left - margin.right,
      height = 200 - margin.top - margin.bottom,
      trends;

  var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;

  var x = d3.time.scale()
      .range([0, width]);
  var y = d3.scale.linear()
      .range([height, 0]);
  var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom");
  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left")
      .ticks(5);

  var line = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.val); });

  var svg = d3.select(priceContainer[0]).append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  // just get US data for now
  d3.json("/data/us.json", function(error, json) {
    if (error) return console.warn(error);

    trends = json.trends;
    trends.forEach(function(d) {
      d.date = parseDate(d.date);
      d.val = +d.val;
    });

    x.domain(d3.extent(trends, function(d) { return d.date; }));
    y.domain([0,100]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("x", 50)
        .attr("dy", ".71em")
        .style("text-anchor", "center")
        .text("Google Trends");

    svg.append("path")
        .datum(trends)
        .attr("class", "line")
        .attr("d", line(trends));
  });
}

// lazy responsive map hack
/*$(window).resize(function() {
  drawMap();
})*/

// form field listeners
// TODO: change what bubbles are shown according to active date
var timeSlider = $("#time-slider"),
    qualityMenu = $("#quality-menu"),
    timeBack = $("#time-back"),
    timePlay = $("#time-play"),
    timeNext = $("#time-next"),
    currentDate = $("#current-date"),
    playInterval,
    isPlaying = false;

timeSlider.on('change', updateTime);
qualityMenu.on('change', colorMap);

timeBack.on('click', function() {
  timeSlider.val(parseInt(timeSlider.val()) - 1);
  updateTime();
});

timePlay.on('click', function() {
  isPlaying = !isPlaying;

  if (!isPlaying) {
    timePlay.find('.glyphicon').removeClass('glyphicon-pause').addClass('glyphicon-play')

    clearInterval(playInterval);
  } else {
    timePlay.find('.glyphicon').removeClass('glyphicon-play').addClass('glyphicon-pause')

    nextTime();

    playInterval = setInterval(nextTime, 1000);
  }
})

timeNext.on('click', nextTime);

function nextTime() {
  timeSlider.val(parseInt(timeSlider.val()) + 1);
  updateTime();
}

function updateTime() {
  var date = new Date(start_year, start_month + parseInt($("#time-slider").val()));

  currentDate.find('.lead').html(moment(date).format('MMMM YYYY'));
  drawEvents();
  colorMap();
}

//$("#current-date-menu").on('change', colorMap, drawEvents);

// initializing code
function initialize() {
  drawMap();
  colorMap();
  drawEvents();
  trendChart();
}

initialize();
<|endoftext|>


<commit_before>import React from 'react';
import { VictoryAxis, VictoryChart, VictoryLabel, VictoryLine, VictoryTheme } from 'victory';

function readableNumber(number) {
  var scale = ['', 'k', 'm'];
  var exponent = Math.floor(Math.log(number) / Math.log(1000));
  return (number / Math.pow(1000, exponent)).toFixed(0) + scale[exponent];
}

function TrendGraph(props) {
  let measurements = [];
  let max_y = 10;
  for (var i = 0; i < props.measurements.length; i++) {
    const measurement = props.measurements[i];
    const m = measurement.value !== null ? Number(measurement.value) : null;
    if (m !== null && m > max_y) { max_y = m }
    const x1 = new Date(measurement.start);
    const x2 = new Date(measurement.end);
    measurements.push({ y: m, x: x1 });
    measurements.push({ y: m, x: x2 });
  }
  const axisStyle = { axisLabel: { padding: 30, fontSize: 11 }, tickLabels: { fontSize: 8 } };
  return (
    <VictoryChart
      height={250}
      scale={{ x: "time", y: "linear" }}
      style={{ parent: { height: 400, width: "90vw", background: "white" } }}
      theme={VictoryTheme.material}
      width={750}
    >
      <VictoryLabel x={375} y={10} text={props.title} textAnchor="middle" />
      <VictoryAxis
        label={"Time"}
        style={axisStyle} />
      <VictoryAxis
        dependentAxis
        domain={[0, max_y + 10]}
        label={props.unit}
        style={axisStyle}
        tickFormat={(t) => `${readableNumber(t)}`} />
      <VictoryLine
        data={measurements}
        interpolation="stepBefore"
        style={{ data: { stroke: "black", strokeWidth: 1 } }} />
    </VictoryChart>
  )
}

export { TrendGraph };
<commit_msg>Fix graph title. (#288)<commit_after>import React from 'react';
import { VictoryAxis, VictoryChart, VictoryLabel, VictoryLine, VictoryTheme } from 'victory';

function readableNumber(number) {
  var scale = ['', 'k', 'm'];
  var exponent = Math.floor(Math.log(number) / Math.log(1000));
  return (number / Math.pow(1000, exponent)).toFixed(0) + scale[exponent];
}

function TrendGraph(props) {
  let measurements = [];
  let max_y = 10;
  for (var i = 0; i < props.measurements.length; i++) {
    const measurement = props.measurements[i];
    const m = measurement.value !== null ? Number(measurement.value) : null;
    if (m !== null && m > max_y) { max_y = m }
    const x1 = new Date(measurement.start);
    const x2 = new Date(measurement.end);
    measurements.push({ y: m, x: x1 });
    measurements.push({ y: m, x: x2 });
  }
  const axisStyle = { axisLabel: { padding: 30, fontSize: 11 }, tickLabels: { fontSize: 8 } };
  return (
    <VictoryChart
      height={250}
      scale={{ x: "time", y: "linear" }}
      style={{ parent: { height: 400, width: "90vw", background: "white" } }}
      theme={VictoryTheme.material}
      width={750}
    >
      <VictoryLabel x={375} y={20} text={props.title} textAnchor="middle" />
      <VictoryAxis
        label={"Time"}
        style={axisStyle} />
      <VictoryAxis
        dependentAxis
        domain={[0, max_y + 10]}
        label={props.unit}
        style={axisStyle}
        tickFormat={(t) => `${readableNumber(t)}`} />
      <VictoryLine
        data={measurements}
        interpolation="stepBefore"
        style={{ data: { stroke: "black", strokeWidth: 1 } }} />
    </VictoryChart>
  )
}

export { TrendGraph };
<|endoftext|>


<commit_before>import Rx from '@reactivex/rxjs/dist/cjs/Rx';
import io from 'socket.io-client';
import config from '../config';

const socket = io.connect(config.busAddress);
//Rx.Observable.fromEvent(socket, 'trackables');

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowRight')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'right' }));

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowLeft')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'left' }));

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowUp')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'straight' }));

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowDown')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'stop' }));

const trackables = Rx.Observable
    .fromEvent(socket, 'trackables')
    .throttleTime(500)
    .subscribe(msg => {
        let dest = {
            x: 500,
            y: 500
        }

        let purples = msg.filter(t => t.rectangle.color === 'custom');
        if (purples.length === 5) {
            let corners = calculateCorners(purples);
            let others = filterCorners(purples, corners);
            if (others.length === 1) {
                dest.x = others[0].x;
                dest.y = others[0].y;
                console.log(`dest ${dest.x},${dest.y}`);
            }
        }

        let yellows = msg.filter(t => t.rectangle.color === 'yellow');
        if (yellows.length === 3) {
            let d1 = distance(yellows[0], yellows[1]);
            let d2 = distance(yellows[1], yellows[2]);
            let d3 = distance(yellows[2], yellows[0]);

            let front, back1, back2;
            if (d1 < d2 && d1 < d3) {
                front = yellows[2];
                back1 = yellows[0];
                back2 = yellows[1];
            } else if (d2 < d1 && d2 < d3) {
                front = yellows[0];
                back1 = yellows[1];
                back2 = yellows[2];
            } else if (d3 < d2 && d3 < d1) {
                front = yellows[1];
                back1 = yellows[0];
                back2 = yellows[2];
            }

            let midpoint = {
                x: (back1.x + back2.x) / 2,
                y: (back1.y + back2.y) / 2
            }
            console.log(`(${front.x},${front.y})(${back1.x},${back1.y})(${back2.x},${back2.y})(${midpoint.x},${midpoint.y})`);

            let angle = rad2deg(angleBetween(front, midpoint, dest));
            console.log(`angle: ${angle}`);

            if (Math.abs(angle) < 20) {
                // rover straight
                socket.emit('command', { target: 'lego-ev3', command: 'straight' });
                setTimeout(function () {
                    socket.emit('command', { target: 'lego-ev3', command: 'stop' });
                }, 1000);
            } else {
                // rover turn
                socket.emit('command', { target: 'lego-ev3', command: 'left' });
                setTimeout(function () {
                    socket.emit('command', { target: 'lego-ev3', command: 'stop' });
                }, 500);
            }

        }
    });

function angleBetween(A, B, C) {
    var AB = Math.sqrt(Math.pow(B.x - A.x, 2) + Math.pow(B.y - A.y, 2));
    var BC = Math.sqrt(Math.pow(B.x - C.x, 2) + Math.pow(B.y - C.y, 2));
    var AC = Math.sqrt(Math.pow(C.x - A.x, 2) + Math.pow(C.y - A.y, 2));
    return Math.acos((BC * BC + AB * AB - AC * AC) / (2 * BC * AB));
}
function rad2deg(radians) {
    return radians * 180 / Math.PI;
}
function distance(p1, p2) {
    return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

function calculateCorners(data) {
    if (data.length < 4) {
        return undefined;
    }

    var topLeft = data
        .sort((a, b) => a.x - b.x)
        .slice(0, 2)
        .sort((a, b) => a.y - b.y)
        .slice(0, 1)[0];

    var topRight = data
        .sort((a, b) => b.x - a.x)
        .slice(0, 2)
        .sort((a, b) => a.y - b.y)
        .slice(0, 1)[0];

    var bottomLeft = data
        .sort((a, b) => b.y - a.y)
        .slice(0, 2)
        .sort((a, b) => a.x - b.x)
        .slice(0, 1)[0];

    var bottomRight = data
        .sort((a, b) => b.y - a.y)
        .slice(0, 2)
        .sort((a, b) => b.x - a.x)
        .slice(0, 1)[0];

    return [
        topLeft,
        topRight,
        bottomRight,
        bottomLeft
    ];
}

function filterCorners(eventData, corners) {
    return eventData.filter(i => {
        return !corners.some(c => i.x === c.x && i.y === c.y)
    });
}<commit_msg>added left and right turn<commit_after>import Rx from '@reactivex/rxjs/dist/cjs/Rx';
import io from 'socket.io-client';
import config from '../config';

const socket = io.connect(config.busAddress);
//Rx.Observable.fromEvent(socket, 'trackables');

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowRight')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'right' }));

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowLeft')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'left' }));

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowUp')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'straight' }));

Rx.Observable
    .fromEvent(document, 'keydown')
    .filter(e => e.code === 'ArrowDown')
    .subscribe(e => socket.emit('command', { target: 'lego-ev3', command: 'stop' }));

const trackables = Rx.Observable
    .fromEvent(socket, 'trackables')
    .throttleTime(1500)
    .subscribe(msg => {
        let dest = {
            x: 500,
            y: 500
        }

        let purples = msg.filter(t => t.rectangle.color === 'custom');
        if (purples.length === 5) {
            let corners = calculateCorners(purples);
            let others = filterCorners(purples, corners);
            if (others.length === 1) {
                dest.x = others[0].x;
                dest.y = others[0].y;
                console.log(`dest ${dest.x},${dest.y}`);
            }
        }

        let yellows = msg.filter(t => t.rectangle.color === 'yellow');
        if (yellows.length === 3) {
            let d1 = distance(yellows[0], yellows[1]);
            let d2 = distance(yellows[1], yellows[2]);
            let d3 = distance(yellows[2], yellows[0]);

            let front, back1, back2;
            if (d1 < d2 && d1 < d3) {
                front = yellows[2];
                back1 = yellows[0];
                back2 = yellows[1];
            } else if (d2 < d1 && d2 < d3) {
                front = yellows[0];
                back1 = yellows[1];
                back2 = yellows[2];
            } else if (d3 < d2 && d3 < d1) {
                front = yellows[1];
                back1 = yellows[0];
                back2 = yellows[2];
            }

            let midpoint = {
                x: (back1.x + back2.x) / 2,
                y: (back1.y + back2.y) / 2
            }
            console.log(`(${front.x},${front.y})(${back1.x},${back1.y})(${back2.x},${back2.y})(${midpoint.x},${midpoint.y})`);

            let angle = rad2deg(angleBetween(front, midpoint, dest));
            console.log(`angle: ${angle}`);
            let destLeft = isLeft(front, midpoint, dest);
            console.log(`isLeft: ${isLeft}`);

            console.log('distance:' + distance(front, dest));
            if (distance(front, dest) > 100) {
                if (Math.abs(angle) < 20) {
                    // rover straight
                    socket.emit('command', { target: 'lego-ev3', command: 'straight' });
                    setTimeout(function () {
                        socket.emit('command', { target: 'lego-ev3', command: 'stop' });
                    }, 1500);
                } else {
                    // rover turn
                    let time = Math.max(50, Math.floor(Math.abs(angle) / 10) * 100);
                    console.log(`turn ${time}ms`);

                    if (destLeft) {
                        socket.emit('command', { target: 'lego-ev3', command: 'left' });
                    } else {
                        socket.emit('command', { target: 'lego-ev3', command: 'right' });
                    }
                    setTimeout(function () {
                        socket.emit('command', { target: 'lego-ev3', command: 'stop' });
                    }, time);
                }
            }

        }
    });

function angleBetween(A, B, C) {
    var AB = Math.sqrt(Math.pow(B.x - A.x, 2) + Math.pow(B.y - A.y, 2));
    var BC = Math.sqrt(Math.pow(B.x - C.x, 2) + Math.pow(B.y - C.y, 2));
    var AC = Math.sqrt(Math.pow(C.x - A.x, 2) + Math.pow(C.y - A.y, 2));
    return Math.acos((BC * BC + AB * AB - AC * AC) / (2 * BC * AB));
}
function rad2deg(radians) {
    return radians * 180 / Math.PI;
}
function distance(p1, p2) {
    return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
function isLeft(lineA, lineB, point) {
    return ((lineB.x - lineA.x) * (point.y - lineA.y) - (lineB.y - lineA.y) * (point.x - lineA.x)) > 0;
}

function calculateCorners(data) {
    if (data.length < 4) {
        return undefined;
    }

    var topLeft = data
        .sort((a, b) => a.x - b.x)
        .slice(0, 2)
        .sort((a, b) => a.y - b.y)
        .slice(0, 1)[0];

    var topRight = data
        .sort((a, b) => b.x - a.x)
        .slice(0, 2)
        .sort((a, b) => a.y - b.y)
        .slice(0, 1)[0];

    var bottomLeft = data
        .sort((a, b) => b.y - a.y)
        .slice(0, 2)
        .sort((a, b) => a.x - b.x)
        .slice(0, 1)[0];

    var bottomRight = data
        .sort((a, b) => b.y - a.y)
        .slice(0, 2)
        .sort((a, b) => b.x - a.x)
        .slice(0, 1)[0];

    return [
        topLeft,
        topRight,
        bottomRight,
        bottomLeft
    ];
}

function filterCorners(eventData, corners) {
    return eventData.filter(i => {
        return !corners.some(c => i.x === c.x && i.y === c.y)
    });
}<|endoftext|>


<commit_before>import LoginModal from './component';

export default LoginModal;
<commit_msg>Restores user action in login modal<commit_after>import { connect } from 'react-redux';

// actions
import { setUser } from 'redactions/user';

// component
import LoginModal from './component';

export default connect(
  null,
  { setUser }
)(LoginModal);
<|endoftext|>


<commit_before>'use strict';
const yeoman = require('yeoman-generator'),
  chalk = require('chalk'),
  yosay = require('yosay'),
  bakery = require('../lib/bakery'),
  feedback = require('../lib/feedback'),
  debug = require('debug')('bakery:generator:index'),
  mkdirp = require('mkdirp'),
  path = require('path'),
  _ = require('lodash');

const CM_TOOLS = ['chef', 'puppet', 'bash'];

var BakeryGenerator = yeoman.Base.extend({

  constructor: function() {
    yeoman.Base.apply(this, arguments);
    this._options.help.desc = 'Show this help';

    /** @property {object} answers - prompt answers */
    this.answers = {};
    this.existingProject = false;

    this.argument('projectname', {
      type: String,
      required: function() {
        return this.projectname != Undefined;
      }
    });

    this.option('awsprofile', {
      type: String,
      alias: 'p',
      desc: 'Name of the AWS profile to use when calling the AWS api for value validation'
    });
  },

  initializing: {
    loadConfig: function() {
      var configFound = this.baseName !== undefined && this.applicationType !== undefined;
      if (configFound) {
        this.existingProject = true;
      }
    }
  },

  default: {
    function() {
      if (path.basename(this.destinationPath()) !== this.projectname) {
        mkdirp(this.projectname);
        this.destinationRoot(this.destinationPath(this.projectname));
      }
    },

    /*saveConfig: function() {
      this.config.set('projectname', this.projectname);
      this.config.saveConfig()
    },*/
  },

  prompting: function() {
    process.env.AWS_PROFILE = this.options.awsprofile || 'default';
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the super-excellent ' + chalk.red('bakery') + ' generator!'
    ));

    var prompts = [];

    return this.prompt(prompts).then(function(props) {
      this.props = props;
      process.env.PROJECTNAME = this.projectname;
      // this.composeWith('bakery:scm', {
      //   arguments: [process.env.PROJECTNAME]
      // }, {});
      this.composeWith('bakery:cm', {
        arguments: [process.env.PROJECTNAME]
      }, {});
      // this.composeWith('bakery:ci', {
      //   arguments: [process.env.PROJECTNAME]
      // }, {});
      this.composeWith('bakery:bake', {
        arguments: [process.env.PROJECTNAME]
      }, {});
    }.bind(this));
  },

  writing: function() {},

  install: function() {
    this.installDependencies();
  }
});

module.exports = BakeryGenerator;
<commit_msg>commented back in sub generators<commit_after>'use strict';
const yeoman = require('yeoman-generator'),
  chalk = require('chalk'),
  yosay = require('yosay'),
  bakery = require('../lib/bakery'),
  feedback = require('../lib/feedback'),
  debug = require('debug')('bakery:generator:index'),
  mkdirp = require('mkdirp'),
  path = require('path'),
  _ = require('lodash');

const CM_TOOLS = ['chef', 'puppet', 'bash'];

var BakeryGenerator = yeoman.Base.extend({

  constructor: function() {
    yeoman.Base.apply(this, arguments);
    this._options.help.desc = 'Show this help';

    /** @property {object} answers - prompt answers */
    this.answers = {};
    this.existingProject = false;

    this.argument('projectname', {
      type: String,
      required: function() {
        return this.projectname != Undefined;
      }
    });

    this.option('awsprofile', {
      type: String,
      alias: 'p',
      desc: 'Name of the AWS profile to use when calling the AWS api for value validation'
    });
  },

  initializing: {
    loadConfig: function() {
      var configFound = this.baseName !== undefined && this.applicationType !== undefined;
      if (configFound) {
        this.existingProject = true;
      }
    }
  },

  default: {
    function() {
      if (path.basename(this.destinationPath()) !== this.projectname) {
        mkdirp(this.projectname);
        this.destinationRoot(this.destinationPath(this.projectname));
      }
    },

    /*saveConfig: function() {
      this.config.set('projectname', this.projectname);
      this.config.saveConfig()
    },*/
  },

  prompting: function() {
    process.env.AWS_PROFILE = this.options.awsprofile || 'default';
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the super-excellent ' + chalk.red('bakery') + ' generator!'
    ));

    var prompts = [];

    return this.prompt(prompts).then(function(props) {
      this.props = props;
      process.env.PROJECTNAME = this.projectname;
      this.composeWith('bakery:scm', {
        arguments: [process.env.PROJECTNAME]
      }, {});
      this.composeWith('bakery:cm', {
        arguments: [process.env.PROJECTNAME]
      }, {});
      this.composeWith('bakery:ci', {
        arguments: [process.env.PROJECTNAME]
      }, {});
      this.composeWith('bakery:bake', {
        arguments: [process.env.PROJECTNAME]
      }, {});
    }.bind(this));
  },

  writing: function() {},

  install: function() {
    this.installDependencies();
  }
});

module.exports = BakeryGenerator;
<|endoftext|>


<commit_before>/**
 * La applicacion que se encarga de todo el tema del CRUD
 * de arcos recurvados
 */
var ArcosRecurvadosCrudApplication = BaseTemplateCrudApp.$extend({

    __init__: function(historyManager, element) {
        var formTemplate = '' +
            '<form role="form" class="form-horizontal">' +
                '
' +
                    'Nombre' +
                    '
' +
                        '<input type="text" name="nombre" id="nombre" class="form-control">' +
                    '
' +
                '
' +
                '
' +
                    'Comentario' +
                    '
' +
                        '<input type="text" name="comentario" id="comentario" class="form-control">' +
                    '
' +
                '
' +
                '<fieldset>' +
                    '<legend>Raiser</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_raiser" id="modelo_raiser" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_raiser" id="largo_raiser" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Palas</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_palas" id="modelo_palas" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_palas" id="largo_palas" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                    '
' +
                        'Libraje' +
                        '
' +
                            '<input type="text" name="libraje_palas" id="libraje_palas" class="form-control">' +
                            'El libraje de las palas. No el libraje que uno le saca a las mismas.' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Otras cosas</legend>' +
                    '
' +
                        'Modelo mira' +
                        '
' +
                            '<input type="text" name="modelo_mira" id="modelo_mira" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo clicker' +
                        '
' +
                            '<input type="text" name="modelo_clicker" id="modelo_clicker" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo rest' +
                        '
' +
                            '<input type="text" name="modelo_rest" id="modelo_rest" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo buttom' +
                        '
' +
                            '<input type="text" name="modelo_buttom" id="modelo_buttom" class="form-control">' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Barra Principal</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_barra_larga_estabilizacion" id="modelo_barra_larga_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_barra_larga_estabilizacion" id="largo_barra_larga_estabilizacion" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                    '
' +
                        'Peso adicional' +
                        '
' +
                            '<input type="text" name="peso_adicional_barra_larga" id="peso_adicional_barra_larga" class="form-control">' +
                            'Siempre que sea posible usar grames' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>VBar / Extender </legend>' +
                    '
' +
                        'Modelo VBar' +
                        '
' +
                            '<input type="text" name="modelo_vbar_estabilizacion" id="modelo_vbar_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo extender' +
                        '
' +
                            '<input type="text" name="modelo_extender_estabilizacion" id="modelo_extender_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo extender' +
                        '
' +
                            '<input type="text" name="largo_extender_estabilizacion" id="largo_extender_estabilizacion" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Barras laterales</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_barra_lateral_estabilizacion" id="modelo_barra_lateral_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_barra_lateral_estabilizacion" id="largo_barra_lateral_estabilizacion" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                    '
' +
                        'Peso adicional' +
                        '
' +
                            '<input type="text" name="peso_adicional_barra_lateral" id="peso_adicional_barra_lateral" class="form-control">' +
                            'Siempre que sea posible usar grames' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '
' +
                    '
' +
                        '<button type="submit" class="btn btn-primary button-save">Grabar</button>' +
                    '
' +
                '
' +
            '</form>';
        var columnNames = [
            'nombre',
            'modelo_raiser',
            'modelo_palas'
        ];
        this.$super(historyManager, 'arco-recurvado', formTemplate, element, columnNames);
    }
});

<commit_msg>Changed comment to textarea<commit_after>/**
 * La applicacion que se encarga de todo el tema del CRUD
 * de arcos recurvados
 */
var ArcosRecurvadosCrudApplication = BaseTemplateCrudApp.$extend({

    __init__: function(historyManager, element) {
        var formTemplate = '' +
            '<form role="form" class="form-horizontal">' +
                '
' +
                    'Nombre' +
                    '
' +
                        '<input type="text" name="nombre" id="nombre" class="form-control">' +
                    '
' +
                '
' +
                '
' +
                    'Comentario' +
                    '
' +
                        '<textarea name="comentario" id="comentario" class="form-control"></textarea>' +
                    '
' +
                '
' +
                '<fieldset>' +
                    '<legend>Raiser</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_raiser" id="modelo_raiser" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_raiser" id="largo_raiser" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Palas</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_palas" id="modelo_palas" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_palas" id="largo_palas" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                    '
' +
                        'Libraje' +
                        '
' +
                            '<input type="text" name="libraje_palas" id="libraje_palas" class="form-control">' +
                            'El libraje de las palas. No el libraje que uno le saca a las mismas.' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Otras cosas</legend>' +
                    '
' +
                        'Modelo mira' +
                        '
' +
                            '<input type="text" name="modelo_mira" id="modelo_mira" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo clicker' +
                        '
' +
                            '<input type="text" name="modelo_clicker" id="modelo_clicker" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo rest' +
                        '
' +
                            '<input type="text" name="modelo_rest" id="modelo_rest" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo buttom' +
                        '
' +
                            '<input type="text" name="modelo_buttom" id="modelo_buttom" class="form-control">' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Barra Principal</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_barra_larga_estabilizacion" id="modelo_barra_larga_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_barra_larga_estabilizacion" id="largo_barra_larga_estabilizacion" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                    '
' +
                        'Peso adicional' +
                        '
' +
                            '<input type="text" name="peso_adicional_barra_larga" id="peso_adicional_barra_larga" class="form-control">' +
                            'Siempre que sea posible usar grames' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>VBar / Extender </legend>' +
                    '
' +
                        'Modelo VBar' +
                        '
' +
                            '<input type="text" name="modelo_vbar_estabilizacion" id="modelo_vbar_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Modelo extender' +
                        '
' +
                            '<input type="text" name="modelo_extender_estabilizacion" id="modelo_extender_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo extender' +
                        '
' +
                            '<input type="text" name="largo_extender_estabilizacion" id="largo_extender_estabilizacion" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '<fieldset>' +
                    '<legend>Barras laterales</legend>' +
                    '
' +
                        'Modelo' +
                        '
' +
                            '<input type="text" name="modelo_barra_lateral_estabilizacion" id="modelo_barra_lateral_estabilizacion" class="form-control">' +
                        '
' +
                    '
' +
                    '
' +
                        'Largo' +
                        '
' +
                            '<input type="text" name="largo_barra_lateral_estabilizacion" id="largo_barra_lateral_estabilizacion" class="form-control">' +
                            'El mismo tiene que estar en pulgadas' +
                        '
' +
                    '
' +
                    '
' +
                        'Peso adicional' +
                        '
' +
                            '<input type="text" name="peso_adicional_barra_lateral" id="peso_adicional_barra_lateral" class="form-control">' +
                            'Siempre que sea posible usar grames' +
                        '
' +
                    '
' +
                '</fieldset>' +

                '
' +
                    '
' +
                        '<button type="submit" class="btn btn-primary button-save">Grabar</button>' +
                    '
' +
                '
' +
            '</form>';
        var columnNames = [
            'nombre',
            'modelo_raiser',
            'modelo_palas'
        ];
        this.$super(historyManager, 'arco-recurvado', formTemplate, element, columnNames);
    }
});

<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
Backbone.$ = $;

var ChildView = require('./child-view');
var MainEvents = require('../../events/main-events');
var PreambleHeadView = require('../header/preamble-head-view');
var CommentView = require('../comment/comment-view');
var CommentIndexView = require('../comment/comment-index-view');
var CommentEvents = require('../../events/comment-events');
var DrawerEvents = require('../../events/drawer-events');
var helpers = require('../../helpers');

var PreambleView = ChildView.extend({
  el: '#content-wrapper',

  events: {
    'click .activate-write': 'handleWriteLink'
  },

  initialize: function(options) {
    this.options = options;

    var parsed = helpers.parsePreambleId(this.options.id);
    var type = parsed.path[0];

    this.id = [parsed.docId].concat(parsed.path).join('-');
    this.options.scrollToId = parsed.hash;
    this.url = parsed.path.join('/');

    if (!options.render) {
      this.render();
    }

    ChildView.prototype.initialize.apply(this, arguments);

    this.listenTo(CommentEvents, 'read:proposal', this.handleRead);
    this.listenTo(CommentEvents, 'comment:write', this.handleWriteTab);
    this.listenTo(MainEvents, 'paragraph:active', this.handleParagraphActive);

    CommentEvents.trigger('comment:readTabOpen');
    DrawerEvents.trigger('pane:init', type === 'preamble' ? 'table-of-contents' : 'table-of-contents-secondary');
  },

  handleRead: function() {
    this.$write.hide();
    this.$read.show();
  },

  handleParagraphActive: function(id) {
    // update current Section ID as active paragraph changes
    this.currentSectionId = id;
  },

  handleWriteLink: function(e) {
    var $target = $(e.target);
    this.write(
      $target.data('section'),
      $target.data('label'),
      $target.closest('[data-permalink-section]')
    );

    CommentEvents.trigger('comment:writeTabOpen');
  },

  handleWriteTab: function() {
    var $section = $('#' + this.currentSectionId);

    this.write(
      $section.find('.activate-write').data('section'),
      $section.find('.activate-write').data('label'),
      $section
    );
  },

  write: function(section, label, $parent) {
    $parent = $parent.clone();
    $parent.find('.activate-write').remove();
    CommentEvents.trigger('comment:target', {
      section: section,
      label: label,
      $parent: $parent
    });
    this.$read.hide();
    this.$write.show();
  },

  render: function() {
    ChildView.prototype.render.apply(this, arguments);

    this.$read = this.$el.find('#preamble-read');
    this.$write = this.$el.find('#preamble-write');

    this.currentSectionId = this.$read.closest('section').attr('id');
    this.docId = this.$read.closest('section').data('doc-id');

    this.preambleHeadView = new PreambleHeadView();

    this.commentView = new CommentView({
      el: this.$write.find('.comment-wrapper'),
      section: this.currentSectionId,
      docId: this.docId
    });

    this.commentIndex = new CommentIndexView({
      el: this.$write.find('.comment-index'),
      docId: this.docId
    });

    if (this.options.mode === 'write') {
      var $parent = $('#' + this.options.section).find('[data-permalink-section]');
      this.write(this.options.section, this.options.label, $parent);
    } else {
      this.handleRead();
    }
  },

  remove: function() {
    this.commentView.remove();
    this.commentIndex.remove();
    Backbone.View.prototype.remove.call(this);
  }
});

module.exports = PreambleView;
<commit_msg>Show appropriate content on write toggle.<commit_after>'use strict';

var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
Backbone.$ = $;

var ChildView = require('./child-view');
var MainEvents = require('../../events/main-events');
var PreambleHeadView = require('../header/preamble-head-view');
var CommentView = require('../comment/comment-view');
var CommentIndexView = require('../comment/comment-index-view');
var CommentEvents = require('../../events/comment-events');
var DrawerEvents = require('../../events/drawer-events');
var helpers = require('../../helpers');

var PreambleView = ChildView.extend({
  el: '#content-wrapper',

  events: {
    'click .activate-write': 'handleWriteLink'
  },

  initialize: function(options) {
    this.options = options;

    var parsed = helpers.parsePreambleId(this.options.id);
    var type = parsed.path[0];

    this.id = [parsed.docId].concat(parsed.path).join('-');
    this.options.scrollToId = parsed.hash;
    this.url = parsed.path.join('/');

    if (!options.render) {
      this.render();
    }

    ChildView.prototype.initialize.apply(this, arguments);

    this.listenTo(CommentEvents, 'read:proposal', this.handleRead);
    this.listenTo(CommentEvents, 'comment:write', this.handleWriteTab);
    this.listenTo(MainEvents, 'paragraph:active', this.handleParagraphActive);

    CommentEvents.trigger('comment:readTabOpen');
    DrawerEvents.trigger('pane:init', type === 'preamble' ? 'table-of-contents' : 'table-of-contents-secondary');
  },

  handleRead: function() {
    this.$write.hide();
    this.$read.show();
  },

  handleParagraphActive: function(id) {
    // update current Section ID as active paragraph changes
    this.section = id;
  },

  handleWriteLink: function(e) {
    var $target = $(e.target);
    this.write(
      $target.data('section'),
      $target.data('label'),
      $target.closest('[data-permalink-section]')
    );

    CommentEvents.trigger('comment:writeTabOpen');
  },

  handleWriteTab: function() {
    var $section = $('#' + this.section);

    this.write(
      $section.find('.activate-write').data('section'),
      $section.find('.activate-write').data('label'),
      $section
    );
  },

  write: function(section, label, $parent) {
    $parent = $parent.clone();
    $parent.find('.activate-write').remove();
    CommentEvents.trigger('comment:target', {
      section: section,
      label: label,
      $parent: $parent
    });
    this.$read.hide();
    this.$write.show();
  },

  render: function() {
    ChildView.prototype.render.apply(this, arguments);

    this.$read = this.$el.find('#preamble-read');
    this.$write = this.$el.find('#preamble-write');

    this.section = this.$read.find('[data-permalink-section]').attr('id');
    this.docId = this.$read.closest('section').data('doc-id');

    this.preambleHeadView = new PreambleHeadView();

    this.commentView = new CommentView({
      el: this.$write.find('.comment-wrapper'),
      section: this.section,
      docId: this.docId
    });

    this.commentIndex = new CommentIndexView({
      el: this.$write.find('.comment-index'),
      docId: this.docId
    });

    if (this.options.mode === 'write') {
      var $parent = $('#' + this.options.section).find('[data-permalink-section]');
      this.write(this.options.section, this.options.label, $parent);
    } else {
      this.handleRead();
    }
  },

  remove: function() {
    this.commentView.remove();
    this.commentIndex.remove();
    Backbone.View.prototype.remove.call(this);
  }
});

module.exports = PreambleView;
<|endoftext|>


<commit_before>/**
 * @requires OpenLayers/Control.js
 */
OpenLayers.Control.FullScreen =
    OpenLayers.Class( OpenLayers.Control, {

    is_full_screen_on: false,

    // remember that suffixes are added to this class: ItemActive or ItemInactive
    btnClass: 'olControlButtonFullScreen',

    // css classess of control panels to be hidden/show on toggling fullscreen
    classElemToHide:  ['.searchDiv', '.logoDiv', '.olControlNoSelect', '.selZoom'],

    elemsToHideSelector: '',

    title: "FullScreen",

    initialize: function(options) {
        var that = this;
        OpenLayers.Control.prototype.initialize.apply(this,[options]);
        $(document).bind("keydown", function (e) {
            var code = e.keyCode || e.which;
            if (code === 122) { //F11
                that.is_full_screen_on = ! that.is_full_screen_on;
                that.toggleControls();
            } else if (code === 27) {// Escape
                // escape button can be used for leaving FS enabled by our button
                if (that.is_full_screen_on === true) {
                    that.is_full_screen_on = false;
                    that.toggleControls();
                } // endif
            } // endif
        }); // bind

        this.elemsToHideSelector = this.classElemToHide.join(',');
        this.type = OpenLayers.Control.TYPE_BUTTON;
    }, // initialize

    draw: function () {
        var position,
            size,
            imgLocation,
            btn,
            className = "fullscreen-button";

        imgLocation = OpenLayers.Util.getImageLocation("norges_fs.png");
        btn = OpenLayers.Util.createButton(
                'OpenLayers_Control_FullScreen' + this.map.id,
                null,
                null,
                imgLocation, "static");

        OpenLayers.Event.observe(btn, 'click',
            OpenLayers.Function.bind(this.toggleFullScreen, this)
        );

        btn.title = this.title;
        btn.className = btn.className === "" ? className : btn.className + " " + className;

        if (this.div == null) {
            this.div = btn;
        } else {
            this.div.appendChild(btn);
        }

        return this.div;
    }, // draw

    hideControls: function () {
        $(this.elemsToHideSelector).not("." + this.panelClass).hide();
    }, //hideControls

    showControls: function () {
        $(this.elemsToHideSelector).show();
    }, // showControls

    enable: function () {
        var el = document.documentElement,
            rfs = // for newer Webkit and Firefox
                   el.requestFullScreen
                || el.webkitRequestFullScreen
                || el.mozRequestFullScreen
                || el.msRequestFullScreen;
        if (rfs !== "undefined" && rfs) {
            rfs.call(el);
        } else if (window.ActiveXObject !== "undefined") {
            // for Internet Explorer
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        } // endif
    }, // enable

    disable: function () {
        // cancel method belongs to document directly
        var cfs = // for newer Webkit and Firefox
                   document.cancelFullScreen
                || document.webkitCancelFullScreen
                || document.mozCancelFullScreen
                || document.msCancelFullScreen;
        if (cfs !== "undefined" && cfs) {
            cfs.call(document);
        } else if (window.ActiveXObject !== "undefined") {
            // for Internet Explorer
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        } // endif
    }, // disable

    toggleFullScreen: function () {
        if (this.is_full_screen_on === true ) {
            this.disable();
            this.showControls();
            this.is_full_screen_on = false;
        } else {
            this.enable();
            this.hideControls();
            this.is_full_screen_on = true;
        } // endif
    }, // toggleFullScreen

    toggleControls: function () {
        if (this.is_full_screen_on === true ) {
            this.hideControls();
            //this.hideControls();
        } else {
            this.showControls();
            //this.showControls();
        } // endif
    },//togglecontrols

    CLASS_NAME: "OpenLayers.Control.FullScreen"
}); // OpenLayers.Control.FullScreen
<commit_msg>set class 'fullscreen' on body, fixed bug in testing for ActiveX presence in Opera<commit_after>/**
 * @requires OpenLayers/Control.js
 */
OpenLayers.Control.FullScreen =
    OpenLayers.Class( OpenLayers.Control, {

    is_full_screen_on: false,

    // remember that suffixes are added to this class: ItemActive or ItemInactive
    btnClass: 'olControlButtonFullScreen',

    // css classess of control panels to be hidden/show on toggling fullscreen
    classElemToHide:  ['.selZoom'],

    elemsToHideSelector: '',

    title: "FullScreen",

    initialize: function(options) {
        var that = this;
        OpenLayers.Control.prototype.initialize.apply(this,[options]);
        $(document).bind("keydown", function (e) {
            var code = e.keyCode || e.which;
            if (code === 122) { //F11
                that.is_full_screen_on = ! that.is_full_screen_on;
                that.toggleControls();
            } else if (code === 27) {// Escape
                // escape button can be used for leaving FS enabled by our button
                if (that.is_full_screen_on === true) {
                    that.is_full_screen_on = false;
                    that.toggleControls();
                } // endif
            } // endif
        }); // bind

        this.elemsToHideSelector = this.classElemToHide.join(',');
        this.type = OpenLayers.Control.TYPE_BUTTON;
    }, // initialize

    draw: function () {
        var position,
            size,
            imgLocation,
            btn,
            className = "fullscreen-button";

        imgLocation = OpenLayers.Util.getImageLocation("norges_fs.png");
        btn = OpenLayers.Util.createButton(
                'OpenLayers_Control_FullScreen' + this.map.id,
                null,
                null,
                imgLocation, "static");

        OpenLayers.Event.observe(btn, 'click',
            OpenLayers.Function.bind(this.toggleFullScreen, this)
        );

        btn.title = this.title;
        btn.className = btn.className === "" ? className : btn.className + " " + className;

        if (this.div == null) {
            this.div = btn;
        } else {
            this.div.appendChild(btn);
        }

        return this.div;
    }, // draw

    hideControls: function () {
        $(this.elemsToHideSelector).not("." + this.panelClass).hide();
        OpenLayers.Element.addClass(document.body, "fullscreen");
    }, //hideControls

    showControls: function () {
        $(this.elemsToHideSelector).show();
        OpenLayers.Element.removeClass(document.body, "fullscreen");
    }, // showControls

    enable: function () {
        var el = document.documentElement,
            rfs = // for newer Webkit and Firefox
                   el.requestFullScreen
                || el.webkitRequestFullScreen
                || el.mozRequestFullScreen
                || el.msRequestFullScreen;
        if (rfs !== "undefined" && rfs) {
            rfs.call(el);
        } else if (typeof window.ActiveXObject !== "undefined") {
            // for Internet Explorer
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        } // endif
    }, // enable

    disable: function () {
        // cancel method belongs to document directly
        var cfs = // for newer Webkit and Firefox
                   document.cancelFullScreen
                || document.webkitCancelFullScreen
                || document.mozCancelFullScreen
                || document.msCancelFullScreen;
        if (cfs !== "undefined" && cfs) {
            cfs.call(document);
        } else if (typeof window.ActiveXObject !== "undefined") {
            // for Internet Explorer
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        } // endif
    }, // disable

    toggleFullScreen: function () {
        if (this.is_full_screen_on === true ) {
            this.disable();
            this.showControls();
            this.is_full_screen_on = false;
        } else {
            this.enable();
            this.hideControls();
            this.is_full_screen_on = true;
        } // endif
    }, // toggleFullScreen

    toggleControls: function () {
        if (this.is_full_screen_on === true ) {
            this.hideControls();
            //this.hideControls();
        } else {
            this.showControls();
            //this.showControls();
        } // endif
    },//togglecontrols

    CLASS_NAME: "OpenLayers.Control.FullScreen"
}); // OpenLayers.Control.FullScreen
<|endoftext|>


<commit_before>//read config params from YAML file
const fs = require('fs');
const YAML = require('yamljs');
const appConfig = YAML.load('config.yml');

module.exports.port = function() {
  let port = appConfig.port;
  let re = /^\d{1,5}$/;
  if ( ( ! re.test(port) ) || (port < 1) || (port > 65535) ) {
    let message = 'ERROR in config.yml: port [' + port + '] should be in the range 1-65535.';
    console.log(message);
    throw message;
  }
  return port;
}

module.exports.docRoot = function() {
  let docRoot = appConfig.docRoot;
  fs.stat(docRoot, (err, stats) => {
    if (err) {
        console.log("ERROR in config.yml: docRoot [" + docRoot + "] not valid.");
        throw err;
    }
    if ( ! stats.isDirectory() ) {
      let message = "ERROR in config.yml: docRoot [" + docRoot + "] not a directory.";
      console.log(message);
      throw message;
    }
  });

  return docRoot;
}
<commit_msg>Add hostName<commit_after>//read config params from YAML file
const fs = require('fs');
const YAML = require('yamljs');
const appConfig = YAML.load('config.yml');

module.exports.port = function() {
  let port = appConfig.port;
  let re = /^\d{1,5}$/;
  if ( ( ! re.test(port) ) || (port < 1) || (port > 65535) ) {
    let message = 'ERROR in config.yml: port [' + port + '] should be in the range 1-65535.';
    console.log(message);
    throw message;
  }
  return port;
}

module.exports.docRoot = function() {
  let docRoot = appConfig.docRoot;
  fs.stat(docRoot, (err, stats) => {
    if (err) {
        console.log("ERROR in config.yml: docRoot [" + docRoot + "] not valid.");
        throw err;
    }
    if ( ! stats.isDirectory() ) {
      let message = "ERROR in config.yml: docRoot [" + docRoot + "] not a directory.";
      console.log(message);
      throw message;
    }
  });

  return docRoot;
}

module.exports.hostName = function() {
  let hostName = appConfig.hostName;
  let re = /\w/;
  if ( ! re.test(hostName) ) {
    let message = 'ERROR in config.yml: hostName [' + hostName + '] is not valid.';
    console.log(message);
    hostName = 'music.ownlifeful.com';
  }
  return hostName;
}
<|endoftext|>