<commit_before>
// define global variables
let charts = {};
let dtp = {};
let dtf = {};
let query_params;

// -- date time parsers
dtp.detail = d3.timeParse("%Y-%m-%dT%H:%M:%S");
dtp.month_year = d3.timeParse('%b-%y');
dtp.date = d3.timeParse("%Y-%m-%d");

dtf.detail = d3.timeFormat("%Y-%m-%d %H:%M")

// ----------------------- functions

// collect names of instances for field 'data name'
function initializeTypeahead() {
  // jquery 'get' is just a wrapper for jquery 'ajax'
  $.get('/instances/names', function(data){
    $('.typeahead').typeahead({source:data});
  }, "json");
}

function setButtons(val) {
  /* enable and disable ipet eval buttons */
  var value = true;
  if (val == "enabled") {
    var value = false;
  }
  $("#visualize button").each(function() {
    this.disabled = value;
  });
};

function generateCharts(request_data) {
  setButton("disabled");
  request_data._xsrf = getCookie("_xsrf");
  /* makes an ajax request for data and then draws charts */
  $.ajax({
    type: "POST",
    url: "visualize",
    data: request_data,
    success: function (data){
      makeCharts(JSON.parse(data));
      setButton("enabled");
    },
    error:function(){
      alert("Something went wrong.");
      setButton("enabled");
    }
  });
}

function makeCharts(data) {
  //re-populate the form with previously submitted values
  $("[name=data-name]").val(query_params["data-name"]);
  $("[name=start-date]").val(query_params["start-date"]);
  $("[name=end-date]").val(query_params["end-date"]);

  if (!data.length) {
    alert("No results found.");
    return;
  }

  // show charts
  $("#charts").removeAttr("hidden");

  // data preprocessing
  data.forEach(function(d) {
    d.git_commit_timestamp = dtp.detail(d.git_commit_timestamp.split("+")[0]);
    d.git_commit_timestamp_formatted = new Date(d.git_commit_timestamp);
  });

  var ndx = crossfilter(data);

  makeSolvedStatusesChart(data, ndx);
  makeRunModeChart(data, ndx);
  makeSolvingNodesChart(data, ndx);
  makeSolvingTimesChart(data, ndx);
  makeResultsCount(data, ndx);
  makeResultsTable(data, ndx);

  RefreshTable();
  dc.renderAll();

  for (var i = 0; i < dc.chartRegistry.list().length; i++) {
    var chartI = dc.chartRegistry.list()[i];
    chartI.on("filtered", RefreshTable);
  }
}

function makeSolvedStatusesChart(data, ndx) {
  charts.solvedStatusesChart = dc.pieChart('#solved-statuses');

  var solvedStatuses = ndx.dimension(function (d) { return d.Status; });
  var solvedStatusesGroup = solvedStatuses.group();

  charts.solvedStatusesChart
    .width(300)
    .height(300)
    .radius(100)
    .innerRadius(50)
    .dimension(solvedStatuses)
    .group(solvedStatusesGroup)
    .renderLabel(true);
}

function makeRunModeChart(data, ndx) {
  charts.runModesChart = dc.pieChart('#opt-mode');

  var runModes = ndx.dimension(function (d) { return d.opt_flag; });
  var runModeGroup = runModes.group();

  charts.runModesChart
    .width(300)
    .height(300)
    .radius(100)
    .innerRadius(50)
    .dimension(runModes)
    .group(runModeGroup)
    .renderLabel(true);
}

function makeResultsCount(data, ndx) {
  charts.resultsCount = dc.dataCount('.dc-results-count');

  var all = ndx.groupAll();

  charts.resultsCount
    .dimension(ndx)
    .group(all);
}

function makeSolvingTimesChart(data, ndx) {
  charts.solvingTimesChart = dc.scatterPlot("#solving-times");

  var solvingTimes = ndx.dimension(function (d) { return [d.git_commit_timestamp, d.TotalTime_solving]; });
  var solvingTimesGroup = solvingTimes.group();

  var max = Math.max.apply(Math, data.map(function(o){return o.TotalTime_solving;}))
  var min = Math.min.apply(Math, data.map(function(o){return o.TotalTime_solving;}))

  var padding = (max - min);
  if (padding){ padding = padding*.1; } else { padding = 1; }

  charts.solvingTimesChart
    .width(600)
    .height(300)
    .dimension(solvingTimes)
    .group(solvingTimesGroup)
    .x(d3.scaleTime().domain([dtp.date(query_params["start-date"]), dtp.date(query_params["end-date"])]))
    .yAxisPadding(padding)
    .renderHorizontalGridLines(true)
    .yAxisLabel("solving time (seconds)")
    .xAxisLabel("git commit timestamp");

  charts.solvingTimesChart.xAxis().tickFormat(dtp.month_year);
}

function makeSolvingNodesChart(data, ndx) {
  charts.solvingNodesChart = dc.scatterPlot("#solving-nodes");

  var solvingNodes = ndx.dimension(function (d) { return [d.git_commit_timestamp, d.Nodes]; });
  var solvingNodesGroup = solvingNodes.group();

  var max = Math.max.apply(Math, data.map(function(o){return o.Nodes;}))
  var min = Math.min.apply(Math, data.map(function(o){return o.Nodes;}))

  var padding = (max - min);
  if (padding){ padding = padding*.1; } else { padding = 1; }

  charts.solvingNodesChart
    .width(600)
    .height(300)
    .dimension(solvingNodes)
    .group(solvingNodesGroup)
    .x(d3.scaleTime().domain([dtp.date(query_params["start-date"]), dtp.date(query_params["end-date"])]))
    .renderHorizontalGridLines(true)
    .yAxisLabel("# solving nodes")
    .xAxisLabel("git commit timestamp")
    .yAxisPadding(padding);

  charts.solvingNodesChart.xAxis().tickFormat(dtp.month_year);
}

function makeResultsTable(data, ndx) {
  charts.resultsTable = $('#results-table');

  charts.tableDimension = ndx.dimension(
    function (d) {
      return d.opt_flag + ' ' + d.Nodes + ' ' + d.TotalTime_solving + ' ' + d.Iterations +
        ' ' + d.file_path;
    }
  );

  var dataTableOptions = {
    "bFilter": false,
    "bInfo": true,
    "bSort": true,
    columnDefs: [{
        targets: 0,
        data: function (d) { return "" + d.filename + ""; },
        defaultContent: ''
      }, {
        targets: 1,
        data: function (d) { return dtf.detail(d.git_commit_timestamp_formatted); },
        type: 'date',
        defaultContent: 'Not found'
      }, {
        targets: 2,
        data: function (d) { return d.opt_flag; },
        defaultContent: ''
      }, {
        targets: 3,
        data: function (d) { return d.Nodes; },
        defaultContent: ''
      }, {
        targets: 4,
        data: function (d) { return d.TotalTime_solving;},
        defaultContent: ''
      }, {
        targets: 5,
        data: function (d) {return d.Iterations;},
        defaultContent: ''
      },
    ]
  };
  charts.resultsTable.dataTable(dataTableOptions);
}

function RefreshTable() {
  dc.events.trigger(function () {
    alldata = charts.tableDimension.top(Infinity);
    charts.resultsTable.fnClearTable();
    charts.resultsTable.fnAddData(alldata);
    charts.resultsTable.fnDraw();
  });
}

function set_active_tab(route) {
  $(".nav-sidebar li").removeClass("active");
  $(`.nav-sidebar li a[href="/${route}"]`).parent("li").addClass("active");
}

// ------------------ document ready
$(document).ready(function() {
  // check if url is of right format
  if (window.location.search) {
    // get_query_params defined in rb-global.js
    var parts = get_query_params(window.location.search);
    if (Object.keys(parts).length == 4) {
      query_params = parts;
      dc.config.defaultColors(d3.schemeSet1);
      generateCharts(parts);
    } else {
      alert("All fields are required to execute a search!");
    }
  }

  initializeTypeahead();
  init_datetimepicker("datetimepicker_start");
  init_datetimepicker("datetimepicker_end");
});
<commit_msg>fix typo in js<commit_after>
// define global variables
let charts = {};
let dtp = {};
let dtf = {};
let query_params;

// -- date time parsers
dtp.detail = d3.timeParse("%Y-%m-%dT%H:%M:%S");
dtp.month_year = d3.timeParse('%b-%y');
dtp.date = d3.timeParse("%Y-%m-%d");

dtf.detail = d3.timeFormat("%Y-%m-%d %H:%M")

// ----------------------- functions

// collect names of instances for field 'data name'
function initializeTypeahead() {
  // jquery 'get' is just a wrapper for jquery 'ajax'
  $.get('/instances/names', function(data){
    $('.typeahead').typeahead({source:data});
  }, "json");
}

function setButtons(val) {
  /* enable and disable ipet eval buttons */
  var value = true;
  if (val == "enabled") {
    var value = false;
  }
  $("#visualize button").each(function() {
    this.disabled = value;
  });
};

function generateCharts(request_data) {
  setButtons("disabled");
  request_data._xsrf = getCookie("_xsrf");
  /* makes an ajax request for data and then draws charts */
  $.ajax({
    type: "POST",
    url: "visualize",
    data: request_data,
    success: function (data){
      makeCharts(JSON.parse(data));
      setButtons("enabled");
    },
    error:function(){
      alert("Something went wrong.");
      setButtons("enabled");
    }
  });
}

function makeCharts(data) {
  //re-populate the form with previously submitted values
  $("[name=data-name]").val(query_params["data-name"]);
  $("[name=start-date]").val(query_params["start-date"]);
  $("[name=end-date]").val(query_params["end-date"]);

  if (!data.length) {
    alert("No results found.");
    return;
  }

  // show charts
  $("#charts").removeAttr("hidden");

  // data preprocessing
  data.forEach(function(d) {
    d.git_commit_timestamp = dtp.detail(d.git_commit_timestamp.split("+")[0]);
    d.git_commit_timestamp_formatted = new Date(d.git_commit_timestamp);
  });

  var ndx = crossfilter(data);

  makeSolvedStatusesChart(data, ndx);
  makeRunModeChart(data, ndx);
  makeSolvingNodesChart(data, ndx);
  makeSolvingTimesChart(data, ndx);
  makeResultsCount(data, ndx);
  makeResultsTable(data, ndx);

  RefreshTable();
  dc.renderAll();

  for (var i = 0; i < dc.chartRegistry.list().length; i++) {
    var chartI = dc.chartRegistry.list()[i];
    chartI.on("filtered", RefreshTable);
  }
}

function makeSolvedStatusesChart(data, ndx) {
  charts.solvedStatusesChart = dc.pieChart('#solved-statuses');

  var solvedStatuses = ndx.dimension(function (d) { return d.Status; });
  var solvedStatusesGroup = solvedStatuses.group();

  charts.solvedStatusesChart
    .width(300)
    .height(300)
    .radius(100)
    .innerRadius(50)
    .dimension(solvedStatuses)
    .group(solvedStatusesGroup)
    .renderLabel(true);
}

function makeRunModeChart(data, ndx) {
  charts.runModesChart = dc.pieChart('#opt-mode');

  var runModes = ndx.dimension(function (d) { return d.opt_flag; });
  var runModeGroup = runModes.group();

  charts.runModesChart
    .width(300)
    .height(300)
    .radius(100)
    .innerRadius(50)
    .dimension(runModes)
    .group(runModeGroup)
    .renderLabel(true);
}

function makeResultsCount(data, ndx) {
  charts.resultsCount = dc.dataCount('.dc-results-count');

  var all = ndx.groupAll();

  charts.resultsCount
    .dimension(ndx)
    .group(all);
}

function makeSolvingTimesChart(data, ndx) {
  charts.solvingTimesChart = dc.scatterPlot("#solving-times");

  var solvingTimes = ndx.dimension(function (d) { return [d.git_commit_timestamp, d.TotalTime_solving]; });
  var solvingTimesGroup = solvingTimes.group();

  var max = Math.max.apply(Math, data.map(function(o){return o.TotalTime_solving;}))
  var min = Math.min.apply(Math, data.map(function(o){return o.TotalTime_solving;}))

  var padding = (max - min);
  if (padding){ padding = padding*.1; } else { padding = 1; }

  charts.solvingTimesChart
    .width(600)
    .height(300)
    .dimension(solvingTimes)
    .group(solvingTimesGroup)
    .x(d3.scaleTime().domain([dtp.date(query_params["start-date"]), dtp.date(query_params["end-date"])]))
    .yAxisPadding(padding)
    .renderHorizontalGridLines(true)
    .yAxisLabel("solving time (seconds)")
    .xAxisLabel("git commit timestamp");

  charts.solvingTimesChart.xAxis().tickFormat(dtp.month_year);
}

function makeSolvingNodesChart(data, ndx) {
  charts.solvingNodesChart = dc.scatterPlot("#solving-nodes");

  var solvingNodes = ndx.dimension(function (d) { return [d.git_commit_timestamp, d.Nodes]; });
  var solvingNodesGroup = solvingNodes.group();

  var max = Math.max.apply(Math, data.map(function(o){return o.Nodes;}))
  var min = Math.min.apply(Math, data.map(function(o){return o.Nodes;}))

  var padding = (max - min);
  if (padding){ padding = padding*.1; } else { padding = 1; }

  charts.solvingNodesChart
    .width(600)
    .height(300)
    .dimension(solvingNodes)
    .group(solvingNodesGroup)
    .x(d3.scaleTime().domain([dtp.date(query_params["start-date"]), dtp.date(query_params["end-date"])]))
    .renderHorizontalGridLines(true)
    .yAxisLabel("# solving nodes")
    .xAxisLabel("git commit timestamp")
    .yAxisPadding(padding);

  charts.solvingNodesChart.xAxis().tickFormat(dtp.month_year);
}

function makeResultsTable(data, ndx) {
  charts.resultsTable = $('#results-table');

  charts.tableDimension = ndx.dimension(
    function (d) {
      return d.opt_flag + ' ' + d.Nodes + ' ' + d.TotalTime_solving + ' ' + d.Iterations +
        ' ' + d.file_path;
    }
  );

  var dataTableOptions = {
    "bFilter": false,
    "bInfo": true,
    "bSort": true,
    columnDefs: [{
        targets: 0,
        data: function (d) { return "" + d.filename + ""; },
        defaultContent: ''
      }, {
        targets: 1,
        data: function (d) { return dtf.detail(d.git_commit_timestamp_formatted); },
        type: 'date',
        defaultContent: 'Not found'
      }, {
        targets: 2,
        data: function (d) { return d.opt_flag; },
        defaultContent: ''
      }, {
        targets: 3,
        data: function (d) { return d.Nodes; },
        defaultContent: ''
      }, {
        targets: 4,
        data: function (d) { return d.TotalTime_solving;},
        defaultContent: ''
      }, {
        targets: 5,
        data: function (d) {return d.Iterations;},
        defaultContent: ''
      },
    ]
  };
  charts.resultsTable.dataTable(dataTableOptions);
}

function RefreshTable() {
  dc.events.trigger(function () {
    alldata = charts.tableDimension.top(Infinity);
    charts.resultsTable.fnClearTable();
    charts.resultsTable.fnAddData(alldata);
    charts.resultsTable.fnDraw();
  });
}

function set_active_tab(route) {
  $(".nav-sidebar li").removeClass("active");
  $(`.nav-sidebar li a[href="/${route}"]`).parent("li").addClass("active");
}

// ------------------ document ready
$(document).ready(function() {
  // check if url is of right format
  if (window.location.search) {
    // get_query_params defined in rb-global.js
    var parts = get_query_params(window.location.search);
    if (Object.keys(parts).length == 4) {
      query_params = parts;
      dc.config.defaultColors(d3.schemeSet1);
      generateCharts(parts);
    } else {
      alert("All fields are required to execute a search!");
    }
  }

  initializeTypeahead();
  init_datetimepicker("datetimepicker_start");
  init_datetimepicker("datetimepicker_end");
});
<|endoftext|>


<commit_before>import Mixin from '@ember/object/mixin';
import ENV from 'irene/config/environment';
import {
  task
} from 'ember-concurrency';
import {
  observer,
  computed
} from '@ember/object';
import {
  isEmpty
} from '@ember/utils';
import {
  run
} from '@ember/runloop';
import {
  __range__
} from 'irene/utils/utils';

// Classic Mixin object
// Should be deprecated once all the pagination is replaced with class based
const PaginateMixin = Mixin.create({

  offset: 0,
  meta: null,
  version: 0,
  extraQueryStrings: "",
  limit: ENV.paginate.perPageLimit,
  isJsonApiPagination: false,
  isDRFPagination: false,
  offsetMultiplier: ENV.paginate.offsetMultiplier,

  versionIncrementer() {
    this.incrementProperty("version");
  },

  versionTrigger: observer('limit', 'offset', "targetModel", "extraQueryStrings", function () {
    return (() => {
      const result = [];
      for (let property of ['limit', 'offset', "targetModel", "extraQueryStrings"]) {
        const propertyOldName = `_${property}`;
        const propertyNewValue = this.get(property);
        const propertyOldValue = this.get(propertyOldName);
        const propertyChanged = propertyOldValue !== propertyNewValue;
        if (propertyChanged) {
          this.set(propertyOldName, propertyNewValue);
          result.push(run.once(this, 'versionIncrementer'));
        } else {
          result.push(undefined);
        }
      }
      return result;
    })();
  }),

  objects: computed('extraQueryStrings', 'isDRFPagination', 'isJsonApiPagination', 'limit', 'offset', 'offsetMultiplier', 'store', 'targetModel', 'version', function () {
    let query;
    if (this.get('isJsonApiPagination')) {
      const query_limit = this.get("limit");
      const query_offset = this.get("offset");
      query = {
        'page[limit]': this.get("limit"),
        'page[offset]': query_limit * query_offset
      };
    } else {
      query = {
        limit: this.get("limit"),
        offset: this.get("offset")
      };
    }
    const extraQueryStrings = this.get("extraQueryStrings");
    if (!isEmpty(extraQueryStrings)) {
      const extraQueries = JSON.parse(extraQueryStrings);
      for (let key in extraQueries) {
        const value = extraQueries[key];
        query[key] = value;
      }
    }
    const targetModel = this.get("targetModel");
    if (this.get('isDRFPagination')) {
      query.offset = query.offset * (this.get("offsetMultiplier") || 1);
    }
    const objects = this.get('store').query(targetModel, query);
    objects.then((result) => {
      const {
        meta
      } = result;
      if (result.links && result.meta.pagination) {
        meta.total = result.meta.pagination.count;
        this.set('isJsonApiPagination', true); // eslint-disable-line
      }
      if ("count" in result.meta) {
        meta.total = result.meta.count || 0;
        /*
        count is only defined for DRF
        JSONAPI has total
        */
        this.set('isDRFPagination', true); // eslint-disable-line
      }
      // Set loading property
      this.set('isLoading', false); // eslint-disable-line
      return this.set("meta", meta); // eslint-disable-line
    });
    return objects;
  }),

  sortedObjects: computed.sort('objects', 'sortProperties'),
  objectCount: computed.alias('objects.length'),
  hasObjects: computed.gt('objectCount', 0),
  hasNoObject: computed.equal('meta.count', 0),

  maxOffset: computed("meta.total", "limit", function () {
    const limit = this.get("limit");
    const total = this.get("meta.total" || 0);
    if (total === 0) {
      return 0;
    }
    return Math.ceil(total / limit) - 1;
  }), // `-1` because offset starts from 0

  /**
   * @property {Boolean} isContainObjects
   * Property to check whether the model has atleast an object
   */
  isContainObjects: computed.or('hasObjects', 'meta.total'),

  /**
   * @property {Boolean} isEmpty
   * Property to check the number of total objects
   */
  isEmpty: computed.equal('meta.total', 0),

  pages: computed("maxOffset", "offset", function () {
    const offset = this.get("offset");
    const maxOffset = this.get("maxOffset");
    let startPage = 0;
    let stopPage = maxOffset;
    let offsetDiffStart = 0;
    let offsetDiffStop = 0;

    if ([NaN, 0, 1].includes(maxOffset)) {
      return [];
    }
    if (maxOffset <= (ENV.paginate.pagePadding * 2)) {
      return __range__(startPage, stopPage, true);
    }

    if (offset > ENV.paginate.pagePadding) {
      startPage = offset - ENV.paginate.pagePadding;
    } else {
      offsetDiffStart = ENV.paginate.pagePadding - offset;
    }

    if (maxOffset >= (ENV.paginate.pagePadding + offset)) {
      stopPage = ENV.paginate.pagePadding + offset;
    } else {
      offsetDiffStop = (ENV.paginate.pagePadding + offset) - maxOffset;
    }

    startPage -= offsetDiffStop;
    stopPage += offsetDiffStart;

    return __range__(startPage, stopPage, true);
  }),

  preDot: computed("offset", function () {
    const offset = this.get("offset");
    return (offset - ENV.paginate.pagePadding) > 0;
  }),

  postDot: computed("offset", "maxOffset", function () {
    const offset = this.get("offset");
    const maxOffset = this.get("maxOffset");
    return (offset + ENV.paginate.pagePadding) < maxOffset;
  }),

  hasPrevious: computed.gt("offset", 0),

  hasNext: computed('offset', 'maxOffset', function () {
    const offset = this.get("offset");
    const maxOffset = this.get("maxOffset");
    return offset < maxOffset;
  }),

  setOffset(offset) {
    this.set("offset", offset);
  },

  actions: {

    gotoPageFirst() {
      this.send("gotoPage", 0);
    },

    gotoPagePrevious() {
      this.decrementProperty("offset");
      this.send("gotoPage", this.get("offset"));
    },

    gotoPage(offset) {
      this.setOffset(offset);
    },

    gotoPageNext() {
      this.incrementProperty("offset");
      this.send("gotoPage", this.get("offset"));
    },

    gotoPageLast() {
      this.send("gotoPage", this.get("maxOffset"));
    }
  }
});

// Class basaed mixin support for glimmer components
import {
  action
} from '@ember/object';
import {
  tracked
} from '@glimmer/tracking';
import {
  gt,
  equal,
  alias
} from '@ember/object/computed';
import {
  scheduleOnce
} from '@ember/runloop';
import {
  inject as service
} from '@ember/service';

export const PaginationMixin = superclass => class extends superclass {
  @service store;

  constructor() {
    super(...arguments);
    scheduleOnce('afterRender', this, this.once);
  }

  @tracked offset = 0;
  @tracked meta = null;
  @tracked version = 0;
  @tracked extraQueryStrings = "";
  @tracked limit = ENV.paginate.perPageLimit;
  @tracked isJsonApiPagination = false;
  @tracked isDRFPagination = false;
  @tracked error = null;
  @tracked currentObjects = [];

  @action
  gotoPage(offset) {
    this.setOffset(offset);
  }

  @action
  gotoPageFirst() {
    this.gotoPage(0)
  }

  @action
  gotoPagePrevious() {
    this.gotoPage(this.offset - 1)
  }

  @action
  gotoPageNext() {
    this.gotoPage(this.offset + 1);
  }

  @action
  gotoPageLast() {
    this.gotoPage(this.maxOffset)
  }

  reload() {
    return this.fetchObjects.perform();
  }

  once() {
    this.reload();
  }

  get currentQuery() {
    let query;
    if (this.isJsonApiPagination) {
      const query_limit = this.limit;
      const query_offset = this.offset;
      query = {
        'page[limit]': this.limit,
        'page[offset]': query_limit * query_offset
      };
    } else {
      query = {
        limit: this.limit,
        offset: this.offset
      };
    }
    const extraQueryStrings = this.extraQueryStrings;
    if (!isEmpty(extraQueryStrings)) {
      const extraQueries = JSON.parse(extraQueryStrings);
      for (let key in extraQueries) {
        const value = extraQueries[key];
        query[key] = value;
      }
    }
    if (this.isDRFPagination) {
      query.offset = query.offset * (this.limit || 1);
    }
    return query
  }

  get isLoading() {
    return this.fetchObjects.isRunning;
  }

  @task(function* () {
    const query = this.currentQuery;
    const targetModel = this.targetModel;
    try {
      const objects = yield this.store.query(targetModel, query);
      const meta = objects.meta;
      if (objects.links && objects.meta.pagination) {
        meta.total = objects.meta.pagination.count;
        this.isJsonApiPagination = true;
      }
      if ("count" in objects.meta) {
        meta.total = objects.meta.count || 0;
        /*
        count is only defined for DRF
        JSONAPI has total
        */
        this.isDRFPagination = true;
      }
      this.meta = meta;
      this.currentObjects = objects;
    } catch (err) {
      this.error = err;
      this.currentObjects = [];
    }
  })
  fetchObjects

  get objects() {
    return this.currentObjects;
  }

  @alias('objects.length') objectCount

  @gt('objectCount', 0) hasObjects;

  @equal('meta.count', 0) hasNoObject;

  @alias('meta.total') totalCount;

  @computed('meta.total', 'limit')
  get maxOffset() {
    const limit = this.limit;
    const total = this.meta ? this.meta.total : 0 || 0;
    if (total === 0) {
      return 0;
    }
    return Math.ceil(total / limit) - 1;
  } // `-1` because offset starts from 0

  @computed("maxOffset", "offset")
  get pages() {
    const offset = this.offset;
    const maxOffset = this.maxOffset;
    let startPage = 0;
    let stopPage = maxOffset;
    let offsetDiffStart = 0;
    let offsetDiffStop = 0;

    if ([NaN, 0, 1].includes(maxOffset)) {
      return [];
    }
    if (maxOffset <= (ENV.paginate.pagePadding * 2)) {
      return __range__(startPage, stopPage, true);
    }

    if (offset > ENV.paginate.pagePadding) {
      startPage = offset - ENV.paginate.pagePadding;
    } else {
      offsetDiffStart = ENV.paginate.pagePadding - offset;
    }

    if (maxOffset >= (ENV.paginate.pagePadding + offset)) {
      stopPage = ENV.paginate.pagePadding + offset;
    } else {
      offsetDiffStop = (ENV.paginate.pagePadding + offset) - maxOffset;
    }

    startPage -= offsetDiffStop;
    stopPage += offsetDiffStart;

    return __range__(startPage, stopPage, true);
  }

  @computed("offset")
  get preDot() {
    return (this.offset - ENV.paginate.pagePadding) > 0;
  }

  @computed("offset", "maxOffset", )
  get postDot() {
    return (this.offset + ENV.paginate.pagePadding) < this.maxOffset;
  }

  @gt("offset", 0) hasPrevious

  @computed('offset', 'maxOffset', )
  get hasNext() {
    return this.offset < this.maxOffset;
  }

  setOffset(offset) {
    this.offset = offset;
    this.fetchObjects.perform();
  }
}

export default PaginateMixin;
<commit_msg>Set DRF pagination true by default in pagination<commit_after>import Mixin from '@ember/object/mixin';
import ENV from 'irene/config/environment';
import {
  task
} from 'ember-concurrency';
import {
  observer,
  computed
} from '@ember/object';
import {
  isEmpty
} from '@ember/utils';
import {
  run
} from '@ember/runloop';
import {
  __range__
} from 'irene/utils/utils';

// Classic Mixin object
// Should be deprecated once all the pagination is replaced with class based
const PaginateMixin = Mixin.create({

  offset: 0,
  meta: null,
  version: 0,
  extraQueryStrings: "",
  limit: ENV.paginate.perPageLimit,
  isJsonApiPagination: false,
  isDRFPagination: true,
  offsetMultiplier: ENV.paginate.offsetMultiplier,

  versionIncrementer() {
    this.incrementProperty("version");
  },

  versionTrigger: observer('limit', 'offset', "targetModel", "extraQueryStrings", function () {
    return (() => {
      const result = [];
      for (let property of ['limit', 'offset', "targetModel", "extraQueryStrings"]) {
        const propertyOldName = `_${property}`;
        const propertyNewValue = this.get(property);
        const propertyOldValue = this.get(propertyOldName);
        const propertyChanged = propertyOldValue !== propertyNewValue;
        if (propertyChanged) {
          this.set(propertyOldName, propertyNewValue);
          result.push(run.once(this, 'versionIncrementer'));
        } else {
          result.push(undefined);
        }
      }
      return result;
    })();
  }),

  objects: computed('extraQueryStrings', 'isDRFPagination', 'isJsonApiPagination', 'limit', 'offset', 'offsetMultiplier', 'store', 'targetModel', 'version', function () {
    let query;
    if (this.get('isJsonApiPagination')) {
      const query_limit = this.get("limit");
      const query_offset = this.get("offset");
      query = {
        'page[limit]': this.get("limit"),
        'page[offset]': query_limit * query_offset
      };
    } else {
      query = {
        limit: this.get("limit"),
        offset: this.get("offset")
      };
    }
    const extraQueryStrings = this.get("extraQueryStrings");
    if (!isEmpty(extraQueryStrings)) {
      const extraQueries = JSON.parse(extraQueryStrings);
      for (let key in extraQueries) {
        const value = extraQueries[key];
        query[key] = value;
      }
    }
    const targetModel = this.get("targetModel");
    if (this.get('isDRFPagination')) {
      query.offset = query.offset * (this.get("offsetMultiplier") || 1);
    }
    const objects = this.get('store').query(targetModel, query);
    objects.then((result) => {
      const {
        meta
      } = result;
      if (result.links && result.meta.pagination) {
        meta.total = result.meta.pagination.count;
        this.set('isJsonApiPagination', true); // eslint-disable-line
        this.set('isDRFPagination', false); // eslint-disable-line
      }
      if ("count" in result.meta) {
        meta.total = result.meta.count || 0;
        /*
        count is only defined for DRF
        JSONAPI has total
        */
        this.set('isJsonApiPagination', false); // eslint-disable-line
        this.set('isDRFPagination', true); // eslint-disable-line
      }
      // Set loading property
      this.set('isLoading', false); // eslint-disable-line
      return this.set("meta", meta); // eslint-disable-line
    });
    return objects;
  }),

  sortedObjects: computed.sort('objects', 'sortProperties'),
  objectCount: computed.alias('objects.length'),
  hasObjects: computed.gt('objectCount', 0),
  hasNoObject: computed.equal('meta.count', 0),

  maxOffset: computed("meta.total", "limit", function () {
    const limit = this.get("limit");
    const total = this.get("meta.total" || 0);
    if (total === 0) {
      return 0;
    }
    return Math.ceil(total / limit) - 1;
  }), // `-1` because offset starts from 0

  /**
   * @property {Boolean} isContainObjects
   * Property to check whether the model has atleast an object
   */
  isContainObjects: computed.or('hasObjects', 'meta.total'),

  /**
   * @property {Boolean} isEmpty
   * Property to check the number of total objects
   */
  isEmpty: computed.equal('meta.total', 0),

  pages: computed("maxOffset", "offset", function () {
    const offset = this.get("offset");
    const maxOffset = this.get("maxOffset");
    let startPage = 0;
    let stopPage = maxOffset;
    let offsetDiffStart = 0;
    let offsetDiffStop = 0;

    if ([NaN, 0, 1].includes(maxOffset)) {
      return [];
    }
    if (maxOffset <= (ENV.paginate.pagePadding * 2)) {
      return __range__(startPage, stopPage, true);
    }

    if (offset > ENV.paginate.pagePadding) {
      startPage = offset - ENV.paginate.pagePadding;
    } else {
      offsetDiffStart = ENV.paginate.pagePadding - offset;
    }

    if (maxOffset >= (ENV.paginate.pagePadding + offset)) {
      stopPage = ENV.paginate.pagePadding + offset;
    } else {
      offsetDiffStop = (ENV.paginate.pagePadding + offset) - maxOffset;
    }

    startPage -= offsetDiffStop;
    stopPage += offsetDiffStart;

    return __range__(startPage, stopPage, true);
  }),

  preDot: computed("offset", function () {
    const offset = this.get("offset");
    return (offset - ENV.paginate.pagePadding) > 0;
  }),

  postDot: computed("offset", "maxOffset", function () {
    const offset = this.get("offset");
    const maxOffset = this.get("maxOffset");
    return (offset + ENV.paginate.pagePadding) < maxOffset;
  }),

  hasPrevious: computed.gt("offset", 0),

  hasNext: computed('offset', 'maxOffset', function () {
    const offset = this.get("offset");
    const maxOffset = this.get("maxOffset");
    return offset < maxOffset;
  }),

  setOffset(offset) {
    this.set("offset", offset);
  },

  actions: {

    gotoPageFirst() {
      this.send("gotoPage", 0);
    },

    gotoPagePrevious() {
      this.decrementProperty("offset");
      this.send("gotoPage", this.get("offset"));
    },

    gotoPage(offset) {
      this.setOffset(offset);
    },

    gotoPageNext() {
      this.incrementProperty("offset");
      this.send("gotoPage", this.get("offset"));
    },

    gotoPageLast() {
      this.send("gotoPage", this.get("maxOffset"));
    }
  }
});

// Class basaed mixin support for glimmer components
import {
  action
} from '@ember/object';
import {
  tracked
} from '@glimmer/tracking';
import {
  gt,
  equal,
  alias
} from '@ember/object/computed';
import {
  scheduleOnce
} from '@ember/runloop';
import {
  inject as service
} from '@ember/service';

export const PaginationMixin = superclass => class extends superclass {
  @service store;

  constructor() {
    super(...arguments);
    scheduleOnce('afterRender', this, this.once);
  }

  @tracked offset = 0;
  @tracked meta = null;
  @tracked version = 0;
  @tracked extraQueryStrings = "";
  @tracked limit = ENV.paginate.perPageLimit;
  @tracked isJsonApiPagination = false;
  @tracked isDRFPagination = true;
  @tracked error = null;
  @tracked currentObjects = [];

  @action
  gotoPage(offset) {
    this.setOffset(offset);
  }

  @action
  gotoPageFirst() {
    this.gotoPage(0)
  }

  @action
  gotoPagePrevious() {
    this.gotoPage(this.offset - 1)
  }

  @action
  gotoPageNext() {
    this.gotoPage(this.offset + 1);
  }

  @action
  gotoPageLast() {
    this.gotoPage(this.maxOffset)
  }

  reload() {
    return this.fetchObjects.perform();
  }

  once() {
    this.reload();
  }

  get currentQuery() {
    let query;
    if (this.isJsonApiPagination) {
      const query_limit = this.limit;
      const query_offset = this.offset;
      query = {
        'page[limit]': this.limit,
        'page[offset]': query_limit * query_offset
      };
    } else {
      query = {
        limit: this.limit,
        offset: this.offset
      };
    }
    const extraQueryStrings = this.extraQueryStrings;
    if (!isEmpty(extraQueryStrings)) {
      const extraQueries = JSON.parse(extraQueryStrings);
      for (let key in extraQueries) {
        const value = extraQueries[key];
        query[key] = value;
      }
    }
    if (this.isDRFPagination) {
      query.offset = query.offset * (this.limit || 1);
    }
    return query
  }

  get isLoading() {
    return this.fetchObjects.isRunning;
  }

  @task(function* () {
    const query = this.currentQuery;
    const targetModel = this.targetModel;
    try {
      const objects = yield this.store.query(targetModel, query);
      const meta = objects.meta;
      if (objects.links && objects.meta.pagination) {
        meta.total = objects.meta.pagination.count;
        this.isJsonApiPagination = true;
        this.isDRFPagination = false;
      }
      if ("count" in objects.meta) {
        meta.total = objects.meta.count || 0;
        /*
        count is only defined for DRF
        JSONAPI has total
        */
        this.isJsonApiPagination = false;
        this.isDRFPagination = true;
      }
      this.meta = meta;
      this.currentObjects = objects;
    } catch (err) {
      this.error = err;
      this.currentObjects = [];
    }
  })
  fetchObjects

  get objects() {
    return this.currentObjects;
  }

  @alias('objects.length') objectCount

  @gt('objectCount', 0) hasObjects;

  @equal('meta.count', 0) hasNoObject;

  @alias('meta.total') totalCount;

  @computed('meta.total', 'limit')
  get maxOffset() {
    const limit = this.limit;
    const total = this.meta ? this.meta.total : 0 || 0;
    if (total === 0) {
      return 0;
    }
    return Math.ceil(total / limit) - 1;
  } // `-1` because offset starts from 0

  @computed("maxOffset", "offset")
  get pages() {
    const offset = this.offset;
    const maxOffset = this.maxOffset;
    let startPage = 0;
    let stopPage = maxOffset;
    let offsetDiffStart = 0;
    let offsetDiffStop = 0;

    if ([NaN, 0, 1].includes(maxOffset)) {
      return [];
    }
    if (maxOffset <= (ENV.paginate.pagePadding * 2)) {
      return __range__(startPage, stopPage, true);
    }

    if (offset > ENV.paginate.pagePadding) {
      startPage = offset - ENV.paginate.pagePadding;
    } else {
      offsetDiffStart = ENV.paginate.pagePadding - offset;
    }

    if (maxOffset >= (ENV.paginate.pagePadding + offset)) {
      stopPage = ENV.paginate.pagePadding + offset;
    } else {
      offsetDiffStop = (ENV.paginate.pagePadding + offset) - maxOffset;
    }

    startPage -= offsetDiffStop;
    stopPage += offsetDiffStart;

    return __range__(startPage, stopPage, true);
  }

  @computed("offset")
  get preDot() {
    return (this.offset - ENV.paginate.pagePadding) > 0;
  }

  @computed("offset", "maxOffset", )
  get postDot() {
    return (this.offset + ENV.paginate.pagePadding) < this.maxOffset;
  }

  @gt("offset", 0) hasPrevious

  @computed('offset', 'maxOffset', )
  get hasNext() {
    return this.offset < this.maxOffset;
  }

  setOffset(offset) {
    this.offset = offset;
    this.fetchObjects.perform();
  }
}

export default PaginateMixin;
<|endoftext|>


<commit_before>// An singleton that contains and manages the sending of picpilot commands
var picpilot_config=require('../../config/picpilot-config');
var Network=require('../Network');
var Logger=require('../util/Logger');
var Validator=require('../util/Validator');
var SimulationManager=require("../SimulationManager");
var AircraftStatus=require('../AircraftStatus');
var Coordinates=require('../models/Coordinates');

var Commands={
  checkConnection: function(){ //to make sure the data relay connection exists first (otherwise we'll prob get weird errors)
    if(SimulationManager.simulationActive){ //just return false if the simulation is active
      return false;
    }

    if(Network.connections['data_relay']){
      return true;
    }
    else{
      Logger.warn('Cannot send command as the data_relay connection has not yet been established');
      return false;
    }
  },
  sendProtectedCommand:function(command){
    if(this.checkConnection()){
      Network.connections['data_relay'].write(command+':'+picpilot_config.get('command_password')+'\r\n');
    }
    if(SimulationManager.simulationActive){
      Logger.info('[Simulation] Successfully sent command '+command+':'+picpilot_config.get('command_password')+'\r\n')
    }
  },
  sendCommand: function(command, value){
    var value='';
    console.log(arguments);
    for (i = 0; i < arguments.length; i++) {
        value+=arguments[i];
        if(i!==arguments.length-1){
          value+=',';
        }
    }
    console.log(value)
    if(this.checkConnection()){
      Network.connections['data_relay'].write(command+':'+value+'\r\n');
    }
    if(SimulationManager.simulationActive){
      Logger.info('[Simulation] Successfully sent command '+command+':'+value+'\r\n')
    }
  },
  sendRawCommand: function(command){
    if(this.checkConnection()){
      Network.connections['data_relay'].write(command+'\r\n');
    }
    if(SimulationManager.simulationActive){
      Logger.info('[Simulation] Successfully sent command: '+command)
    }
  },
  activateWriteMode: function(){
    this.sendRawCommand('commander');
  },
  sendRoll: function(roll){
    if(Validator.isValidRoll(roll)){
      this.sendCommand('set_rollAngle',roll);
    }
    else{
      Logger.error('Command to not sent since invalid roll value detected! Roll:'+roll);
    }
  },
  sendPitch: function(pitch){
    if(Validator.isValidPitch(pitch)){
      this.sendCommand('set_pitchAngle',pitch);
    }
    else{
      Logger.error('Command to not sent since invalid pitch value detected! Pitch:'+pitch);
    }
  },
  sendHeading: function(heading){
    if(Validator.isValidHeading(heading)){
      this.sendCommand('set_heading',heading);
    }
    else{
      Logger.error('Command to not sent since invalid heading value detected! Heading:'+heading);
    }
  },
  sendAltitude:function(altitude){
    if(Validator.isValidAltitude(altitude)){
      this.sendCommand('set_altitude',altitude);
    }
    else{
      Logger.error('Command to not sent since invalid altitude value detected! Altitude:'+altitude);
    }
  },
  sendThrottle:function(throttle){
    if(Validator.isValidThrottle(throttle)){
      this.sendCommand('set_throttle',throttle);
    }
    else{
      Logger.error('Command to not sent since invalid throttle value detected! Throttle:'+throttle);
    }
  },
  sendFlap:function(flap){
    if(Validator.isValidFlap(flap)){
      this.sendCommand('set_flap',flap);
    }
    else{
      Logger.error('Command to not sent since invalid flap value detected! Flap Setpoint:'+flap);
    }
  },
  sendKPGain: function(type,gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_'+type+'KPGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid gain value detected! Gain value:'+gain);
    }
  },
  sendKIGain: function(type, gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_'+type+'KIGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid gain value detected! Gain value:'+gain);
    }
  },
  sendKDGain: function(type, gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_'+type+'KDGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid gain value detected! Gain value:'+gain);
    }
  },
  sendPathGain: function(gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_pathGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid path gain value detected! Gain value:'+gain);
    }
  },
  sendOrbitGain: function(gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_orbitGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid orbit gain value detected! Gain value:'+gain);
    }
  },
  showGain: function(value){
    if(Validator.isValidNumber(value)){
      this.sendCommand('set_showGain',value);
    }
    else{
      Logger.error('Command to not sent since invalid show gain value detected! Value:'+value);
    }
  },
  sendAutoLevel: function(level){
    if(Validator.isValidNumber(level)){
      this.sendCommand('set_autonomousLevel', level);
    }
    else{
      Logger.error('Command not sent since invalid autonomous level value detected! Value: '+level);
    }
  },
  armPlane: function(){
    this.sendProtectedCommand('arm_vehicle');
  },
  disarmPlane: function(){
    this.sendProtectedCommand('disarm_vehicle');
  },
  killPlane: function(){
    this.sendProtectedCommand('kill_plane');
    AircraftStatus.setKillModeStatus(true);
  },
  unkillPlane: function(){
    this.sendProtectedCommand('unkill_plane');
    AircraftStatus.setKillModeStatus(false);
  },
  dropProbe: function(){
    this.sendCommand('drop_probe',1);
  },
  resetProbe: function(){
    this.sendCommand('reset_probe',1);
  },
  clearWaypoints: function(){
    this.sendCommand('clear_waypoints',1);
  },
  setTargetWaypoint: function(number){
    if(Validator.isValidNumber(number)){
      this.sendCommand('set_targetWaypoint', number);
    }
    else{
      Logger.error('setTargetWaypoint command not since invalid waypoint number was passed in. Number: '+number);
    }
  },
  removeWaypoint: function(number){
    if(Validator.isValidNumber(number)){
      this.sendCommand('remove_waypoint', number);
    }
    else{
      Logger.error('removeWaypoint command not since invalid waypoint number was passed in. Number: '+number);
    }
  },
  returnHome: function(){
    this.sendCommand('return_home',1);
  },
  cancelReturnHome: function(){
    this.sendCommand('cancel_returnHome',1);
  },
  setReturnHome: function(coordinates){
    var coords=Coordinates(coordinates);
    if(coords && coords.alt){
      this.sendCommand('set_ReturnHomeCoordinates',coords.lat, coords.lng, coords.alt);
    }
    else{
      Logger.error('setReturnHome command not since invalid coordinates were passed in. Coordinates: '+coordinates);
    }
  },
  appendWaypoint: function(coordinates, radius){
    var coords=Coordinates(coordinates);
    if(coords && coords.alt && Validator.isValidNumber(radius)){
      this.sendCommand('new_waypoint',coords.lat, coords.lng, coords.alt, radius);
    }
    else{
      Logger.error('appendWaypoint command not since invalid coordinates were passed in. Coordinates: '+coordinates);
    }
  },
  insertWaypoint: function(index,coordinates, radius){
    var coords=Coordinates(coordinates);
    if(Validator.isInteger(index) && coords && coords.alt && Validator.isValidNumber(radius)){
      this.sendCommand('insert_Waypoint',coords.lat, coords.lng, coords.alt, radius, index-1, index+1);
    }
    else{
      Logger.error('insertWaypoint command not since invalid waypoint number or coordinates were passed in. Index: '+index);
    }
  }
};
module.exports=Commands;<commit_msg>Unbroke the commands module<commit_after>// An singleton that contains and manages the sending of picpilot commands
var picpilot_config=require('../../config/picpilot-config');
var Network=require('../Network');
var Logger=require('../util/Logger');
var Validator=require('../util/Validator');
var SimulationManager=require("../SimulationManager");
var AircraftStatus=require('../AircraftStatus');
var Coordinates=require('../models/Coordinates');

var Commands={
  checkConnection: function(){ //to make sure the data relay connection exists first (otherwise we'll prob get weird errors)
    if(SimulationManager.simulationActive){ //just return false if the simulation is active
      return false;
    }

    if(Network.connections['data_relay']){
      return true;
    }
    else{
      Logger.warn('Cannot send command as the data_relay connection has not yet been established');
      return false;
    }
  },
  sendProtectedCommand:function(command){
    if(this.checkConnection()){
      Network.connections['data_relay'].write(command+':'+picpilot_config.get('command_password')+'\r\n');
    }
    if(SimulationManager.simulationActive){
      Logger.info('[Simulation] Successfully sent command '+command+':'+picpilot_config.get('command_password')+'\r\n')
    }
  },
  sendCommand: function(command, value){
    if(this.checkConnection()){
      Network.connections['data_relay'].write(command+':'+value+'\r\n');
    }
    if(SimulationManager.simulationActive){
      Logger.info('[Simulation] Successfully sent command '+command+':'+value+'\r\n')
    }
  },
  sendRawCommand: function(command){
    if(this.checkConnection()){
      Network.connections['data_relay'].write(command+'\r\n');
    }
    if(SimulationManager.simulationActive){
      Logger.info('[Simulation] Successfully sent command: '+command)
    }
  },
  activateWriteMode: function(){
    this.sendRawCommand('commander');
  },
  sendRoll: function(roll){
    if(Validator.isValidRoll(roll)){
      this.sendCommand('set_rollAngle',roll);
    }
    else{
      Logger.error('Command to not sent since invalid roll value detected! Roll:'+roll);
    }
  },
  sendPitch: function(pitch){
    if(Validator.isValidPitch(pitch)){
      this.sendCommand('set_pitchAngle',pitch);
    }
    else{
      Logger.error('Command to not sent since invalid pitch value detected! Pitch:'+pitch);
    }
  },
  sendHeading: function(heading){
    if(Validator.isValidHeading(heading)){
      this.sendCommand('set_heading',heading);
    }
    else{
      Logger.error('Command to not sent since invalid heading value detected! Heading:'+heading);
    }
  },
  sendAltitude:function(altitude){
    if(Validator.isValidAltitude(altitude)){
      this.sendCommand('set_altitude',altitude);
    }
    else{
      Logger.error('Command to not sent since invalid altitude value detected! Altitude:'+altitude);
    }
  },
  sendThrottle:function(throttle){
    if(Validator.isValidThrottle(throttle)){
      this.sendCommand('set_throttle',throttle);
    }
    else{
      Logger.error('Command to not sent since invalid throttle value detected! Throttle:'+throttle);
    }
  },
  sendFlap:function(flap){
    if(Validator.isValidFlap(flap)){
      this.sendCommand('set_flap',flap);
    }
    else{
      Logger.error('Command to not sent since invalid flap value detected! Flap Setpoint:'+flap);
    }
  },
  sendKPGain: function(type,gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_'+type+'KPGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid gain value detected! Gain value:'+gain);
    }
  },
  sendKIGain: function(type, gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_'+type+'KIGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid gain value detected! Gain value:'+gain);
    }
  },
  sendKDGain: function(type, gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_'+type+'KDGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid gain value detected! Gain value:'+gain);
    }
  },
  sendPathGain: function(gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_pathGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid path gain value detected! Gain value:'+gain);
    }
  },
  sendOrbitGain: function(gain){
    if(Validator.isValidNumber(gain)){
      this.sendCommand('set_orbitGain',gain);
    }
    else{
      Logger.error('Command to not sent since invalid orbit gain value detected! Gain value:'+gain);
    }
  },
  showGain: function(value){
    if(Validator.isValidNumber(value)){
      this.sendCommand('set_showGain',value);
    }
    else{
      Logger.error('Command to not sent since invalid show gain value detected! Value:'+value);
    }
  },
  sendAutoLevel: function(level){
    if(Validator.isValidNumber(level)){
      this.sendCommand('set_autonomousLevel', level);
    }
    else{
      Logger.error('Command not sent since invalid autonomous level value detected! Value: '+level);
    }
  },
  armPlane: function(){
    this.sendProtectedCommand('arm_vehicle');
  },
  disarmPlane: function(){
    this.sendProtectedCommand('disarm_vehicle');
  },
  killPlane: function(){
    this.sendProtectedCommand('kill_plane');
    AircraftStatus.setKillModeStatus(true);
  },
  unkillPlane: function(){
    this.sendProtectedCommand('unkill_plane');
    AircraftStatus.setKillModeStatus(false);
  },
  dropProbe: function(){
    this.sendCommand('drop_probe',1);
  },
  resetProbe: function(){
    this.sendCommand('reset_probe',1);
  },
  clearWaypoints: function(){
    this.sendCommand('clear_waypoints',1);
  },
  setTargetWaypoint: function(number){
    if(Validator.isValidNumber(number)){
      this.sendCommand('set_targetWaypoint', number);
    }
    else{
      Logger.error('setTargetWaypoint command not since invalid waypoint number was passed in. Number: '+number);
    }
  },
  removeWaypoint: function(number){
    if(Validator.isValidNumber(number)){
      this.sendCommand('remove_waypoint', number);
    }
    else{
      Logger.error('removeWaypoint command not since invalid waypoint number was passed in. Number: '+number);
    }
  },
  returnHome: function(){
    this.sendCommand('return_home',1);
  },
  cancelReturnHome: function(){
    this.sendCommand('cancel_returnHome',1);
  },
  setReturnHome: function(coordinates){
    var coords=Coordinates(coordinates);
    if(coords && coords.alt){
      this.sendCommand('set_ReturnHomeCoordinates',coords.lat, coords.lng, coords.alt);
    }
    else{
      Logger.error('setReturnHome command not since invalid coordinates were passed in. Coordinates: '+coordinates);
    }
  },
  appendWaypoint: function(coordinates, radius){
    var coords=Coordinates(coordinates);
    if(coords && coords.alt && Validator.isValidNumber(radius)){
      this.sendCommand('new_waypoint',coords.lat, coords.lng, coords.alt, radius);
    }
    else{
      Logger.error('appendWaypoint command not since invalid coordinates were passed in. Coordinates: '+coordinates);
    }
  },
  insertWaypoint: function(index,coordinates, radius){
    var coords=Coordinates(coordinates);
    if(Validator.isInteger(index) && coords && coords.alt && Validator.isValidNumber(radius)){
      this.sendCommand('insert_Waypoint',coords.lat, coords.lng, coords.alt, radius, index-1, index+1);
    }
    else{
      Logger.error('insertWaypoint command not since invalid waypoint number or coordinates were passed in. Index: '+index);
    }
  }
};
module.exports=Commands;<|endoftext|>


<commit_before>
const GameEvent = {
	Invalid: 0,

	StartGame: 1,
	StartPhase: 2,
	ProceedPhase: 3,
	EndPhase: 4,
};

module.exports = GameEvent;
<commit_msg>Add EndGame event<commit_after>
const GameEvent = {
	Invalid: 0,

	StartGame: 1,
	EndGame: 2,

	StartPhase: 3,
	ProceedPhase: 4,
	EndPhase: 5,
};

module.exports = GameEvent;
<|endoftext|>


<commit_before>'use strict';

(() => {
  function parseURL (text) {
    const xml = new window.DOMParser().parseFromString(text, 'text/xml')
    const tag = xml.getElementsByTagName('Key')[0]
    return decodeURI(tag.childNodes[0].nodeValue)
  }

  function addHiddenInput (body, name, form) {
    const key = parseURL(body)
    const input = document.createElement('input')
    input.type = 'hidden'
    input.value = key
    input.name = name
    form.appendChild(input)
  }

  function request (method, url, data) {
    return new Promise((resolve, reject) => {
      const xhr = new window.XMLHttpRequest()
      xhr.open(method, url)
      xhr.onload = () => {
        if (xhr.status === 201) {
          resolve(xhr.responseText)
        } else {
          reject(xhr.statusText)
        }
      }
      xhr.onerror = () => {
        reject(xhr.statusText)
      }
      xhr.send(data)
    })
  }

  function uploadFiles (e, fileInput, name) {
    const url = fileInput.getAttribute('data-url')
    const form = e.target
    const promises = Array.from(fileInput.files).map((file) => {
      const s3Form = new window.FormData()
      Array.from(fileInput.attributes).forEach(attr => {
        let name = attr.name
        if (name.startsWith('data-fields')) {
          name = name.replace('data-fields-', '')
          s3Form.append(name, attr.value)
        }
      })
      s3Form.append('success_action_status', '201')
      s3Form.append('Content-Type', file.type)
      s3Form.append('file', file)
      return request('POST', url, s3Form)
    })
    Promise.all(promises).then((results) => {
      results.forEach((result) => {
        addHiddenInput(result, name, form)
      })

      const input = document.createElement('input')
      input.type = 'hidden'
      input.name = 's3file'
      input.value = fileInput.name
      form.appendChild(input)
      fileInput.name = ''
      form.submit()
    }, (err) => {
      console.log(err)
      fileInput.setCustomValidity(err)
      fileInput.reportValidity()
    })
  }

  function addHandlers (fileInput) {
    const form = fileInput.closest('form')
    form.addEventListener('submit', (e) => {
      uploadFiles(e, fileInput, fileInput.name)
      e.preventDefault()
    }, false)
  }

  document.addEventListener('DOMContentLoaded', () => {
    [].forEach.call(document.querySelectorAll('.s3file'), addHandlers)
  })

  document.addEventListener('DOMNodeInserted', (e) => {
    if (e.target.tagName) {
      const el = e.target.querySelector('.s3file')
      if (el) addHandlers(el)
    }
  })
})()
<commit_msg>Fix multi file support<commit_after>'use strict';

(() => {
  function parseURL (text) {
    const xml = new window.DOMParser().parseFromString(text, 'text/xml')
    const tag = xml.getElementsByTagName('Key')[0]
    return decodeURI(tag.childNodes[0].nodeValue)
  }

  function addHiddenInput (body, name, form) {
    const key = parseURL(body)
    const input = document.createElement('input')
    input.type = 'hidden'
    input.value = key
    input.name = name
    form.appendChild(input)
  }

  function waitForAllFiles(form) {
    if (window.uploading !== 0) {
      setTimeout(() => {
        waitForAllFiles(form)
      }, 100)
    } else {
      form.submit()
    }
  }

  function request (method, url, data) {
    return new Promise((resolve, reject) => {
      const xhr = new window.XMLHttpRequest()
      xhr.open(method, url)
      xhr.onload = () => {
        if (xhr.status === 201) {
          resolve(xhr.responseText)
        } else {
          reject(xhr.statusText)
        }
      }
      xhr.onerror = () => {
        reject(xhr.statusText)
      }
      xhr.send(data)
    })
  }

  function uploadFiles (form, fileInput, name) {
    const url = fileInput.getAttribute('data-url')
    const promises = Array.from(fileInput.files).map((file) => {
      const s3Form = new window.FormData()
      Array.from(fileInput.attributes).forEach(attr => {
        let name = attr.name
        if (name.startsWith('data-fields')) {
          name = name.replace('data-fields-', '')
          s3Form.append(name, attr.value)
        }
      })
      s3Form.append('success_action_status', '201')
      s3Form.append('Content-Type', file.type)
      s3Form.append('file', file)
      return request('POST', url, s3Form)
    })
    Promise.all(promises).then((results) => {
      results.forEach((result) => {
        addHiddenInput(result, name, form)
      })

      const input = document.createElement('input')
      input.type = 'hidden'
      input.name = 's3file'
      input.value = fileInput.name
      fileInput.name = ''
      form.appendChild(input)
      window.uploading -= 1
    }, (err) => {
      console.log(err)
      fileInput.setCustomValidity(err)
      fileInput.reportValidity()
    })

  }

  document.addEventListener('DOMContentLoaded', () => {
    let forms = Array.from(document.querySelectorAll('.s3file')).map(input => {
      return input.closest('form')
    })
    forms = new Set(forms)
    forms.forEach(form => {
      form.onsubmit = (e) => {
        e.preventDefault()
        window.uploading = 0
        const inputs = document.querySelectorAll('.s3file')
        Array.from(inputs).forEach(input => {
            window.uploading += 1
            uploadFiles(form, input, input.name)
          }
        )
        waitForAllFiles(form)
      }
    })
  })

})()
<|endoftext|>


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

// Connect the IR module to port a
var hardware = tessel.port('a');

// Import library and connect to module
var infrared = require('../index').connect(hardware);

// When we're connected
infrared.on('connected', function(err) {
	if (!err) {
		console.log("Connected to IR!");

		// Start turning tv on and off every 3 seconds
		setInterval(powerTV, 3000);
	}
})

// If we get data, print it out
infrared.on('data', function(data) {
	console.log("Received RX Data: ", data);
});

var powerTV = function() {

	// Make a buffer off on/off durations (each duration is 16 bits)
	var powerBuffer = new Buffer([0, 178, 255, 168, 0, 12, 255, 246, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 224, 0, 13, 255, 224, 0, 12, 255, 224, 0, 12, 255, 224, 0, 12]);

	// Send the signal at 38 kHz
	infrared.sendRawSignal(38, powerBuffer, function(err) {
		if (err) console.log("Unable to send signal: ", err);
		else {
			console.log("TV Should be powered...");
		}
	})
}
<commit_msg>added semicolons<commit_after>var tessel = require('tessel');

// Connect the IR module to port a
var hardware = tessel.port('a');

// Import library and connect to module
var infrared = require('../index').connect(hardware);

// When we're connected
infrared.on('connected', function(err) {
	if (!err) {
		console.log("Connected to IR!");

		// Start turning tv on and off every 3 seconds
		setInterval(powerTV, 3000);
	}
});

// If we get data, print it out
infrared.on('data', function(data) {
	console.log("Received RX Data: ", data);
});

var powerTV = function() {

	// Make a buffer off on/off durations (each duration is 16 bits)
	var powerBuffer = new Buffer([0, 178, 255, 168, 0, 12, 255, 246, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 224, 0, 13, 255, 224, 0, 12, 255, 224, 0, 12, 255, 224, 0, 12]);

	// Send the signal at 38 kHz
	infrared.sendRawSignal(38, powerBuffer, function(err) {
		if (err) console.log("Unable to send signal: ", err);
		else {
			console.log("TV Should be powered...");
		}
	});
}
<|endoftext|>


<commit_before>"use strict";

var a = 1;
let b = 1;

console.log("after global declaration", a, b);

function asdf() {
  var a = 2;
  let b = 2;
  console.log("in method asdf", a, b);
}

console.log("after function declaration", a, b);

asdf();

console.log("after function call", a, b)

if(true) {
  var a = 3;
  let b = 3;
  console.log("in if block", a, b);
}

console.log("after if block", a, b);
<commit_msg>extend javascript sample with let and var in loops<commit_after>"use strict";

var a = 1;
let b = 1;

console.log("after global declaration", a, b);

function asdf() {
  var a = 2;
  let b = 2;
  console.log("in method asdf", a, b);
}

console.log("after function declaration", a, b);

asdf();

console.log("after function call", a, b)

if(true) {
  var a = 3;
  let b = 3;
  console.log("in if block", a, b);
}

console.log("after if block", a, b);

console.log("---");

var items = [1,2,3,4]
for (var i = 0; i < items.length; i++) {
  setTimeout(function () {
    console.log("logging item with index %d using var, %s: %s", i, items, items[i]);
  }, 10);
}

// the same sample with let

for (let i = 0; i < items.length; i++) {
  setTimeout(function () {
    console.log("logging item with index %d using let, %s: %s", i, items, items[i]);
  }, 10);
}
<|endoftext|>


<commit_before>$(function() {
  // our document model - stores the datastructure generated from docurium
  var Docurium = Backbone.Model.extend({

    defaults: {'version': 'unknown'},

    initialize: function() {
      this.loadVersions()
    },

    loadVersions: function() {
      $.get("project.json", function(data) {
        docurium.set({'version': 'HEAD', 'versions': data.versions, 'github': data.github})
        docurium.loadDoc()
      })
    },

    loadDoc: function() {
      version = this.get('version')
      $.ajax({
        url: version + '.json',
        context: this,
        dataType: 'json',
        success: function(data){
          this.set({'data': data})
          Backbone.history.start()
        }
      })
    },

    collapseSection: function(data) {
      $(this).next().toggle(100)
      return false
    },

    showFun: function(gname, fname) {
      id = '#groupItem' + gname
      ref = parseInt($(id).attr('ref'))

      group = docurium.get('data')['groups'][ref]
      fdata = docurium.get('data')['functions']
      gname = group[0]
      functions = group[1]

      content = $('.content')
      content.empty()

      content.append($('
').addClass('funcTitle').append(fname))
      if(fdata[fname]['description']) {
        sub = content.append($('
').addClass('funcDesc').append( ' ' + fdata[fname]['description'] ))
      }

      argtable = $('
').addClass('funcTable')
      args = fdata[fname]['args']
      for(var i=0; i<args.length; i++) {
        arg = args[i]
        row = $('
')
        row.append($('').attr('valign', 'top').attr('nowrap', true).append(this.hotLink(arg.type)))
        row.append($('').attr('valign', 'top').addClass('var').append(arg.name))
        row.append($('').addClass('comment').append(arg.comment))
        argtable.append(row)
      }
      content.append(argtable)

      retdiv = $('
').addClass('returns')
      retdiv.append($('
').append("returns"))
      rettable = $('
').addClass('funcTable')
      retrow = $('
')
      rettable.append(retrow)
      retdiv.append(rettable)

      ret = fdata[fname]['return']
      retrow.append($('').attr('valign', 'top').append(this.hotLink(ret.type)))
      if(ret.comment) {
        retrow.append($('').addClass('comment').append(ret.comment))
      }
      content.append(retdiv)

      if (fdata[fname]['comments']) {
        content.append($('
').append(fdata[fname]['comments']))
      }

      ex = $('').addClass('params')
      ex.append(this.hotLink(fdata[fname]['return']['type'] + ' ' + fname + '(' + fdata[fname]['argline'] + ');'))
      example = $('
').addClass('example')
      example.append($('
').append("signature"))
      example.append(ex)
      content.append(example)

      also = $('
').addClass('also')

      flink = $('' + group[0] + '')
      flink.click( docurium.showGroup )
      also.append("Also in ")
      also.append(flink)
      also.append(" group:
")

      for(i=0; i<functions.length; i++) {
        f = functions[i]
        d = fdata[f]
        link = $('').attr('href', '#' + groupLink(gname, f)).append(f)
        also.append(link)
        also.append(', ')
      }

      content.append(also)
      link = this.github_file(fdata[fname].file, fdata[fname].line, fdata[fname].lineto)
      flink = $('').attr('target', 'github').attr('href', link).append(fdata[fname].file)
      content.append($('
').addClass('fileLink').append("Defined in: ").append(flink))

      this.addHotlinks()
    },

    showType: function(data, manual) {
      if(manual) {
        id = '#typeItem' + domSafe(manual)
        ref = parseInt($(id).attr('ref'))
      } else {
        ref = parseInt($(this).attr('ref'))
      }
      tdata = docurium.get('data')['types'][ref]
      tname = tdata[0]
      data = tdata[1]

      ws.saveLocation(typeLink(tname))

      content = $('.content')
      content.empty()
      content.append($('
').addClass('funcTitle').append(tname).append($("").append(data.type)))

      content.append($('
').append(data.value))
      if(data.block) {
        content.append($('
').append(data.block))
      }

      var ret = data.used.returns
      if (ret.length > 0) {
        content.append($('
').append('Returns'))
      }
      for(var i=0; i<ret.length; i++) {
        gname = docurium.groupOf(ret[i])
        flink = $('').attr('href', '#' + groupLink(gname, ret[i])).append(ret[i])
        flink.click( docurium.showFun )
        content.append(flink)
        content.append(', ')
      }

      var needs = data.used.needs
      if (needs.length > 0) {
        content.append($('
').append('Argument In'))
      }
      for(var i=0; i<needs.length; i++) {
        gname = docurium.groupOf(needs[i])
        flink = $('').attr('href', '#' + groupLink(gname, needs[i])).append(needs[i])
        flink.click( docurium.showFun )
        content.append(flink)
        content.append(', ')
      }

      link = docurium.github_file(data.file, data.line, data.lineto)
      flink = $('').attr('target', 'github').attr('href', link).append(data.file)
      content.append($('
').addClass('fileLink').append("Defined in: ").append(flink))

      return false
    },

    showGroup: function(data, manual, flink) {
      if(manual) {
        id = '#groupItem' + manual
        ref = parseInt($(id).attr('ref'))
      } else {
        ref = parseInt($(this).attr('ref'))
      }
      group = docurium.get('data')['groups'][ref]
      fdata = docurium.get('data')['functions']
      gname = group[0]

      ws.saveLocation(groupLink(gname));

      functions = group[1]
      $('.content').empty()
      $('.content').append($('
').append(gname + ' functions'))

      table = $('
').addClass('methods')
      for(i=0; i<functions.length; i++) {
        f = functions[i]
        d = fdata[f]
        row = $('
')
        row.append($('').attr('nowrap', true).attr('valign', 'top').append(d['return']['type'].substring(0, 20)))
        link = $('').attr('href', '#' + groupLink(gname, f)).append(f)
        row.append($('').attr('valign', 'top').addClass('methodName').append( link ))
        args = d['args']
        argtd = $('')
        for(j=0; j<args.length; j++) {
          argtd.append(args[j].type + ' ' + args[j].name)
          argtd.append($('
'))
        }
        row.append(argtd)
        table.append(row)
      }
      $('.content').append(table)

      for(var i=0; i<functions.length; i++) {
        f = functions[i]
        argsText = '( ' + fdata[f]['argline'] + ' )'
        link = $('').attr('href', '#' + groupLink(gname, f)).append(f)
        $('.content').append($('
').append(link).append($('').append(argsText)))
        $('.content').append($('
').append(fdata[f]['rawComments']))
      }
      return false
    },

    // look for structs and link them
    hotLink: function(text) {
      types = this.get('data')['types']
      for(var i=0; i<types.length; i++) {
        type = types[i]
        typeName = type[0]
        typeData = type[1]
        re = new RegExp(typeName + ' ', 'gi');
        link = '' + typeName + ' '
        text = text.replace(re, link)
      }
      return text
    },

    groupHash: false,
    groupOf: function (func) {
      if(!this.groupHash) {
        this.groupHash = {}
        data = this.get('data')
        for(var i=0; i<data['groups'].length; i++) {
          group = data['groups'][i][1]
          groupName = data['groups'][i][0]
          for(var j=0; j<group.length; j++) {
            f = group[j]
            this.groupHash[f] = groupName
          }
        }
      }
      return this.groupHash[func]
    },

    addHotlinks: function() {
      types = this.get('data')['types']
      for(var i=0; i<types.length; i++) {
        type = types[i]
        typeName = type[0]
        className = '.typeLink' + domSafe(typeName)
        $(className).click( this.showType )
      }
    },

    refreshView: function() {
      data = this.get('data')

      // Function Groups
      menu = $('
')
      title = $('
Functions
').click( this.collapseSection )
      menu.append(title)
      list = $('
')
      _.each(data['groups'], function(group, i) {
        flink = $('' + group[0] + '  (' + group[1].length + ')')
        flink.click( this.showGroup )
        fitem = $('
')
        fitem.append(flink)
        list.append(fitem)
      }, this)
      menu.append(list)

      // Types
      title = $('
Types
').click( this.collapseSection )
      menu.append(title)
      list = $('
')

      fitem = $('
')
      fitem.append($('').addClass('divide').append("Enums"))
      list.append(fitem)

      _.each(data['types'], function(group, i) {
        if(group[1]['block'] && group[1]['type'] == 'enum') {
          flink = $('' + group[0]  + '')
          flink.click( this.showType )
          fitem = $('
')
          fitem.append(flink)
          list.append(fitem)
        }
      }, this)

      fitem = $('
')
      fitem.append($('').addClass('divide').append("Public Struct"))
      list.append(fitem)

      _.each(data['types'], function(group, i) {
        if(group[1]['block'] && group[1]['type'] != 'enum') {
          flink = $('' + group[0]  + '')
          flink.click( this.showType )
          fitem = $('
')
          fitem.append(flink)
          list.append(fitem)
        }
      }, this)

      fitem = $('
')
      fitem.append($('').addClass('divide').append("Private Struct"))
      list.append(fitem)

      _.each(data['types'], function(group, i) {
        if(!group[1]['block']) {
          flink = $('' + group[0]  + '')
          flink.click( this.showType )
          fitem = $('
')
          fitem.append(flink)
          list.append(fitem)
        }
      }, this)
      list.hide()
      menu.append(list)

      // File Listing
      title = $('
Files
').click( this.collapseSection )
      menu.append(title)
      filelist = $('
')
      _.each(data['files'], function(file) {
        url = this.github_file(file['file'])
        flink = $('' + file['file'] + '')
        fitem = $('
')
        fitem.append(flink)
        filelist.append(fitem)
      }, this)
      filelist.hide()
      menu.append(filelist)

      list = $('#files-list')
      list.empty()
      list.append(menu)
    },

    github_file: function(file, line, lineto) {
      url = "https://github.com/" + this.get('github')
      url += "/blob/" + this.get('version') + '/' + data.prefix + '/' + file
      if(line) {
        url += '#L' + line.toString()
        if(lineto) {
          url += '-' + lineto.toString()
        }
      } else {
        url += '#files'
      }
      return url
    }

  })

  var Workspace = Backbone.Controller.extend({

    routes: {
      ":version/group/:group":        "group",
      ":version/type/:type":          "showtype",
      ":version/group/:group/:func":  "groupFun",
      ":version/search/:query":       "search",
    },

    group: function(version, gname) {
      docurium.showGroup(null, gname)
    },

    groupFun: function(version, gname, fname) {
      docurium.showFun(gname, fname)
    },

    showtype: function(version, tname) {
      docurium.showType(null, tname)
    },

    search: function(version, query) {
    },

  });

  function groupLink(gname, fname) {
    if(fname) {
      return docurium.get('version') + "/group/" + gname + '/' + fname
    } else {
      return docurium.get('version') + "/group/" + gname
    }
  }

  function typeLink(tname) {
    return docurium.get('version') + "/type/" + tname
  }

  function domSafe(str) {
    return str.replace('_', '-')
  }

  window.docurium = new Docurium
  window.ws = new Workspace

  docurium.bind('change:version', function(model, version) {
    $('#version').text(version)
  })
  docurium.bind('change:data', function(model, data) {
    model.refreshView()
  })

})
<commit_msg>basic function searching - through name and argline<commit_after>$(function() {
  // our document model - stores the datastructure generated from docurium
  var Docurium = Backbone.Model.extend({

    defaults: {'version': 'unknown'},

    initialize: function() {
      this.loadVersions()
    },

    loadVersions: function() {
      $.get("project.json", function(data) {
        docurium.set({'version': 'HEAD', 'versions': data.versions, 'github': data.github})
        docurium.loadDoc()
      })
    },

    loadDoc: function() {
      version = this.get('version')
      $.ajax({
        url: version + '.json',
        context: this,
        dataType: 'json',
        success: function(data){
          this.set({'data': data})
          Backbone.history.start()
        }
      })
    },

    collapseSection: function(data) {
      $(this).next().toggle(100)
      return false
    },

    showFun: function(gname, fname) {
      id = '#groupItem' + gname
      ref = parseInt($(id).attr('ref'))

      group = docurium.get('data')['groups'][ref]
      fdata = docurium.get('data')['functions']
      gname = group[0]
      functions = group[1]

      content = $('.content')
      content.empty()

      content.append($('
').addClass('funcTitle').append(fname))
      if(fdata[fname]['description']) {
        sub = content.append($('
').addClass('funcDesc').append( ' ' + fdata[fname]['description'] ))
      }

      argtable = $('
').addClass('funcTable')
      args = fdata[fname]['args']
      for(var i=0; i<args.length; i++) {
        arg = args[i]
        row = $('
')
        row.append($('').attr('valign', 'top').attr('nowrap', true).append(this.hotLink(arg.type)))
        row.append($('').attr('valign', 'top').addClass('var').append(arg.name))
        row.append($('').addClass('comment').append(arg.comment))
        argtable.append(row)
      }
      content.append(argtable)

      retdiv = $('
').addClass('returns')
      retdiv.append($('
').append("returns"))
      rettable = $('
').addClass('funcTable')
      retrow = $('
')
      rettable.append(retrow)
      retdiv.append(rettable)

      ret = fdata[fname]['return']
      retrow.append($('').attr('valign', 'top').append(this.hotLink(ret.type)))
      if(ret.comment) {
        retrow.append($('').addClass('comment').append(ret.comment))
      }
      content.append(retdiv)

      if (fdata[fname]['comments']) {
        content.append($('
').append(fdata[fname]['comments']))
      }

      ex = $('').addClass('params')
      ex.append(this.hotLink(fdata[fname]['return']['type'] + ' ' + fname + '(' + fdata[fname]['argline'] + ');'))
      example = $('
').addClass('example')
      example.append($('
').append("signature"))
      example.append(ex)
      content.append(example)

      also = $('
').addClass('also')

      flink = $('' + group[0] + '')
      flink.click( docurium.showGroup )
      also.append("Also in ")
      also.append(flink)
      also.append(" group:
")

      for(i=0; i<functions.length; i++) {
        f = functions[i]
        d = fdata[f]
        link = $('').attr('href', '#' + groupLink(gname, f)).append(f)
        also.append(link)
        also.append(', ')
      }

      content.append(also)
      link = this.github_file(fdata[fname].file, fdata[fname].line, fdata[fname].lineto)
      flink = $('').attr('target', 'github').attr('href', link).append(fdata[fname].file)
      content.append($('
').addClass('fileLink').append("Defined in: ").append(flink))

      this.addHotlinks()
    },

    showType: function(data, manual) {
      if(manual) {
        id = '#typeItem' + domSafe(manual)
        ref = parseInt($(id).attr('ref'))
      } else {
        ref = parseInt($(this).attr('ref'))
      }
      tdata = docurium.get('data')['types'][ref]
      tname = tdata[0]
      data = tdata[1]

      ws.saveLocation(typeLink(tname))

      content = $('.content')
      content.empty()
      content.append($('
').addClass('funcTitle').append(tname).append($("").append(data.type)))

      content.append($('
').append(data.value))
      if(data.block) {
        content.append($('
').append(data.block))
      }

      var ret = data.used.returns
      if (ret.length > 0) {
        content.append($('
').append('Returns'))
      }
      for(var i=0; i<ret.length; i++) {
        gname = docurium.groupOf(ret[i])
        flink = $('').attr('href', '#' + groupLink(gname, ret[i])).append(ret[i])
        flink.click( docurium.showFun )
        content.append(flink)
        content.append(', ')
      }

      var needs = data.used.needs
      if (needs.length > 0) {
        content.append($('
').append('Argument In'))
      }
      for(var i=0; i<needs.length; i++) {
        gname = docurium.groupOf(needs[i])
        flink = $('').attr('href', '#' + groupLink(gname, needs[i])).append(needs[i])
        flink.click( docurium.showFun )
        content.append(flink)
        content.append(', ')
      }

      link = docurium.github_file(data.file, data.line, data.lineto)
      flink = $('').attr('target', 'github').attr('href', link).append(data.file)
      content.append($('
').addClass('fileLink').append("Defined in: ").append(flink))

      return false
    },

    showGroup: function(data, manual, flink) {
      if(manual) {
        id = '#groupItem' + manual
        ref = parseInt($(id).attr('ref'))
      } else {
        ref = parseInt($(this).attr('ref'))
      }
      group = docurium.get('data')['groups'][ref]
      fdata = docurium.get('data')['functions']
      gname = group[0]

      ws.saveLocation(groupLink(gname));

      functions = group[1]
      $('.content').empty()
      $('.content').append($('
').append(gname + ' functions'))

      table = $('
').addClass('methods')
      for(i=0; i<functions.length; i++) {
        f = functions[i]
        d = fdata[f]
        row = $('
')
        row.append($('').attr('nowrap', true).attr('valign', 'top').append(d['return']['type'].substring(0, 20)))
        link = $('').attr('href', '#' + groupLink(gname, f)).append(f)
        row.append($('').attr('valign', 'top').addClass('methodName').append( link ))
        args = d['args']
        argtd = $('')
        for(j=0; j<args.length; j++) {
          argtd.append(args[j].type + ' ' + args[j].name)
          argtd.append($('
'))
        }
        row.append(argtd)
        table.append(row)
      }
      $('.content').append(table)

      for(var i=0; i<functions.length; i++) {
        f = functions[i]
        argsText = '( ' + fdata[f]['argline'] + ' )'
        link = $('').attr('href', '#' + groupLink(gname, f)).append(f)
        $('.content').append($('
').append(link).append($('').append(argsText)))
        $('.content').append($('
').append(fdata[f]['rawComments']))
      }
      return false
    },

    // look for structs and link them
    hotLink: function(text) {
      types = this.get('data')['types']
      for(var i=0; i<types.length; i++) {
        type = types[i]
        typeName = type[0]
        typeData = type[1]
        re = new RegExp(typeName + ' ', 'gi');
        link = '' + typeName + ' '
        text = text.replace(re, link)
      }
      return text
    },

    groupHash: false,
    groupOf: function (func) {
      if(!this.groupHash) {
        this.groupHash = {}
        data = this.get('data')
        for(var i=0; i<data['groups'].length; i++) {
          group = data['groups'][i][1]
          groupName = data['groups'][i][0]
          for(var j=0; j<group.length; j++) {
            f = group[j]
            this.groupHash[f] = groupName
          }
        }
      }
      return this.groupHash[func]
    },

    addHotlinks: function() {
      types = this.get('data')['types']
      for(var i=0; i<types.length; i++) {
        type = types[i]
        typeName = type[0]
        className = '.typeLink' + domSafe(typeName)
        $(className).click( this.showType )
      }
    },

    refreshView: function() {
      data = this.get('data')

      // Function Groups
      menu = $('
')
      title = $('
Functions
').click( this.collapseSection )
      menu.append(title)
      list = $('
')
      _.each(data['groups'], function(group, i) {
        flink = $('' + group[0] + '  (' + group[1].length + ')')
        flink.click( this.showGroup )
        fitem = $('
')
        fitem.append(flink)
        list.append(fitem)
      }, this)
      menu.append(list)

      // Types
      title = $('
Types
').click( this.collapseSection )
      menu.append(title)
      list = $('
')

      fitem = $('
')
      fitem.append($('').addClass('divide').append("Enums"))
      list.append(fitem)

      _.each(data['types'], function(group, i) {
        if(group[1]['block'] && group[1]['type'] == 'enum') {
          flink = $('' + group[0]  + '')
          flink.click( this.showType )
          fitem = $('
')
          fitem.append(flink)
          list.append(fitem)
        }
      }, this)

      fitem = $('
')
      fitem.append($('').addClass('divide').append("Public Struct"))
      list.append(fitem)

      _.each(data['types'], function(group, i) {
        if(group[1]['block'] && group[1]['type'] != 'enum') {
          flink = $('' + group[0]  + '')
          flink.click( this.showType )
          fitem = $('
')
          fitem.append(flink)
          list.append(fitem)
        }
      }, this)

      fitem = $('
')
      fitem.append($('').addClass('divide').append("Private Struct"))
      list.append(fitem)

      _.each(data['types'], function(group, i) {
        if(!group[1]['block']) {
          flink = $('' + group[0]  + '')
          flink.click( this.showType )
          fitem = $('
')
          fitem.append(flink)
          list.append(fitem)
        }
      }, this)
      list.hide()
      menu.append(list)

      // File Listing
      title = $('
Files
').click( this.collapseSection )
      menu.append(title)
      filelist = $('
')
      _.each(data['files'], function(file) {
        url = this.github_file(file['file'])
        flink = $('' + file['file'] + '')
        fitem = $('
')
        fitem.append(flink)
        filelist.append(fitem)
      }, this)
      filelist.hide()
      menu.append(filelist)

      list = $('#files-list')
      list.empty()
      list.append(menu)
    },

    github_file: function(file, line, lineto) {
      url = "https://github.com/" + this.get('github')
      url += "/blob/" + this.get('version') + '/' + data.prefix + '/' + file
      if(line) {
        url += '#L' + line.toString()
        if(lineto) {
          url += '-' + lineto.toString()
        }
      } else {
        url += '#files'
      }
      return url
    },

    search: function(data) {
      var searchResults = []
      var value = $('#search-field').attr('value')
      if (value.length < 3) {
        return false
      }
      this.searchResults = []

      ws.saveLocation(searchLink(value))

      data = docurium.get('data')

      // look for functions (name, comment, argline)
      for (var name in data.functions) {
        f = data.functions[name]
        if (name.search(value) > -1) {
          gname = docurium.groupOf(name)
          var flink = $('').attr('href', '#' + groupLink(gname, name)).append(name)
          searchResults.push(['fun-' + name, flink])
        }
        if (f.argline) {
          if (f.argline.search(value) > -1) {
            gname = docurium.groupOf(name)
            var flink = $('').attr('href', '#' + groupLink(gname, name)).append(name)
            searchResults.push(['fun-' + name, flink, f.argline])
          }
        }
      }

      // look for types
      // look for files
      content = $('.content')
      content.empty()

      content.append($('
').append("Search Results"))
      table = $("
")
      var shown = {}
      for (var i in searchResults) {
        row = $("
")
        result = searchResults[i]
        if (!shown[result[0]]) {
          link = result[1]
          match = result[2]
          row.append($('').append(link))
          row.append($('').append(match))
          table.append(row)
          shown[result[0]] = true
        }
      }
      content.append(table)

    }

  })

  var Workspace = Backbone.Controller.extend({

    routes: {
      ":version/group/:group":        "group",
      ":version/type/:type":          "showtype",
      ":version/group/:group/:func":  "groupFun",
      ":version/search/:query":       "search",
    },

    group: function(version, gname) {
      docurium.showGroup(null, gname)
    },

    groupFun: function(version, gname, fname) {
      docurium.showFun(gname, fname)
    },

    showtype: function(version, tname) {
      docurium.showType(null, tname)
    },

    search: function(version, query) {
      $('#search-field').attr('value', query)
      docurium.search()
    },

  });

  function groupLink(gname, fname) {
    if(fname) {
      return docurium.get('version') + "/group/" + gname + '/' + fname
    } else {
      return docurium.get('version') + "/group/" + gname
    }
  }

  function typeLink(tname) {
    return docurium.get('version') + "/type/" + tname
  }

  function searchLink(tname) {
    return docurium.get('version') + "/search/" + tname
  }

  function domSafe(str) {
    return str.replace('_', '-')
  }

  window.docurium = new Docurium
  window.ws = new Workspace

  docurium.bind('change:version', function(model, version) {
    $('#version').text(version)
  })
  docurium.bind('change:data', function(model, data) {
    model.refreshView()
  })

  $('#search-field').keyup( docurium.search )

})
<|endoftext|>


<commit_before>import DS from 'ember-data';

export default DS.Model.extend({
  posse_id: DS.attr('string'),
  problem_id: DS.attr('string'),
  content: DS.attr('string'),
  points_earned: DS.attr('string')
});
<commit_msg>solutions have posse names<commit_after>import DS from 'ember-data';

export default DS.Model.extend({
  posse_id: DS.attr('string'),
  problem_id: DS.attr('string'),
  content: DS.attr('string'),
  points_earned: DS.attr('string'),
  posse: DS.attr('string')
});
<|endoftext|>