<commit_before>
var jobStatusTimeout = null;
var requestPendingAllJobs = false;

function buildDownloadLink(jobId, state) {
  var extension = state === 'failed' ? '.json' : '';
  var msg = state === 'failed'
          ? 'Télécharger le rapport d\'erreur de l\'optimisation'
          : 'Télécharger le résultat de l\'optimisation';

  var url = "/0.1/vrp/jobs/" + jobId + extension + '?api_key=' + getParams()['api_key'];

  return ' ' + msg
    + '';
}

var jobsManager = {
  jobs: [],
  htmlElements: {
    builder: function (jobs) {
      $(jobs).each(function () {

        currentJob = this;
        var donwloadBtn = currentJob.status === 'completed' || currentJob.status === 'failed';

        var jobDOM =
          '
'
          + '' + (new Date(currentJob.time)).toLocaleString('fr-FR') + ' : '
          + '' + 'Job N° ' + currentJob.uuid + ' '
          + '<button value=' + currentJob.uuid + ' data-role="delete">'
          + ((currentJob.status === 'queued' || currentJob.status === 'working') ? i18n.killOptim : i18n.deleteOptim)
          + '</button>'
          + ' (Status: ' + currentJob.status + ')'
          + (donwloadBtn ? buildDownloadLink(currentJob.uuid, currentJob.status) : '')
          + '
';

        $('#jobs-list').append(jobDOM);

      });
      $('#jobs-list button').on('click', function () {
        jobsManager.roleDispatcher(this);
      });
    }
  },
  roleDispatcher: function (object) {
    switch ($(object).data('role')) {
      case 'focus':
        //actually in building, create to apply different behavior to the button object restartJob, actually not set. #TODO
        break;
      case 'delete':
        this.ajaxDeleteJob($(object).val());
        break;
    }
  },
  ajaxGetJobs: function (timeinterval) {
    var ajaxload = function () {
      if (!requestPendingAllJobs) {
        requestPendingAllJobs = true;
        $.ajax({
          url: '/0.1/vrp/jobs',
          type: 'get',
          dataType: 'json',
          data: { api_key: getParams()['api_key'] },
          complete: function () { requestPendingAllJobs = false; }
        }).done(function (data) {
          jobsManager.shouldUpdate(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
          if (jqXHR.status !== 500) {
            clearInterval(window.AjaxGetRequestInterval);
          }
          if (jqXHR.status == 401) {
            $('#optim-list-status').prepend('
' + i18n.unauthorizedError + '
');
            $('form input, form button').prop('disabled', true);
          }
        });
      }
    };
    if (timeinterval) {
      ajaxload();
      window.AjaxGetRequestInterval = setInterval(ajaxload, 5000);
    } else {
      ajaxload();
    }
  },
  ajaxDeleteJob: function (uuid) {
    $.ajax({
      url: '/0.1/vrp/jobs/' + uuid,
      type: 'delete',
      dataType: 'json',
      data: {
        api_key: getParams()['api_key']
      },
    }).done(function (data) {
      if (debug) { console.log("the uuid has been deleted from the jobs queue & the DB"); }
      $('button[data-role="delete"][value="' + uuid + '"]').fadeOut(500, function () { $(this).closest('.job').remove(); });
    });
  },
  shouldUpdate: function (data) {
    // erase list if no job running
    if (data.length === 0 && jobsManager.jobs.length !== 0) {
      $('#jobs-list').empty();
    }
    //check if chagements occurs in the data api. #TODO, update if more params are needed.
    $(data).each(function (index, object) {
      if (jobsManager.jobs.length > 0) {
        if (object.status != jobsManager.jobs[index].status || jobsManager.jobs.length != data.length) {
          jobsManager.jobs = data;
          $('#jobs-list').empty();
          jobsManager.htmlElements.builder(jobsManager.jobs);
        }
      }
      else {
        jobsManager.jobs = data;
        $('#jobs-list').empty();
        jobsManager.htmlElements.builder(jobsManager.jobs);
      }
    });
  },
  checkJobStatus: function (options, cb) {
    var nbError = 0;
    var requestPendingJobTimeout = false;

    if (options.interval) {
      jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
      return;
    }

    requestPendingJob();

    function requestPendingJob() {
      $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: '/0.1/vrp/jobs/'
          + (options.job.id || options.job.uuid)
          // + (options.format ? options.format : '')
          + '?api_key=' + getParams()["api_key"],
        success: function (job, _, xhr) {

          if (options.interval && (checkJSONJob(job) || checkCSVJob(xhr))) {
            if (debug) console.log("REQUEST PENDING JOB", checkCSVJob(xhr), checkJSONJob(job));
            requestPendingJobTimeout = true;
          }

          nbError = 0;
          cb(null, job, xhr);
      },
        error: function (xhr, status) {
          ++nbError
          if (nbError > 2) {
            cb({ xhr, status });
            return alert(i18n.failureOptim(nbError, status));
          }
          requestPendingJobTimeout = true;
        },
        complete: function () {
          if (requestPendingJobTimeout) {
            requestPendingJobTimeout = false;

            // interval max: 1mins
            options.interval *= 2;
            if (options.interval > 60000)  {
              options.interval = 60000
            }

            jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
          }
        }
      });
  }
},
  stopJobChecking: function () {
    requestPendingJobTimeout = false;
    clearTimeout(jobStatusTimeout);
  }
};

function checkCSVJob(xhr) {
  if (debug) console.log(xhr, xhr.status);
  return (xhr.status !== 200 && xhr.status !== 202);
}

function checkJSONJob(job) {
  if (debug) console.log("JOB: ", job, (job.job && job.job.status !== 'completed'));
  return ((job.job && job.job.status !== 'completed') && typeof job !== 'string')
}
<commit_msg>Fix missing parenthesis on ternary operation<commit_after>
var jobStatusTimeout = null;
var requestPendingAllJobs = false;

function buildDownloadLink(jobId, state) {
  var extension = state === 'failed' ? '.json' : '';
  var msg = state === 'failed'
          ? 'Télécharger le rapport d\'erreur de l\'optimisation'
          : 'Télécharger le résultat de l\'optimisation';

  var url = "/0.1/vrp/jobs/" + jobId + extension + '?api_key=' + getParams()['api_key'];

  return ' ' + msg
    + '';
}

var jobsManager = {
  jobs: [],
  htmlElements: {
    builder: function (jobs) {
      $(jobs).each(function () {

        currentJob = this;
        var donwloadBtn = currentJob.status === 'completed' || currentJob.status === 'failed';

        var jobDOM =
          '
'
          + '' + (new Date(currentJob.time)).toLocaleString('fr-FR') + ' : '
          + '' + 'Job N° ' + currentJob.uuid + ' '
          + '<button value=' + currentJob.uuid + ' data-role="delete">'
          + ((currentJob.status === 'queued' || currentJob.status === 'working') ? i18n.killOptim : i18n.deleteOptim)
          + '</button>'
          + ' (Status: ' + currentJob.status + ')'
          + (donwloadBtn ? buildDownloadLink(currentJob.uuid, currentJob.status) : '')
          + '
';

        $('#jobs-list').append(jobDOM);

      });
      $('#jobs-list button').on('click', function () {
        jobsManager.roleDispatcher(this);
      });
    }
  },
  roleDispatcher: function (object) {
    switch ($(object).data('role')) {
      case 'focus':
        //actually in building, create to apply different behavior to the button object restartJob, actually not set. #TODO
        break;
      case 'delete':
        this.ajaxDeleteJob($(object).val());
        break;
    }
  },
  ajaxGetJobs: function (timeinterval) {
    var ajaxload = function () {
      if (!requestPendingAllJobs) {
        requestPendingAllJobs = true;
        $.ajax({
          url: '/0.1/vrp/jobs',
          type: 'get',
          dataType: 'json',
          data: { api_key: getParams()['api_key'] },
          complete: function () { requestPendingAllJobs = false; }
        }).done(function (data) {
          jobsManager.shouldUpdate(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
          if (jqXHR.status !== 500) {
            clearInterval(window.AjaxGetRequestInterval);
          }
          if (jqXHR.status == 401) {
            $('#optim-list-status').prepend('
' + i18n.unauthorizedError + '
');
            $('form input, form button').prop('disabled', true);
          }
        });
      }
    };
    if (timeinterval) {
      ajaxload();
      window.AjaxGetRequestInterval = setInterval(ajaxload, 5000);
    } else {
      ajaxload();
    }
  },
  ajaxDeleteJob: function (uuid) {
    $.ajax({
      url: '/0.1/vrp/jobs/' + uuid,
      type: 'delete',
      dataType: 'json',
      data: {
        api_key: getParams()['api_key']
      },
    }).done(function (data) {
      if (debug) { console.log("the uuid has been deleted from the jobs queue & the DB"); }
      $('button[data-role="delete"][value="' + uuid + '"]').fadeOut(500, function () { $(this).closest('.job').remove(); });
    });
  },
  shouldUpdate: function (data) {
    // erase list if no job running
    if (data.length === 0 && jobsManager.jobs.length !== 0) {
      $('#jobs-list').empty();
    }
    //check if chagements occurs in the data api. #TODO, update if more params are needed.
    $(data).each(function (index, object) {
      if (jobsManager.jobs.length > 0) {
        if (object.status != jobsManager.jobs[index].status || jobsManager.jobs.length != data.length) {
          jobsManager.jobs = data;
          $('#jobs-list').empty();
          jobsManager.htmlElements.builder(jobsManager.jobs);
        }
      }
      else {
        jobsManager.jobs = data;
        $('#jobs-list').empty();
        jobsManager.htmlElements.builder(jobsManager.jobs);
      }
    });
  },
  checkJobStatus: function (options, cb) {
    var nbError = 0;
    var requestPendingJobTimeout = false;

    if (options.interval) {
      jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
      return;
    }

    requestPendingJob();

    function requestPendingJob() {
      $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: '/0.1/vrp/jobs/'
          + (options.job.id || options.job.uuid)
          // + (options.format ? options.format : '')
          + '?api_key=' + getParams()["api_key"],
        success: function (job, _, xhr) {

          if (options.interval && (checkJSONJob(job) || checkCSVJob(xhr))) {
            if (debug) console.log("REQUEST PENDING JOB", checkCSVJob(xhr), checkJSONJob(job));
            requestPendingJobTimeout = true;
          }

          nbError = 0;
          cb(null, job, xhr);
      },
        error: function (xhr, status) {
          ++nbError
          if (nbError > 2) {
            cb({ xhr, status });
            return alert(i18n.failureOptim(nbError, status));
          }
          requestPendingJobTimeout = true;
        },
        complete: function () {
          if (requestPendingJobTimeout) {
            requestPendingJobTimeout = false;

            // interval max: 1mins
            options.interval *= 2;
            if (options.interval > 60000)  {
              options.interval = 60000
            }

            jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
          }
        }
      });
  }
},
  stopJobChecking: function () {
    requestPendingJobTimeout = false;
    clearTimeout(jobStatusTimeout);
  }
};

function checkCSVJob(xhr) {
  if (debug) console.log(xhr, xhr.status);
  return (xhr.status !== 200 && xhr.status !== 202);
}

function checkJSONJob(job) {
  if (debug) console.log("JOB: ", job, (job.job && job.job.status !== 'completed'));
  return ((job.job && job.job.status !== 'completed') && typeof job !== 'string')
}
<|endoftext|>


<commit_before>(function () {
    var statusData = function () {
        var data = [],
            statusData = $.parseJSON($('#status-data').text());

        for (var status in statusData) {
            data.push({ status: status, points: statusData[status].points });
        }

        return data;
    };

    var statusPieChart = (function () {
        var width, height, radius,

            svg,
            arc,

            pieData;

        var setSVG = function (id) {
            svg = d3.select(id).append('svg')
                .attr('width', width)
                .attr('height', height)
                .append('g')
                .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
        };

        var addPie = function () {
            var pie = d3.layout.pie()
                .value(function (d) { return d.points; });

            svg.selectAll('.arc')
                .data(pie(pieData))
                .enter().append('g')
                .attr('class', 'arc')
                .append('path')
                    .attr('d', arc)
                    .attr('class', function (d) { return 'status filter-backlog ' + d.data.status; })
                    .attr('data-column', 'status')
                    .attr('data-value', function (d) { return d.data.status; });
        };

        var setArc = function () {
            arc = d3.svg.arc()
                .outerRadius(radius - 10)
                .innerRadius(0);
        };

        var showTooltipOnMouseOver = function () {
            svg.selectAll('.status')
                .on('mousemove', function (d) {
                    svg.select('#label-tooltip')
                        .text(d.data.status)
                        .style('display', 'block')
                        .attr('x', d3.mouse(this)[0] + 10)
                        .attr('y', d3.mouse(this)[1] + 10)
                })
                .on('mouseout', function () {
                    svg.select('#label-tooltip').style('display', 'none');
                });
        };

        var addLabelToolTip = function () {
            svg.append('text')
                .attr('id', 'label-tooltip')
                .style('display', 'none');

            showTooltipOnMouseOver();
        };

        return {
            /**
             * @param {Object[]} data - List of objects containing status name and number of points for the respective status.
             */
            init: function (data) {
                pieData = data;
            },

            /**
             * @param id - ID of the element containing the pie chart
             * @param width - width of the pie chart area
             * @param height - height of the pie chart area
             */
            render: function (id, pieWidth, pieHeight) {
                width = pieWidth;
                height = pieHeight;
                radius = width / 2;

                setSVG(id);
                setArc();

                addPie();
                addLabelToolTip();
            }
        };
    })();

    statusPieChart.init(statusData());
    statusPieChart.render('#pie', 250, 250);
})();
<commit_msg>Add missing semicolon.<commit_after>(function () {
    var statusData = function () {
        var data = [],
            statusData = $.parseJSON($('#status-data').text());

        for (var status in statusData) {
            data.push({ status: status, points: statusData[status].points });
        }

        return data;
    };

    var statusPieChart = (function () {
        var width, height, radius,

            svg,
            arc,

            pieData;

        var setSVG = function (id) {
            svg = d3.select(id).append('svg')
                .attr('width', width)
                .attr('height', height)
                .append('g')
                .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
        };

        var addPie = function () {
            var pie = d3.layout.pie()
                .value(function (d) { return d.points; });

            svg.selectAll('.arc')
                .data(pie(pieData))
                .enter().append('g')
                .attr('class', 'arc')
                .append('path')
                    .attr('d', arc)
                    .attr('class', function (d) { return 'status filter-backlog ' + d.data.status; })
                    .attr('data-column', 'status')
                    .attr('data-value', function (d) { return d.data.status; });
        };

        var setArc = function () {
            arc = d3.svg.arc()
                .outerRadius(radius - 10)
                .innerRadius(0);
        };

        var showTooltipOnMouseOver = function () {
            svg.selectAll('.status')
                .on('mousemove', function (d) {
                    svg.select('#label-tooltip')
                        .text(d.data.status)
                        .style('display', 'block')
                        .attr('x', d3.mouse(this)[0] + 10)
                        .attr('y', d3.mouse(this)[1] + 10);
                })
                .on('mouseout', function () {
                    svg.select('#label-tooltip').style('display', 'none');
                });
        };

        var addLabelToolTip = function () {
            svg.append('text')
                .attr('id', 'label-tooltip')
                .style('display', 'none');

            showTooltipOnMouseOver();
        };

        return {
            /**
             * @param {Object[]} data - List of objects containing status name and number of points for the respective status.
             */
            init: function (data) {
                pieData = data;
            },

            /**
             * @param id - ID of the element containing the pie chart
             * @param width - width of the pie chart area
             * @param height - height of the pie chart area
             */
            render: function (id, pieWidth, pieHeight) {
                width = pieWidth;
                height = pieHeight;
                radius = width / 2;

                setSVG(id);
                setArc();

                addPie();
                addLabelToolTip();
            }
        };
    })();

    statusPieChart.init(statusData());
    statusPieChart.render('#pie', 250, 250);
})();
<|endoftext|>


<commit_before>/* global bundle, $ */

var d3 = require("d3");

var COLOR_TABLE = [
  "#C8D2D9", "#97ABB8", "#FFBEB9", "#FFD1CE"
];

/**
 * updateGraph
 *
 * Update the graph with some new data and remove the old one.
 *
 * @newData: New tuples of data to update the graph with
 */
function updateGraph(newData) {
  var svg;

  /* The individual points of data, not including labels */
  var dataPoints = newData.map(function onEachDataPoint(w) {
    return w.value;
  });

  /* Drop any existing SVG elements */
  Array.prototype.forEach.call(document.getElementsByClassName("chart"),
                               function dropInnerHTMLOf(element) {
                                 /* Drop everything inside this chart */
                                 element.innerHTML = "";  // eslint-disable-line no-param-reassign
                               });

  svg = d3.select("div.chart")
          .append("svg")
          .attr("class", "svgchart")
          .attr("width", function computeWidth() {
            return this.parentNode.clientWidth * 0.80;
          })
          .attr("height", function computeHeight() {
            return this.parentNode.clientHeight * 0.80;
          })
          .attr("style", function computeTransform() {
            var x = this.parentNode.clientWidth * 0.10;
            var y = this.parentNode.clientHeight * 0.10;
            return ["transform: translate(", x, "px,", y, "px", ")"].join("");
          });

  newData.forEach(function forEachDataPoint(dataPoint, index) {
    var g = svg.append("g")
               .attr("transform", function computeBarY() {
                 var chartHeight = this.parentNode.clientHeight;
                 var barSpacing = 10;
                 var barHeight = ((chartHeight - (barSpacing *
                                                  newData.length)) /
                                  newData.length);

                 var y = (index * barSpacing) + (index * barHeight);
                 return "translate(0.0, " + y + ")";
               });
    g.append("rect")
     .attr("height", function computeBarHeight() {
       var chartHeight = this.parentNode.parentNode.clientHeight;
       var barSpacing = 10;
       return ((chartHeight - (barSpacing * newData.length)) /
               newData.length);
     })
     .transition()
     .delay(index * 50)
     .duration(750)
     .ease(d3.easeElastic.period(0.4))
     .attr("width", function computeBarWidth() {
       var parentWidth = this.parentNode.parentNode.clientWidth;
       var x = d3.scaleLinear().domain([0, d3.max(dataPoints)])
                               .range([0, parentWidth]);
       return x(dataPoint.value);
     })
     .attr("rx", "15")
     .attr("ry", "15")
     .attr("fill", COLOR_TABLE[index % COLOR_TABLE.length]);
    g.append("text")
     .attr("fill", "#ffffff")
     .text(dataPoint.name)
     .attr("y", function computeY() {
       var chartHeight = this.parentNode.parentNode.clientHeight;
       var barSpacing = 10;
       var textHeight = 15;
       return (((chartHeight - (barSpacing * newData.length)) /
               newData.length) / 2) + (textHeight / 2);
     })
     .attr("x", 10);
  });
}

/**
 * postGraphUpdateRequest
 *
 * Post a request to the server to get a new graph.
 *
 * @name The chart name to fetch.
 */
function postGraphUpdateRequest(name) {
  $.ajax({
    url: "/get_bar_chart",
    data: {
      name: name
    },
    success: function onXHRSuccess(data) {
      updateGraph(data.data);
    }
  });
}

document.addEventListener("DOMContentLoaded", function onDOMLoaded() {
  $("#chartSelectionDropdown ul li a").click(function onDropdownClick(event) {
    var div = $(this).parent().parent().parent();
    var button = div.find("button");

    button.html(this.text + " ");
    div.removeClass("open");
    event.preventDefault();

    postGraphUpdateRequest($(this).attr("data-selection-id"));
    return false;
  });
});
<commit_msg>retraction: Deal with labels being too short to fit into the bars<commit_after>/* global bundle, $ */

var d3 = require("d3");

var COLOR_TABLE = [
  "#C8D2D9", "#97ABB8", "#FFBEB9", "#FFD1CE"
];

/* This is a poor-man's estimate, given the fact that measuring the
 * actual size of the characters (accounting for kerning) will involve
 * significant DOM mutation. */
var INDIVIDUAL_CHARACTER_SIZE = 7;

/**
 * calculateChartOffset

/**
 * updateGraph
 *
 * Update the graph with some new data and remove the old one.
 *
 * @newData: New tuples of data to update the graph with
 */
function updateGraph(newData) {
  var svg;
  var chartContainer = document.getElementsByClassName("chart")[0];

  /* The individual points of data, not including labels */
  var dataPoints = newData.map(function onEachDataPoint(w) {
    return w.value;
  });

  /* Estimated sizes of the labels and the bars if no scaling was appleid -
   * use this to determine whether an offset should be applied to the chart
   * based on the width of the smallest bar and its corresponding label. If
   * a bar's label size exceeds the size of the bar, we need to make
   * at least enough room on the left hand side for the bar label */
  var offsetAmount = 0;
  var postprocessedData = newData.map(function onEachDataPoint(d) {
    var availableParentWidth = chartContainer.clientWidth * 0.80;
    var x = d3.scaleLinear().domain([0, d3.max(dataPoints)])
                            .range([0, availableParentWidth]);
    var bar = x(d.value);
    var label = 10 + (INDIVIDUAL_CHARACTER_SIZE * d.name.length);
    var isOffset = false;

    if (label > bar) {
      isOffset = true;
      if (offsetAmount < label) {
        offsetAmount = label;
      }
    }

    return {
      name: d.name,
      value: d.value,
      isOffset: isOffset
    };
  });

  /* Drop any existing SVG elements */
  Array.prototype.forEach.call(document.getElementsByClassName("chart"),
                               function dropInnerHTMLOf(element) {
                                 /* Drop everything inside this chart */
                                 element.innerHTML = "";  // eslint-disable-line no-param-reassign
                               });

  svg = d3.select("div.chart")
          .append("svg")
          .attr("class", "svgchart")
          .attr("width", function computeWidth() {
            return this.parentNode.clientWidth * 0.80;
          })
          .attr("height", function computeHeight() {
            return this.parentNode.clientHeight * 0.80;
          })
          .attr("style", function computeTransform() {
            var x = this.parentNode.clientWidth * 0.10;
            var y = this.parentNode.clientHeight * 0.10;
            return ["transform: translate(", x, "px,", y, "px", ")"].join("");
          });

  postprocessedData.forEach(function forEachDataPoint(dataPoint, index) {
    var g = svg.append("g")
               .attr("transform", function computeBarY() {
                 var chartHeight = this.parentNode.clientHeight;
                 var barSpacing = 10;
                 var barHeight = ((chartHeight - (barSpacing *
                                                  postprocessedData.length)) /
                                  postprocessedData.length);

                 var y = (index * barSpacing) + (index * barHeight);
                 return "translate(0.0, " + y + ")";
               });
    g.append("rect")
     .attr("height", function computeBarHeight() {
       var chartHeight = this.parentNode.parentNode.clientHeight;
       var barSpacing = 10;
       return ((chartHeight - (barSpacing * postprocessedData.length)) /
               postprocessedData.length);
     })
     .transition()
     .delay(index * 50)
     .duration(750)
     .ease(d3.easeElastic.period(0.4))
     .attr("width", function computeBarWidth() {
       var parentWidth = (this.parentNode.parentNode.clientWidth -
                          offsetAmount);
       var x = d3.scaleLinear().domain([0, d3.max(dataPoints)])
                               .range([0, parentWidth]);
       return x(dataPoint.value);
     })
     .attr("rx", "15")
     .attr("ry", "15")
     .attr("x", String(offsetAmount))
     .attr("fill", COLOR_TABLE[index % COLOR_TABLE.length]);
    g.append("text")
     .attr("fill", dataPoint.isOffset ? "#000000" : "#ffffff")
     .text(dataPoint.name)
     .attr("y", function computeY() {
       var chartHeight = this.parentNode.parentNode.clientHeight;
       var barSpacing = 10;
       var textHeight = 15;
       return (((chartHeight - (barSpacing * postprocessedData.length)) /
               postprocessedData.length) / 2) + (textHeight / 2);
     })
     .attr("x", dataPoint.isOffset ? 10 : 10 + offsetAmount);
  });
}

/**
 * postGraphUpdateRequest
 *
 * Post a request to the server to get a new graph.
 *
 * @name The chart name to fetch.
 */
function postGraphUpdateRequest(name) {
  $.ajax({
    url: "/get_bar_chart",
    data: {
      name: name
    },
    success: function onXHRSuccess(data) {
      updateGraph(data.data);
    }
  });
}

document.addEventListener("DOMContentLoaded", function onDOMLoaded() {
  $("#chartSelectionDropdown ul li a").click(function onDropdownClick(event) {
    var div = $(this).parent().parent().parent();
    var button = div.find("button");

    button.html(this.text + " ");
    div.removeClass("open");
    event.preventDefault();

    postGraphUpdateRequest($(this).attr("data-selection-id"));
    return false;
  });
});
<|endoftext|>


<commit_before>function handle_followers(data) {
    for (var i in data) add_player(data[i]);
}

function add_player(data) {
    ('stats' in data) ? create_row(data) : $.ajax({url:'/' + data.user + '/stats', success:create_row});
}

function new_element(target, type, new_class, contents) {
    var element = document.createElement(type);
    element.className = new_class;
    element.innerHTML = contents;
    target.appendChild(element);
}

function create_row(data) {
    var user = data.user;
    var score = data.stats.score;
    var today = data.stats.today;
    var board = document.getElementById('scoreboard');

    var row = document.createElement('div');
    row.className = 'player';
    row.setAttribute('data-name', user);
    row.setAttribute('data-score', score);

    new_element(row, 'span', 'name', user);
    new_element(row, 'span', 'score', score);

    if (today == 1) new_element(row, 'i', 'fa fa-check-square', '');

    var rows = board.getElementsByClassName('player');
    for ( var i = 0 ; i < rows.length ; i++ ) {
        if (parseInt(rows[i].getAttribute('data-score')) > score) continue;
        board.insertBefore(row, rows[i]);
        return;
    }
    board.appendChild(row);
}

$(document).ready(function(){
    if (typeof preload === 'undefined') {
        $.ajax({url:'/' + player_one + '/following', success:handle_followers});
    } else {
        handle_followers(preload);
    }
});

<commit_msg>add github icon<commit_after>function handle_followers(data) {
    for (var i in data) add_player(data[i]);
}

function add_player(data) {
    ('stats' in data) ? create_row(data) : $.ajax({url:'/' + data.user + '/stats', success:create_row});
}

function new_element(target, type, new_class, contents) {
    var element = document.createElement(type);
    element.className = new_class;
    element.innerHTML = contents;
    target.appendChild(element);
}

function create_row(data) {
    var user = data.user;
    var score = data.stats.score;
    var today = data.stats.today;
    var board = document.getElementById('scoreboard');

    var row = document.createElement('div');
    row.className = 'player';
    row.setAttribute('data-name', user);
    row.setAttribute('data-score', score);

    new_element(row, 'span', 'name', user + '<i class="fa fa-github-square"></i>');
    new_element(row, 'span', 'score', score);

    if (today == 1) new_element(row, 'i', 'fa fa-check-square', '');

    var rows = board.getElementsByClassName('player');
    for ( var i = 0 ; i < rows.length ; i++ ) {
        if (parseInt(rows[i].getAttribute('data-score')) > score) continue;
        board.insertBefore(row, rows[i]);
        return;
    }
    board.appendChild(row);
}

$(document).ready(function(){
    if (typeof preload === 'undefined') {
        $.ajax({url:'/' + player_one + '/following', success:handle_followers});
    } else {
        handle_followers(preload);
    }
});

<|endoftext|>


<commit_before>function getFile(a,d){var c=a;var b;if(window.XMLHttpRequest){b=new XMLHttpRequest()}else{b=new ActiveXObject("Microsoft.XMLHTTP")}b.onreadystatechange=function(){if(b.readyState==1){if(b.overrideMimeType){b.overrideMimeType("application/json");b.setRequestHeader("Accept","application/vnd.github.v3.text-match+json")}b.send()}if(b.readyState==4){if(b.status===200||b.status===0){d(b.responseText)}}};b.open("GET",c,true)}function mapURL(a){var b="http://talmeida.github.io/";var j="_posts/";if(a.lastIndexOf(j,0)===0){var i=a.split("-");i.splice(0,3);return b+i.join("-").replace(".md","")}var f="/about";var h="/contact";if(a.lastIndexOf(f,0)===0||a.lastIndexOf(h,0)===0){return b+a.replace(".md","")}var e="strategy/";var c="/strategy";var g="tools/";var d="/tools";if(a.lastIndexOf(e,0)===0||a.lastIndexOf(g,0)===0||a.lastIndexOf(c,0)===0||a.lastIndexOf(d,0)===0){return b+a.replace(".md",".html")}return b+a}function doSearch(){var b=document.getElementById("search").value;var a="https://api.github.com/search/code?q='"+b+"' in:file language:markdown repo:talmeida/talmeida.github.io&sort=indexed&order=desc";getFile(a,function(d){var i=JSON.parse(d);var g=["

Found "+i.total_count.toString()+" match(es).
"];if(i.items&&i.items.length>0){g.push("
Results:
");var f,c;for(f=0;f<i.items.length;++f){var h=i.items[f];g.push("

"+h.name.replace(".md","")+"");if(h.text_matches&&h.text_matches.length>0){g.push("
");for(c=0;c<h.text_matches.length;++c){var e=h.text_matches[c].fragment;e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");g.push("
"+e.replace(new RegExp(b,"gi"),""+b+"")+"
")}g.push("
")}g.push("
")}}document.getElementById("output").innerHTML=g.join("")});return};<commit_msg>Search<commit_after>function getFile(a,d){var c=a;var b;if(window.XMLHttpRequest){b=new XMLHttpRequest()}else{b=new ActiveXObject("Microsoft.XMLHTTP")}b.onreadystatechange=function(){if(b.readyState==1){if(b.overrideMimeType){b.overrideMimeType("application/json");b.setRequestHeader("Accept","application/vnd.github.v3.text-match+json")}b.send()}if(b.readyState==4){if(b.status===200||b.status===0){d(b.responseText)}}};b.open("GET",c,true)}function mapURL(a){var b="http://nzthiago.github.io/";var j="_posts/";if(a.lastIndexOf(j,0)===0){var i=a.split("-");i.splice(0,3);return b+i.join("-").replace(".md","")}var f="/about";var h="/contact";if(a.lastIndexOf(f,0)===0||a.lastIndexOf(h,0)===0){return b+a.replace(".md","")}var e="strategy/";var c="/strategy";var g="tools/";var d="/tools";if(a.lastIndexOf(e,0)===0||a.lastIndexOf(g,0)===0||a.lastIndexOf(c,0)===0||a.lastIndexOf(d,0)===0){return b+a.replace(".md",".html")}return b+a}function doSearch(){var b=document.getElementById("search").value;var a="https://api.github.com/search/code?q='"+b+"' in:file language:markdown repo:nzthiago/nzthiago.github.io&sort=indexed&order=desc";getFile(a,function(d){var i=JSON.parse(d);var g=["

Found "+i.total_count.toString()+" match(es).
"];if(i.items&&i.items.length>0){g.push("
Results:
");var f,c;for(f=0;f<i.items.length;++f){var h=i.items[f];g.push("

"+h.name.replace(".md","")+"");if(h.text_matches&&h.text_matches.length>0){g.push("
");for(c=0;c<h.text_matches.length;++c){var e=h.text_matches[c].fragment;e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");g.push("
"+e.replace(new RegExp(b,"gi"),""+b+"")+"
")}g.push("
")}g.push("
")}}document.getElementById("output").innerHTML=g.join("")});return};<|endoftext|>


<commit_before>

self.addEventListener('message', function(e) {
  var data = e.data;
  switch (data.cmd) {

    case 'start':
        init_worker(data.config);
        console.log( 'start' );
        break;
    case 'evolve':
        console.log( 'evolve' );
        do_ea();
        break;
        }

    }, false
);

function init_worker(config) {
    self.population_size = config.population_size;
    self.period = config.period;
    self.traps = config.traps;
    self.trap_len = config.trap_len;
    self.trap_b = config.trap_b;
    self.chromosome_size = traps * trap_len;
    self.experiment_id = null;

    self.trap_fitness = new trap.Trap({
        "l": trap_len,
        "a": 1,
        "b": trap_b,
        "z": trap_len - 1
    });

    self.eo = new Nodeo({
        population_size: self.population_size,
        chromosome_size: self.chromosome_size,
        fitness_func: self.trap_fitness
    });
    //Worker uuid
    self.uuid = config.worker_uuid;
    var xmlhttp = new XMLHttpRequest();
    // PUTs worker info
    xmlhttp.open("PUT", "/start/"+uuid+"/with/"+population_size, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {

            if (xmlhttp.status == 200 /*|| xmlhttp.status == 304*/)
            {
                var data = JSON.parse(xmlhttp.responseText);
                console.log( data.experiment_id  );
                if ( data.experiment_id !== "undefined"  ) {

                    self.experiment_id= data.experiment_id;
                    console.log(self.experiment_id);
                }

                postMessage(
                    {
                        status:'created'
                    });

            }
            else if (xmlhttp2.readyState == 4 &&  xmlhttp.status == 404)
            {
                /// UNABLE TO INITIALIZE
                console.log("Error 404: not_created");
                // TO DO: HANDLE
                postMessage(
                    {
                        status:'not_created'
                    });

            }

        }
    };
    xmlhttp.send();
}

function restart() {

    console.log("restarting");

    self.eo = new Nodeo({
        population_size: self.population_size,
        chromosome_size: self.chromosome_size,
        fitness_func: self.trap_fitness
    });

    postMessage(
        {
            status:'starting'

        });

    do_ea();
}

function do_ea() {
    eo.generation();
    //if ( eo.population[0].fitness == traps*trap_b ) {
    //    console.log('finished before');
    //}

    if ( (eo.generation_count % period === 0) ) {

        // gets a random chromosome from the pool
        var xmlhttp = new XMLHttpRequest();
        var url = "/random";
        xmlhttp.open("GET", url, true);
        xmlhttp.onreadystatechange = function() {

           if (xmlhttp.readyState == 4 ) {

                if (xmlhttp.status == 200 /*|| xmlhttp.status == 304*/)
                {
                    var data = JSON.parse(xmlhttp.responseText);
                    if ( data.chromosome ) {
                        eo.incorporate( data.chromosome );
                       }

                }
                else if ( xmlhttp.status == 404)
                    {   console.log("404");
                        //There is no population
                        postMessage(
                        {
                        status:'no_work',
                        generation_count:eo.generation_count,
                        best:eo.population[0].string,
                        fitness:eo.population[0].fitness,'period':period,
                        pop_size: eo.population.length
                        });
                        console.log("AFTER 404");
                        //No more work
                        //return;

                    }

            }
        };
        xmlhttp.send();

        if (self.experiment_id  !== "undefined" ) {
            var xmlhttp2 = new XMLHttpRequest();
            // And puts another one in the pool
            xmlhttp2.open("PUT", "/experiment/" + self.experiment_id + "/one/" + eo.population[0].string + "/" + eo.population[0].fitness + "/" + uuid, true);
            xmlhttp2.onreadystatechange = function () {
                if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {

                    postMessage(
                        {
                            status: 'working',
                            generation_count: eo.generation_count,
                            best: eo.population[0].string,
                            fitness: eo.population[0].fitness, 'period': period, 'ips': ips,
                            pop_size: eo.population.length,
                            current_expid: self.experiment_id
                        });
                }
                else if (xmlhttp2.readyState == 4 && xmlhttp2.status == 410) {
                    var data = JSON.parse(xmlhttp2.responseText);
                    self.experiment_id = data.current_expid;

                    postMessage({
                            status: 'experiment_not_found',
                            current_experiment_id:self.experiment_id
                        });
                    restart();

                }

            };
            xmlhttp2.send();
        }
        //IPs
        var xmlhttp3 = new XMLHttpRequest();
        var url = "/IPs";
        var ips = "";
        xmlhttp3.onreadystatechange = function() {
            if (xmlhttp3.readyState == 4 && xmlhttp3.status == 200) {
                var data = JSON.parse(xmlhttp3.responseText);
                ips = Object.keys( data ).length;

                postMessage({
                    status:'working',
                    generation_count:eo.generation_count,
                    best:eo.population[0].string,
                    fitness:eo.population[0].fitness,'period':period,'ips':ips,
                    pop_size: eo.population.length
                    });

                }

            };
        xmlhttp3.open("GET", url, true);
        xmlhttp3.send();

    }

    if ( eo.population[0].fitness < traps*trap_b ) {

        setTimeout(do_ea, 5);

    }

    else{

        /// FOUND IT

        if (self.experiment_id  !== "undefined" ) {

            var xmlhttp2 = new XMLHttpRequest();
            ///experiment/:expid/one/:chromosome/:fitness/:uuid
            xmlhttp2.open("PUT", "/experiment/" + self.experiment_id + "/one/" + eo.population[0].string + "/" + eo.population[0].fitness + "/" + uuid, true);
            xmlhttp2.onreadystatechange = function () {
                if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
                    postMessage(
                        {
                            status:'finished',
                            generation_count: eo.generation_count,
                            best: eo.population[0].string,
                            fitness: eo.population[0].fitness, 'period': period, 'ips': ips,
                            pop_size: eo.population.length,
                            current_expid: self.experiment_id
                        });

                }
                else if (xmlhttp2.readyState == 4 && xmlhttp2.status == 410) {
                    var data = JSON.parse(xmlhttp2.responseText);
                    self.experiment_id = data.current_expid;

                    postMessage(
                        {
                           status: 'experiment_not_found',
                           current_experiment_id:self.experiment_id

                        });

                }
                // Restart either way
                restart();
                console.log('finished after');
            };

            xmlhttp2.send();
        }

        //close();
    }
}

function Nodeo( options ) {
/*jshint validthis: true */
    for ( var i in options ) {
	this[i] = options[i];
    }
    if ( ! this.population_size ) {
	return new Error ("0 population size");
    }
    if ( ! this.fitness_func ) {
	return new Error ("No fitness func");
    } else if ( typeof( this.fitness_func) === 'function' ) {
	this.fitness_obj = new Fitness( options.fitness_func );
    } else {
	this.fitness_obj = this.fitness_func;
    }
    if ( !this.tournament_size ) {
	this.tournament_size = 2;
    }
    if ( !this.pool_size ) {
	this.pool_size = this.population_size - 2;
    }

    if ( !this.chromosome_size || isNaN(this.chromosome_size) ) {
	throw "Chromosome size error";
    }
    this.population = [];
//    console.log( this.fitness_obj.apply );
    do {
	var this_string = utils.random( this.chromosome_size );
	var chromosome = new Chromosome( this_string,
					 this.fitness_obj.apply( this_string ) );
	this.population.push( chromosome );
    } while( this.population.length < this.population_size );

    // Methods
    this.tournament_selection = tournament_selection;
    this.evaluation = evaluation;
    this.generation= generation;
    this.rank=rank;
    this.incorporate=incorporate;
    this.generation_count=0;
};

// create fitness function object if it does not exist
function Fitness ( f ) {
 /*jshint validthis: true */
    this.apply = f;
}

// Selects a new population of size pool_size via comparing tournament_size chromosomes and taking the best
function tournament_selection( tournament_size, pool_size ) {
/*jshint validthis: true */
    var pool = [];
    if ( tournament_size <= 1 ) {
	return new Error ("Tournament size too small");
    }
    do {
//	var joust = [];
	var best =  this.population[ Math.floor(Math.random()*this.population.length) ] ;
	for ( var i = 1; i < tournament_size; i ++) {
	    var another= this.population[ Math.floor(Math.random()*this.population.length) ];
	    if ( another.fitness > best.fitness) {
		best = another;
	    }
	}
	pool.push( best );
    } while (pool.length < pool_size );
    return pool;
}

// Evaluates all the population not in cache
function evaluation( new_guys ) {
/*jshint validthis: true */
    for (var i in new_guys) {
	new_guys[i].fitness = this.fitness_obj.apply( new_guys[i].string );
    }
}

// sort population
function rank () {
    /*jshint validthis: true */
    var sorted_population = this.population.sort( function(a,b){ return b.fitness - a.fitness; } );
    this.population = sorted_population;
}

// Single generation
function generation() {
    /*jshint validthis: true */
    var chosen = this.tournament_selection( this.tournament_size, this.pool_size);
    this.rank(); // to get the best
    var the_best = [this.population[0],this.population[1]];
    var new_population = this.population[0].reproduction(chosen);
    this.evaluation(new_population);
    this.population = the_best.concat( new_population );
    this.rank(); // ranking twice????
    this.generation_count++;
}

function Trap( options ) {
    for ( var i in options ) {
	this[i] = options[i];
    }
    if ( !this.l ) {
	this.l = 3;
    }
    if ( !this.a ) {
	this.a = 1;
    }
    if ( !this.b ) {
	this.l = 2;
    }
    if ( !this.z ) {
	this.a = this.l-1;
    }

    // Methods
    this.apply = apply;
}

trap = {}
trap.Trap = Trap;

// Applies trap function to chromosome using instance values
function apply( chromosome ){
    return functions.ltrap(chromosome, this.l, this.a, this.b, this.z);
}

// L-trap function
ltrap = function(x,l,a,b,z) {
    var total = 0;
    for ( var i = 0;  i < x.length; i+= l ) {
	var this_substr = x.substr(  i, l );
	var num_ones = 0;
	for ( var j = 0;  j < this_substr.length; j++ ) {
	  num_ones += (this_substr.substring(j,j+1) === "1");
	}
	var this_result;
	if ( num_ones <= z ) {
	  this_result = a*(z-num_ones)/z;
	} else {
	  this_result = b*(num_ones -z)/(l-z);
	}
	total += this_result;
//	console.log("Total " + i + " :"+total + " num_ones " + num_ones );
    }

    return total;
};

functions = {}
functions.ltrap = ltrap;

var utils = {};

// Create a random chromosome
utils.random= function (length){
    var chromosome = '';
    for ( var i = 0; i < length; i++ ){
    chromosome = chromosome + ((Math.random() >= 0.5)? "1": "0") ;
    }

    return chromosome;
};

// Computes maxOnes fitness
utils.max_ones = function (chromosome){
    var ones = 0;
    console.log( "MO " + chromosome);
    for ( var i=0; i < chromosome.length; i++ ){
    ones += parseInt(chromosome.charAt(i));
    }
    return ones;
};

// Creates a single chromosome. Includes all utility functions
function Chromosome(string,fitness){
    this.string = string;
    this.fitness = fitness;

    // functions
    this.invert = invert;
    this.mutate = mutate;
    this.crossover=crossover;
    this.reproduction=reproduction;
}

// Bit-flips the whole chromosome
function invert (chromosome) {
    var inverted='';
    for (var i = 0; i < chromosome.string.length; i ++ ) {
    inverted += chromosome.string.charAt(i).match(/1/)?"0":"1";
    }
    return new Chromosome (inverted);
}

// Bit-flips a single bit
function mutate (chromosome ) {

    var mutation_point = Math.floor( Math.random() * chromosome.string.length);
    var temp = chromosome.string;
    var flip_bit = temp.charAt(mutation_point).match(/1/)?"0":"1";
    var clone = temp.substring(0,mutation_point) +
    flip_bit +
    temp.substring(mutation_point+1,temp.length) ;
    return new Chromosome( clone );
}

// Interchanges a substring between the two parents
function crossover ( chrom1, chrom2 ) {
    var length = chrom1.string.length;
    var xover_point = Math.floor( Math.random() * length);
    var range = 1 + Math.floor(Math.random() * (length - xover_point) );
    var new_chrom1 = chrom1.string.substr(0,xover_point);
    var new_chrom2 = chrom2.string.substr(0,xover_point);
    new_chrom1+= chrom2.string.substring(xover_point,xover_point+range) +
    chrom1.string.substring(xover_point+range,length);
    new_chrom2+= chrom1.string.substring(xover_point,xover_point+range) +
    chrom2.string.substring(xover_point+range,length);
    return [new Chromosome(new_chrom1), new Chromosome(new_chrom2)];
}

// Applies operators to the pool
function reproduction(  pool ) {
/*jshint validthis: true */
    var offspring = [];
    while (pool.length ) {
    var first = pool.splice( Math.floor(Math.random()*pool.length), 1 );
    var second = pool.splice( Math.floor(Math.random()*pool.length), 1 );
    var crossovers = this.crossover( first[0], second[0] );
    for ( var i in crossovers ) {
        offspring.push( this.mutate(crossovers[i]));
    }
    }
    return offspring;
}

function incorporate( chromosome ) {
//    console.log(chromosome);
    if ( chromosome.length != this.chromosome_size )
    throw "Bad chromosome length" + chromosome.length + "!=" + this.chromosome_size ;
    var new_guy = new Chromosome( chromosome,
                  this.fitness_obj.apply( chromosome ) );
    this.population.push( new_guy );
    this.rank();
    this.population.pop(); // extracts the last

}
<commit_msg>Reporting workers instead of IPs<commit_after>

self.addEventListener('message', function(e) {
  var data = e.data;
  switch (data.cmd) {

    case 'start':
        init_worker(data.config);
        console.log( 'start' );
        break;
    case 'evolve':
        console.log( 'evolve' );
        do_ea();
        break;
        }

    }, false
);

function init_worker(config) {
    self.population_size = config.population_size;
    self.period = config.period;
    self.traps = config.traps;
    self.trap_len = config.trap_len;
    self.trap_b = config.trap_b;
    self.chromosome_size = traps * trap_len;
    self.experiment_id = null;

    self.trap_fitness = new trap.Trap({
        "l": trap_len,
        "a": 1,
        "b": trap_b,
        "z": trap_len - 1
    });

    self.eo = new Nodeo({
        population_size: self.population_size,
        chromosome_size: self.chromosome_size,
        fitness_func: self.trap_fitness
    });
    //Worker uuid
    self.uuid = config.worker_uuid;
    var xmlhttp = new XMLHttpRequest();
    // PUTs worker info
    xmlhttp.open("PUT", "/start/"+uuid+"/with/"+population_size, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {

            if (xmlhttp.status == 200 /*|| xmlhttp.status == 304*/)
            {
                var data = JSON.parse(xmlhttp.responseText);
                console.log( data.experiment_id  );
                if ( data.experiment_id !== "undefined"  ) {

                    self.experiment_id= data.experiment_id;
                    console.log(self.experiment_id);
                }

                postMessage(
                    {
                        status:'created'
                    });

            }
            else if (xmlhttp2.readyState == 4 &&  xmlhttp.status == 404)
            {
                /// UNABLE TO INITIALIZE
                console.log("Error 404: not_created");
                // TO DO: HANDLE
                postMessage(
                    {
                        status:'not_created'
                    });

            }

        }
    };
    xmlhttp.send();
}

function restart() {

    console.log("restarting");

    self.eo = new Nodeo({
        population_size: self.population_size,
        chromosome_size: self.chromosome_size,
        fitness_func: self.trap_fitness
    });

    postMessage(
        {
            status:'starting'

        });

    do_ea();
}

function do_ea() {
    eo.generation();
    //if ( eo.population[0].fitness == traps*trap_b ) {
    //    console.log('finished before');
    //}

    if ( (eo.generation_count % period === 0) ) {

        // gets a random chromosome from the pool
        var xmlhttp = new XMLHttpRequest();
        var url = "/random";
        xmlhttp.open("GET", url, true);
        xmlhttp.onreadystatechange = function() {

           if (xmlhttp.readyState == 4 ) {

                if (xmlhttp.status == 200 /*|| xmlhttp.status == 304*/)
                {
                    var data = JSON.parse(xmlhttp.responseText);
                    if ( data.chromosome ) {
                        eo.incorporate( data.chromosome );
                       }

                }
                else if ( xmlhttp.status == 404)
                    {   console.log("404");
                        //There is no population
                        postMessage(
                        {
                        status:'no_work',
                        generation_count:eo.generation_count,
                        best:eo.population[0].string,
                        fitness:eo.population[0].fitness,'period':period,
                        pop_size: eo.population.length
                        });
                        console.log("AFTER 404");
                        //No more work
                        //return;

                    }

            }
        };
        xmlhttp.send();

        if (self.experiment_id  !== "undefined" ) {
            var xmlhttp2 = new XMLHttpRequest();
            // And puts another one in the pool
            xmlhttp2.open("PUT", "/experiment/" + self.experiment_id + "/one/" + eo.population[0].string + "/" + eo.population[0].fitness + "/" + uuid, true);
            xmlhttp2.onreadystatechange = function () {
                if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {

                    postMessage(
                        {
                            status: 'working',
                            generation_count: eo.generation_count,
                            best: eo.population[0].string,
                            fitness: eo.population[0].fitness, 'period': period, 'ips': ips,
                            pop_size: eo.population.length,
                            current_expid: self.experiment_id
                        });
                }
                else if (xmlhttp2.readyState == 4 && xmlhttp2.status == 410) {
                    var data = JSON.parse(xmlhttp2.responseText);
                    self.experiment_id = data.current_expid;

                    postMessage({
                            status: 'experiment_not_found',
                            current_experiment_id:self.experiment_id
                        });
                    restart();

                }

            };
            xmlhttp2.send();
        }
        //Workers
        var xmlhttp3 = new XMLHttpRequest();
        var url = "/workers";
        var ips = "";
        xmlhttp3.onreadystatechange = function() {
            if (xmlhttp3.readyState == 4 && xmlhttp3.status == 200) {
                var data = JSON.parse(xmlhttp3.responseText);
                ips = Object.keys( data ).length;

                postMessage({
                    status:'working',
                    generation_count:eo.generation_count,
                    best:eo.population[0].string,
                    fitness:eo.population[0].fitness,
                    'period':period,
                    'ips':ips,
                    pop_size: eo.population.length
                    });

                }

            };
        xmlhttp3.open("GET", url, true);
        xmlhttp3.send();

    }

    if ( eo.population[0].fitness < traps*trap_b ) {

        setTimeout(do_ea, 5);

    }

    else{

        /// FOUND IT

        if (self.experiment_id  !== "undefined" ) {

            var xmlhttp2 = new XMLHttpRequest();
            ///experiment/:expid/one/:chromosome/:fitness/:uuid
            xmlhttp2.open("PUT", "/experiment/" + self.experiment_id + "/one/" + eo.population[0].string + "/" + eo.population[0].fitness + "/" + uuid, true);
            xmlhttp2.onreadystatechange = function () {
                if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
                    postMessage(
                        {
                            status:'finished',
                            generation_count: eo.generation_count,
                            best: eo.population[0].string,
                            fitness: eo.population[0].fitness, 'period': period, 'ips': ips,
                            pop_size: eo.population.length,
                            current_expid: self.experiment_id
                        });

                }
                else if (xmlhttp2.readyState == 4 && xmlhttp2.status == 410) {
                    var data = JSON.parse(xmlhttp2.responseText);
                    self.experiment_id = data.current_expid;

                    postMessage(
                        {
                           status: 'experiment_not_found',
                           current_experiment_id:self.experiment_id

                        });

                }
                // Restart either way
                restart();
                console.log('finished after');
            };

            xmlhttp2.send();
        }

        //close();
    }
}

function Nodeo( options ) {
/*jshint validthis: true */
    for ( var i in options ) {
	this[i] = options[i];
    }
    if ( ! this.population_size ) {
	return new Error ("0 population size");
    }
    if ( ! this.fitness_func ) {
	return new Error ("No fitness func");
    } else if ( typeof( this.fitness_func) === 'function' ) {
	this.fitness_obj = new Fitness( options.fitness_func );
    } else {
	this.fitness_obj = this.fitness_func;
    }
    if ( !this.tournament_size ) {
	this.tournament_size = 2;
    }
    if ( !this.pool_size ) {
	this.pool_size = this.population_size - 2;
    }

    if ( !this.chromosome_size || isNaN(this.chromosome_size) ) {
	throw "Chromosome size error";
    }
    this.population = [];
//    console.log( this.fitness_obj.apply );
    do {
	var this_string = utils.random( this.chromosome_size );
	var chromosome = new Chromosome( this_string,
					 this.fitness_obj.apply( this_string ) );
	this.population.push( chromosome );
    } while( this.population.length < this.population_size );

    // Methods
    this.tournament_selection = tournament_selection;
    this.evaluation = evaluation;
    this.generation= generation;
    this.rank=rank;
    this.incorporate=incorporate;
    this.generation_count=0;
};

// create fitness function object if it does not exist
function Fitness ( f ) {
 /*jshint validthis: true */
    this.apply = f;
}

// Selects a new population of size pool_size via comparing tournament_size chromosomes and taking the best
function tournament_selection( tournament_size, pool_size ) {
/*jshint validthis: true */
    var pool = [];
    if ( tournament_size <= 1 ) {
	return new Error ("Tournament size too small");
    }
    do {
//	var joust = [];
	var best =  this.population[ Math.floor(Math.random()*this.population.length) ] ;
	for ( var i = 1; i < tournament_size; i ++) {
	    var another= this.population[ Math.floor(Math.random()*this.population.length) ];
	    if ( another.fitness > best.fitness) {
		best = another;
	    }
	}
	pool.push( best );
    } while (pool.length < pool_size );
    return pool;
}

// Evaluates all the population not in cache
function evaluation( new_guys ) {
/*jshint validthis: true */
    for (var i in new_guys) {
	new_guys[i].fitness = this.fitness_obj.apply( new_guys[i].string );
    }
}

// sort population
function rank () {
    /*jshint validthis: true */
    var sorted_population = this.population.sort( function(a,b){ return b.fitness - a.fitness; } );
    this.population = sorted_population;
}

// Single generation
function generation() {
    /*jshint validthis: true */
    var chosen = this.tournament_selection( this.tournament_size, this.pool_size);
    this.rank(); // to get the best
    var the_best = [this.population[0],this.population[1]];
    var new_population = this.population[0].reproduction(chosen);
    this.evaluation(new_population);
    this.population = the_best.concat( new_population );
    this.rank(); // ranking twice????
    this.generation_count++;
}

function Trap( options ) {
    for ( var i in options ) {
	this[i] = options[i];
    }
    if ( !this.l ) {
	this.l = 3;
    }
    if ( !this.a ) {
	this.a = 1;
    }
    if ( !this.b ) {
	this.l = 2;
    }
    if ( !this.z ) {
	this.a = this.l-1;
    }

    // Methods
    this.apply = apply;
}

trap = {}
trap.Trap = Trap;

// Applies trap function to chromosome using instance values
function apply( chromosome ){
    return functions.ltrap(chromosome, this.l, this.a, this.b, this.z);
}

// L-trap function
ltrap = function(x,l,a,b,z) {
    var total = 0;
    for ( var i = 0;  i < x.length; i+= l ) {
	var this_substr = x.substr(  i, l );
	var num_ones = 0;
	for ( var j = 0;  j < this_substr.length; j++ ) {
	  num_ones += (this_substr.substring(j,j+1) === "1");
	}
	var this_result;
	if ( num_ones <= z ) {
	  this_result = a*(z-num_ones)/z;
	} else {
	  this_result = b*(num_ones -z)/(l-z);
	}
	total += this_result;
//	console.log("Total " + i + " :"+total + " num_ones " + num_ones );
    }

    return total;
};

functions = {}
functions.ltrap = ltrap;

var utils = {};

// Create a random chromosome
utils.random= function (length){
    var chromosome = '';
    for ( var i = 0; i < length; i++ ){
    chromosome = chromosome + ((Math.random() >= 0.5)? "1": "0") ;
    }

    return chromosome;
};

// Computes maxOnes fitness
utils.max_ones = function (chromosome){
    var ones = 0;
    console.log( "MO " + chromosome);
    for ( var i=0; i < chromosome.length; i++ ){
    ones += parseInt(chromosome.charAt(i));
    }
    return ones;
};

// Creates a single chromosome. Includes all utility functions
function Chromosome(string,fitness){
    this.string = string;
    this.fitness = fitness;

    // functions
    this.invert = invert;
    this.mutate = mutate;
    this.crossover=crossover;
    this.reproduction=reproduction;
}

// Bit-flips the whole chromosome
function invert (chromosome) {
    var inverted='';
    for (var i = 0; i < chromosome.string.length; i ++ ) {
    inverted += chromosome.string.charAt(i).match(/1/)?"0":"1";
    }
    return new Chromosome (inverted);
}

// Bit-flips a single bit
function mutate (chromosome ) {

    var mutation_point = Math.floor( Math.random() * chromosome.string.length);
    var temp = chromosome.string;
    var flip_bit = temp.charAt(mutation_point).match(/1/)?"0":"1";
    var clone = temp.substring(0,mutation_point) +
    flip_bit +
    temp.substring(mutation_point+1,temp.length) ;
    return new Chromosome( clone );
}

// Interchanges a substring between the two parents
function crossover ( chrom1, chrom2 ) {
    var length = chrom1.string.length;
    var xover_point = Math.floor( Math.random() * length);
    var range = 1 + Math.floor(Math.random() * (length - xover_point) );
    var new_chrom1 = chrom1.string.substr(0,xover_point);
    var new_chrom2 = chrom2.string.substr(0,xover_point);
    new_chrom1+= chrom2.string.substring(xover_point,xover_point+range) +
    chrom1.string.substring(xover_point+range,length);
    new_chrom2+= chrom1.string.substring(xover_point,xover_point+range) +
    chrom2.string.substring(xover_point+range,length);
    return [new Chromosome(new_chrom1), new Chromosome(new_chrom2)];
}

// Applies operators to the pool
function reproduction(  pool ) {
/*jshint validthis: true */
    var offspring = [];
    while (pool.length ) {
    var first = pool.splice( Math.floor(Math.random()*pool.length), 1 );
    var second = pool.splice( Math.floor(Math.random()*pool.length), 1 );
    var crossovers = this.crossover( first[0], second[0] );
    for ( var i in crossovers ) {
        offspring.push( this.mutate(crossovers[i]));
    }
    }
    return offspring;
}

function incorporate( chromosome ) {
//    console.log(chromosome);
    if ( chromosome.length != this.chromosome_size )
    throw "Bad chromosome length" + chromosome.length + "!=" + this.chromosome_size ;
    var new_guy = new Chromosome( chromosome,
                  this.fitness_obj.apply( chromosome ) );
    this.population.push( new_guy );
    this.rank();
    this.population.pop(); // extracts the last

}
<|endoftext|>


<commit_before>// param direction:true mean up,false mean down
// 纵向的滚动
function publicRoll(node,direction) {
	// debugger
	var selfHeight=parseInt(node.css('height'))
	var selfTop=parseInt(node.css('top'))
	var parentNode=node.parent()
	var parentHeight=parseInt(parentNode.css('height'))

	var scrollTimes=parseInt(selfHeight/parentHeight)
	var singleSrcollHeight=selfHeight/scrollTimes
	// console.log('times',(scrollTimes--))
	if (direction) {
		if (-selfTop/singleSrcollHeight==(scrollTimes-1)){
		var reverseDireTimer=setInterval(function (e) {
			selfTop+=6
			node.css('top',selfTop+'px')
			if (selfTop>=0) {
				clearInterval(reverseDireTimer)
				// console.log(-selfTop/singleSrcollHeight)
			}
		},1)
		}else{
			var timer=setInterval(function  () {
				selfTop-=6
				node.css('top',selfTop+'px')
				if (-selfTop%singleSrcollHeight==0) {
					clearInterval(timer)
					// console.log(-selfTop/singleSrcollHeight)
				}
			},3)
		}
	}//end if
	else {
		if (selfTop>=0){
			var reverseDireTimer2=setInterval(function (e) {
				selfTop-=6
				node.css('top',selfTop+'px')
				if (selfTop<=-singleSrcollHeight*(scrollTimes-1)) {
					clearInterval(reverseDireTimer2)
					// console.log(-selfTop/singleSrcollHeight)
				}
			},1)
		}else{
			var timer2=setInterval(function  () {

				selfTop+=6
				node.css('top',selfTop+'px')
				if (-selfTop%singleSrcollHeight==0) {
					clearInterval(timer2)
					// console.log(-selfTop/singleSrcollHeight)
				}
			},3)
		}

	}//end else
}

//因为收藏功能和加入购物车功能在处理逻辑是很多相同的地方，
		//所以把飞入效果做成一个function，传入的参数点击元素，新元素以及目标元素
		function flyTo(sourceEle,destinaEle,newEle) {
			// body...
			var sourceX=sourceEle.offset().left
			var sourceY=sourceEle.offset().top
			var destinationX=destinaEle.offset().left
			var destinationY=destinaEle.offset().top
			var disX=destinationX-sourceX
			var disY=destinationY-sourceY
			var speedX=disX/100
			var speedY=0
			var accerY=0
			if (disY>0) {
				speedY=15
				accerY=(disY-speedY*100)*2/10000
			}
			else{
				speedY=-15
				accerY=(disY-speedY*100)*2/10000
			}
			// accerY=(disY+15*100)*2/10000
			// console.log('dis',disY,'speed',speedY,'accerY',accerY)
			var nowX=0
			var nowY=0
			var timer=window.setInterval(function(){
				nowX+=speedX
				speedY+=accerY
				// console.log(accerY,speedY)
				nowY+=speedY
				newEle.css('top',nowY)
				newEle.css('left',nowX)
				if (nowX>disX) {
					clearInterval(timer)
					var temPen=document.getElementById(newEle.attr('id'))
					temPen.parentNode.removeChild(temPen)
					destinaEle.css('color','#c40000')
					setTimeout(function  () {
						destinaEle.css('color','white')
					}, 100)
				}
			},15)
		}
<commit_msg>Update public.js<commit_after>// param direction:true mean up,false mean down
// 纵向的滚动
function publicRoll(node,direction) {
	// debugger
	var selfHeight=parseInt(node.css('height'))
	var selfTop=parseInt(node.css('top'))
	var parentNode=node.parent()
	var parentHeight=parseInt(parentNode.css('height'))

	var scrollTimes=parseInt(selfHeight/parentHeight)
	var singleSrcollHeight=selfHeight/scrollTimes
	// console.log('times',(scrollTimes--))
	if (direction) {
		if (-selfTop/singleSrcollHeight==(scrollTimes-1)){
		var reverseDireTimer=setInterval(function (e) {
			selfTop+=6
			node.css('top',selfTop+'px')
			if (selfTop>=0) {
				clearInterval(reverseDireTimer)
				// console.log(-selfTop/singleSrcollHeight)
			}
		},1)
		}else{
			var timer=setInterval(function  () {
				selfTop-=6
				node.css('top',selfTop+'px')
				if (-selfTop%singleSrcollHeight==0) {
					clearInterval(timer)
					// console.log(-selfTop/singleSrcollHeight)
				}
			},3)
		}
	}//end if
	else {
		if (selfTop>=0){
			var reverseDireTimer2=setInterval(function (e) {
				selfTop-=6
				node.css('top',selfTop+'px')
				if (selfTop<=-singleSrcollHeight*(scrollTimes-1)) {
					clearInterval(reverseDireTimer2)
					// console.log(-selfTop/singleSrcollHeight)
				}
			},1)
		}else{
			var timer2=setInterval(function  () {

				selfTop+=6
				node.css('top',selfTop+'px')
				if (-selfTop%singleSrcollHeight==0) {
					clearInterval(timer2)
					// console.log(-selfTop/singleSrcollHeight)
				}
			},3)
		}

	}//end else
}

//因为收藏功能和加入购物车功能在处理逻辑是很多相同的地方，
//所以把飞入效果做成一个function，传入的参数点击元素，新元素以及目标元素
function flyTo(sourceEle,destinaEle,newEle) {
// body...
//获取飞入动画对应的起始元素的坐标值
var sourceX=sourceEle.offset().left
var sourceY=sourceEle.offset().top
//获取飞入动画对应的结束元素的坐标值
var destinationX=destinaEle.offset().left
var destinationY=destinaEle.offset().top
//计算得到飞入动画在横向与纵向移动的距离
var disX=destinationX-sourceX
var disY=destinationY-sourceY
//飞行时间取100个计时器间隔时间，计算得到横向飞行速度
var speedX=disX/100
var speedY=0
var accerY=0
//结束元素有可能在起始元素的上方，也有可能在起始元素的下方，分别计算纵向的初始速度和加速度
if (disY>0) {
	speedY=15
	accerY=(disY-speedY*100)*2/10000
}
else{
	speedY=-15
	accerY=(disY-speedY*100)*2/10000
}
// accerY=(disY+15*100)*2/10000
// console.log('dis',disY,'speed',speedY,'accerY',accerY)
var nowX=0
var nowY=0
//创建定时器，每隔15毫秒执行一次，由于浏览器的性能问题不是真正的15毫秒应该是大于15毫秒，
//这里使用一个较小的时间间隔就可以在单位时间内执行更多次的移动，从而使飞入动画更加流畅
var timer=window.setInterval(function(){
	nowX+=speedX
	speedY+=accerY
	// console.log(accerY,speedY)
	nowY+=speedY
	newEle.css('top',nowY)
	newEle.css('left',nowX)
	//当飞动元素的横坐标值已经大于飞行的横向距离就清空定时器
	if (nowX>disX) {
		clearInterval(timer)
		var temPen=document.getElementById(newEle.attr('id'))
		temPen.parentNode.removeChild(temPen)
		//在结束时设置结束元素样式变为红色，并使用定时器在100毫秒之后设置为原来的背景色，从而加强了飞入的动画效果
		destinaEle.css('color','#c40000')
		setTimeout(function  () {
			destinaEle.css('color','white')
		}, 100)
	}
},15)
}
<|endoftext|>


<commit_before>$('form').submit(function(event) {

  event.preventDefault();

  if ($(this).hasClass('shake')) {
    return;
  }

  $.post('/api/login', $(this).serialize(), function(response) {
    location.reload();
  }).error(function() {

    var timeout,
        form = $(this);

    clearTimeout(timeout);

    form.find('input').addClass('wrong');
    form.addClass('shake');

    timeout = setTimeout(function() {
      form.removeClass('shake');
    }, 1000);

  }.bind(this));

});

$('input').keyup(function(event) {
  var code = event.which;

  if (event.which == 13 || event.which == 9) {
    return;
  }

  $(this).removeClass('wrong');
});
<commit_msg>Adjust path to current url<commit_after>$('form').submit(function(event) {

  event.preventDefault();

  if ($(this).hasClass('shake')) {
    return;
  }

  $.post(document.URL, $(this).serialize(), function(response) {
    location.reload();
  }).error(function() {

    var timeout,
        form = $(this);

    clearTimeout(timeout);

    form.find('input').addClass('wrong');
    form.addClass('shake');

    timeout = setTimeout(function() {
      form.removeClass('shake');
    }, 1000);

  }.bind(this));

});

$('input').keyup(function(event) {
  var code = event.which;

  if (event.which == 13 || event.which == 9) {
    return;
  }

  $(this).removeClass('wrong');
});
<|endoftext|>


<commit_before>var baasRef = new Firebase('https://amber-torch-384.firebaseio.com/');

var PollBox = React.createClass({
  loadPollsFromServer: function() {
    baasRef.child('polls').child('question-1').on('child_added', function(snapshot) {
      var poll = snapshot.val();
      poll.id = snapshot.key();
      var data = this.state.data;
      data.push(poll);
      this.setState({data: data});
    }.bind(this));
  },
  handlePollSubmit: function(poll) {
    console.log(poll)
    poll.id = Date.now();
    baasRef.child('polls').child('question-1').push(poll);
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    this.loadPollsFromServer();
    setInterval(this.loadPollsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (

Polls sample

        <PollList data={this.state.data} />
        <PollForm onPollSubmit={this.handlePollSubmit} />

    );
  }
});

var PollList = React.createClass({
  render: function() {
    var pollNodes = this.props.data.map(function(poll) {
      return (
        <Poll author={poll.author} key={poll.id}>
          {poll.text}
        </Poll>
      );
    });
    return (

        {pollNodes.reverse()}

    );
  }
});

var PollForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();
    var author = this.refs.author.value.trim();
    var text = this.refs.text.value.trim();
    if (!text || !author) {
      return;
    }
    this.props.onPollSubmit({author: author, text: text});
    this.refs.author.value = '';
    this.refs.text.value = '';
  },
  render: function() {
    return (
      <form className="pollForm" onSubmit={this.handleSubmit}>
        <input type="text" placeholder="Your name" ref="author" />
        <input type="text" placeholder="Say something..." ref="text" />
        <input type="submit" value="Post" />
      </form>
    );
  }
});

var Poll = React.createClass({
  rawMarkup: function() {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return { __html: rawMarkup };
  },

  render: function() {
    return (

          {this.props.author}

    );
  }
});

ReactDOM.render(
  <PollBox pollInterval={200000} />,
  document.getElementById('content')
);
<commit_msg>rename baas url<commit_after>var baasRef = new Firebase('https://yourfirebaseappname.firebaseio.com/');

var PollBox = React.createClass({
  loadPollsFromServer: function() {
    baasRef.child('polls').child('question-1').on('child_added', function(snapshot) {
      var poll = snapshot.val();
      poll.id = snapshot.key();
      var data = this.state.data;
      data.push(poll);
      this.setState({data: data});
    }.bind(this));
  },
  handlePollSubmit: function(poll) {
    console.log(poll)
    poll.id = Date.now();
    baasRef.child('polls').child('question-1').push(poll);
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    this.loadPollsFromServer();
    setInterval(this.loadPollsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (

Polls sample

        <PollList data={this.state.data} />
        <PollForm onPollSubmit={this.handlePollSubmit} />

    );
  }
});

var PollList = React.createClass({
  render: function() {
    var pollNodes = this.props.data.map(function(poll) {
      return (
        <Poll author={poll.author} key={poll.id}>
          {poll.text}
        </Poll>
      );
    });
    return (

        {pollNodes.reverse()}

    );
  }
});

var PollForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();
    var author = this.refs.author.value.trim();
    var text = this.refs.text.value.trim();
    if (!text || !author) {
      return;
    }
    this.props.onPollSubmit({author: author, text: text});
    this.refs.author.value = '';
    this.refs.text.value = '';
  },
  render: function() {
    return (
      <form className="pollForm" onSubmit={this.handleSubmit}>
        <input type="text" placeholder="Your name" ref="author" />
        <input type="text" placeholder="Say something..." ref="text" />
        <input type="submit" value="Post" />
      </form>
    );
  }
});

var Poll = React.createClass({
  rawMarkup: function() {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return { __html: rawMarkup };
  },

  render: function() {
    return (

          {this.props.author}

    );
  }
});

ReactDOM.render(
  <PollBox pollInterval={200000} />,
  document.getElementById('content')
);
<|endoftext|>


<commit_before>var pathArray = location.href.split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var baseurl = protocol + '//' + host + '/';

plyr.setup({
	controls: ['current-time','play','progress'],
});

var app = new Vue({
	el: '#backstage',
	delimiters: ['[[', ']]'],
	data: {
		vueLoaded: true,
		songForm: false,
		userForm: false,
		instrumentForm: false,
		message: 'Hello Vue!',
		instrumentsInSong: [],
		instrumentUser: '',
		instruments: '',
		song: 'test',
		selectedInstrument: '',
		selectedInstrumentUser: '',
		justAddingInstrument: false,
		info: '',
		sortedSongcasts: '',
		fileChosen: false,
		attachmenttypes: [],
		someValue: false,
		attachmenttypeChosen: false,
		fileupload: '',
		songattachments: [],
		metaEdit: false,
		justAddingAttachment: false,
		percentCompleted: 0,
		justUploading:false,
		attachment_comment: '',
	},
	mounted: function() {
		var _this = this;
		axios.get(baseurl + 'api/instruments').then(function (response) {
			_this.instruments = response.data;
		});

		axios.get(baseurl + 'api/song/' + pathArray[4]).then(function (response) {
			_this.song = response.data;
		});

		axios.get(baseurl + 'api/attachmenttypes').then(function (response) {
			_this.attachmenttypes = response.data;
		});

		axios.get(baseurl + 'api/attachments-by-type/' + pathArray[4]).then(function (response) {
			_this.songattachments = response.data;
		});
	},
	methods: {
		contains: function(needle, haystack) {
			if (haystack) {
				if (haystack.includes(needle)) {
					this.someValue = true;
				}
			}
		},
		sortSongcasts: function (a,b) {
			if (a.cast.instrument.name < b.cast.instrument.name)
				return -1;
			if (a.cast.instrument.name > b.cast.instrument.name)
				return 1;
			return 0;
		},
		songUpdate: function(song_id) {
			var _this = this;
			axios.patch(baseurl + 'songs/' + song_id, _this.song)
				.then(function(response) {
					_this.song = response.data
					_this.metaEdit = false;
				})
				.catch(function(error)  {
					console.log(error)
				});
		},
		instrumentAdd: function() {
			this.instrumentsInSong.push('asd');
			this.justAddingInstrument = true;
		},
		instrumentRemove: function(index) {
			alert(index);
			this.instrumentsInSong.splice(index,1);
		},
		instrumentSelectToggle: function(instrument) {
			this.selectedInstrumentUser = '';
			if(instrument == this.selectedInstrument) {
				return this.selectedInstrument = '';
			}
			this.selectedInstrument = '';
			this.selectedInstrument = instrument;
		},
		instrumentUserSelectToggle: function(user) {
			this.selectedInstrumentUser = '';
			this.selectedInstrumentUser = user;
		},
		instrumentAddCancel: function() {
			this.justAddingInstrument = false;
			this.instrumentsInSong = [];
			this.selectedInstrument = '';
			this.selectedInstrumentUser = '';
		},
		songcastSave: function(song_id,instrument,user) {
			var _this = this;
			axios.get(baseurl + 'songcast/add/' + song_id + '/' + instrument.id + '/' + user.id)
				.then(function (response) {
					if(response.data) {
						_this.song.songcasts.push(response.data);
						_this.justAddingInstrument = false;
						_this.instrumentsInSong = [];
						_this.selectedInstrument = '';
						_this.selectedInstrumentUser = '';
					}
				})
				.catch(function (error) {
					console.log(error);
					_this.info = true;
					setTimeout(function(){
						_this.info = false;
					}, 3000);
				});
		},
		songcastDelete: function(songcast, index) {
			var _this = this;
			if(songcast.id) {
				axios.delete(baseurl + 'songcasts/' + songcast.id)
					.then(function (response) {
						_this.song.songcasts.splice(index,1);
					})
					.catch(function (error) {
						_this.song.songcasts.splice(index,1);
					});
			}
		},

		attachmentAdd: function() {
			var _this = this;

			var output = document.getElementById('output');
			var data = new FormData();
			data.append('file', document.getElementById('file').files[0]);
			data.append('type', _this.attachmenttypeChosen);
			data.append('song_id', _this.song.id);
			data.append('comment', _this.attachment_comment);

			var typeindex = _this.songattachments.findIndex(x => x.id == _this.attachmenttypeChosen);

			var config = {
				onUploadProgress: function(progressEvent) {
					_this.justUploading = true;
					_this.percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
				}
			};

			axios.post(baseurl + 'attachments', data, config)
				.then(function (response) {
					_this.songattachments[typeindex].attachments.unshift(response.data);
					_this.endAddingAttachment();
				})
				.catch(function (err) {
					console.log(err.message);
					_this.endAddingAttachment();
					alert('Entschuldigung, es gab ein Fehler beim Upload :/')
				});
		},

		endAddingAttachment: function() {
			this.justUploading = false;
			this.justAddingAttachment = false;
			this.percentCompleted = 0;
			this.attachmenttypeChosen = false;
			this.fileChosen = false;
			this.attachment_comment = '';
		},

		attachmentDelete: function(attachment, index, attachmenttype_id) {
			var _this = this;

			var confirmAnswer;
			function confirm1() {
				confirmAnswer =  confirm("Wollen Sie diese Seite wirklich sehen?");
			}
			confirm1();

			console.log(confirmAnswer);
			if (confirmAnswer == false) {
				return false;
			}

			var typeindex = _this.songattachments.findIndex(x => x.id == attachmenttype_id);

			axios.delete(baseurl + 'attachments/' + attachment.id)
				.then(function (response) {
					_this.songattachments[typeindex].attachments.splice(index,1);
				})
				.catch(function (error) {
					_this.songattachments[typeindex].attachments.splice(index,1);
				});
		},

		fileExistCheck: function(event) {
			this.fileChosen = event.target.files[0];
		},
	}
});<commit_msg>load plyr when vue is mounted<commit_after>var pathArray = location.href.split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var baseurl = protocol + '//' + host + '/';

var app = new Vue({
	el: '#backstage',
	delimiters: ['[[', ']]'],
	data: {
		vueLoaded: true,
		songForm: false,
		userForm: false,
		instrumentForm: false,
		message: 'Hello Vue!',
		instrumentsInSong: [],
		instrumentUser: '',
		instruments: '',
		song: 'test',
		selectedInstrument: '',
		selectedInstrumentUser: '',
		justAddingInstrument: false,
		info: '',
		sortedSongcasts: '',
		fileChosen: false,
		attachmenttypes: [],
		someValue: false,
		attachmenttypeChosen: false,
		fileupload: '',
		songattachments: [],
		metaEdit: false,
		justAddingAttachment: false,
		percentCompleted: 0,
		justUploading:false,
		attachment_comment: '',
	},
	mounted: function() {
		plyr.setup({
			controls: ['current-time','play','progress'],
		});
		var _this = this;
		axios.get(baseurl + 'api/instruments').then(function (response) {
			_this.instruments = response.data;
		});

		axios.get(baseurl + 'api/song/' + pathArray[4]).then(function (response) {
			_this.song = response.data;
		});

		axios.get(baseurl + 'api/attachmenttypes').then(function (response) {
			_this.attachmenttypes = response.data;
		});

		axios.get(baseurl + 'api/attachments-by-type/' + pathArray[4]).then(function (response) {
			_this.songattachments = response.data;
		});
	},
	methods: {
		contains: function(needle, haystack) {
			if (haystack) {
				if (haystack.includes(needle)) {
					this.someValue = true;
				}
			}
		},
		sortSongcasts: function (a,b) {
			if (a.cast.instrument.name < b.cast.instrument.name)
				return -1;
			if (a.cast.instrument.name > b.cast.instrument.name)
				return 1;
			return 0;
		},
		songUpdate: function(song_id) {
			var _this = this;
			axios.patch(baseurl + 'songs/' + song_id, _this.song)
				.then(function(response) {
					_this.song = response.data
					_this.metaEdit = false;
				})
				.catch(function(error)  {
					console.log(error)
				});
		},
		instrumentAdd: function() {
			this.instrumentsInSong.push('asd');
			this.justAddingInstrument = true;
		},
		instrumentRemove: function(index) {
			alert(index);
			this.instrumentsInSong.splice(index,1);
		},
		instrumentSelectToggle: function(instrument) {
			this.selectedInstrumentUser = '';
			if(instrument == this.selectedInstrument) {
				return this.selectedInstrument = '';
			}
			this.selectedInstrument = '';
			this.selectedInstrument = instrument;
		},
		instrumentUserSelectToggle: function(user) {
			this.selectedInstrumentUser = '';
			this.selectedInstrumentUser = user;
		},
		instrumentAddCancel: function() {
			this.justAddingInstrument = false;
			this.instrumentsInSong = [];
			this.selectedInstrument = '';
			this.selectedInstrumentUser = '';
		},
		songcastSave: function(song_id,instrument,user) {
			var _this = this;
			axios.get(baseurl + 'songcast/add/' + song_id + '/' + instrument.id + '/' + user.id)
				.then(function (response) {
					if(response.data) {
						_this.song.songcasts.push(response.data);
						_this.justAddingInstrument = false;
						_this.instrumentsInSong = [];
						_this.selectedInstrument = '';
						_this.selectedInstrumentUser = '';
					}
				})
				.catch(function (error) {
					console.log(error);
					_this.info = true;
					setTimeout(function(){
						_this.info = false;
					}, 3000);
				});
		},
		songcastDelete: function(songcast, index) {
			var _this = this;
			if(songcast.id) {
				axios.delete(baseurl + 'songcasts/' + songcast.id)
					.then(function (response) {
						_this.song.songcasts.splice(index,1);
					})
					.catch(function (error) {
						_this.song.songcasts.splice(index,1);
					});
			}
		},

		attachmentAdd: function() {
			var _this = this;

			var output = document.getElementById('output');
			var data = new FormData();
			data.append('file', document.getElementById('file').files[0]);
			data.append('type', _this.attachmenttypeChosen);
			data.append('song_id', _this.song.id);
			data.append('comment', _this.attachment_comment);

			var typeindex = _this.songattachments.findIndex(x => x.id == _this.attachmenttypeChosen);

			var config = {
				onUploadProgress: function(progressEvent) {
					_this.justUploading = true;
					_this.percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
				}
			};

			axios.post(baseurl + 'attachments', data, config)
				.then(function (response) {
					_this.songattachments[typeindex].attachments.unshift(response.data);
					_this.endAddingAttachment();
				})
				.catch(function (err) {
					console.log(err.message);
					_this.endAddingAttachment();
					alert('Entschuldigung, es gab ein Fehler beim Upload :/')
				});
		},

		endAddingAttachment: function() {
			this.justUploading = false;
			this.justAddingAttachment = false;
			this.percentCompleted = 0;
			this.attachmenttypeChosen = false;
			this.fileChosen = false;
			this.attachment_comment = '';
		},

		attachmentDelete: function(attachment, index, attachmenttype_id) {
			var _this = this;

			var confirmAnswer;
			function confirm1() {
				confirmAnswer =  confirm("Wollen Sie diese Seite wirklich sehen?");
			}
			confirm1();

			console.log(confirmAnswer);
			if (confirmAnswer == false) {
				return false;
			}

			var typeindex = _this.songattachments.findIndex(x => x.id == attachmenttype_id);

			axios.delete(baseurl + 'attachments/' + attachment.id)
				.then(function (response) {
					_this.songattachments[typeindex].attachments.splice(index,1);
				})
				.catch(function (error) {
					_this.songattachments[typeindex].attachments.splice(index,1);
				});
		},

		fileExistCheck: function(event) {
			this.fileChosen = event.target.files[0];
		},
	}
});<|endoftext|>


<commit_before>var timer = (function()
{
    var running = false;
    var inputTime = 0;
    var targetTime;

    var start = function()
    {
        console.log("Starting");
        running = true;
        inputTime = getInputTime();
        var now = (new Date()).getTime();
        targetTime = now + (inputTime * 1000);
        render();
    };

    var getInputTime = function()
    {
        var timeField = $("#time-input");
        var timeString = timeField.val();
        return timeString * 1;
    };

    var getTimeLeft = function()
    {
        var now = new Date();
        return (targetTime - now.getTime());
    };

    var stop = function()
    {
        running = false;
    };

    var tick = function()
    {
        render();
    };

    var render = function()
    {
        var sleft = getTimeLeft();
        $("#seconds-left").text(sleft);
    };

    /**
     * Initialize the system, hook up event listeners.
     * @returns {undefined}
     */
    var init = function()
    {
        console.log("Initializing");
        $("#tick").click(tick);
        $("#time-input").change(start);
    };

     // public API
    return {
        init: init
    };
})();

$( document ).ready( timer.init );<commit_msg>Some comments<commit_after>// Module pattern as recommended by jquery
var timer = (function()
{
    var running = false;
    var inputTime = 0;
    var targetTime;

    /**
     * Start the ticking.
     *
     * @returns {undefined}
     */
    var start = function()
    {
        console.log("Starting");
        running = true;
        inputTime = getInputTime();
        var now = (new Date()).getTime();
        targetTime = now + (inputTime * 1000);
        render();
    };

    var getInputTime = function()
    {
        var timeField = $("#time-input");
        var timeString = timeField.val();
        return timeString * 1;
    };

    var getTimeLeft = function()
    {
        var now = new Date();
        return (targetTime - now.getTime());
    };

    var stop = function()
    {
        running = false;
    };

    /**
     * Interval callback.
     *
     * @returns {undefined}
     */
    var tick = function()
    {
        render();
    };

    var render = function()
    {
        var sleft = getTimeLeft();
        $("#seconds-left").text(sleft);
    };

    /**
     * Initialize the system, hook up event listeners.
     * @returns {undefined}
     */
    var init = function()
    {
        console.log("Initializing");
        $("#tick").click(tick);
        $("#time-input").change(start);
    };

     // public API
    return {
        init: init
    };
})();

$( document ).ready( timer.init );<|endoftext|>