<commit_before>//función que se ejecuta al cargar la pagina
$(function(){
    //-- Declarar variables =============================== //
    var orden_documento = $("#orden-documento");
    var orden_nombre = $("#orden-nombre");
    var orden_aseguradora = $("#orden-aseguradora");
    var orden_contrato = $("#orden-contrato");
    var orden_servicios_cups = $("#orden_servicios_cups");
    var orden_servicios_descripcion = $("#orden_servicios_descripcion");
    var orden_servicios_cantidad = $("#orden_servicios_cantidad");
    var orden_servicios_copago = $("#orden_servicios_copago");
    var orden_servicios_valor_unitario = $("#orden_servicios_valor_unitario");
    var orden_servicios_valor_total = $("#orden_servicios_valor_total");
    var temporizador_documento = 0;
    var temporizador_cups = 0;
    var orden_servicios_añadir = $("#orden_servicios_añadir");
    var orden_servicios_eliminar = $("#orden_servicios_eliminar");
    var orden_servicios_servicios = $("#orden_servicios_servicios");
    const orden_servicios_servicios_campos = $('
<input type="text" name="cups" id="orden_servicios_cups" class="form-control" >	<input type="text" name="descripcion" readonly id="orden_servicios_descripcion" class="form-control" >	<input type="number" name="cantidad" id="orden_servicios_cantidad" class="form-control" >	<input type="number" step="0.01" name="copago" id="orden_servicios_copago" class="form-control" >	<input type="number" step="0.01" name="valor_unitario" id="orden_servicios_valor_unitario" class="form-control" >	<input type="number" step="0.01" name="valor_total" readonly id="orden_servicios_valor_total" class="form-control" >
');

    //-- Fin de declarar variables ======================= //

    //-- Agregar eventos ================================= //
    orden_documento.on("keyup",function(){
        clearInterval(temporizador_documento)
        temporizador_documento = setTimeout(buscarPaciente,1000);

    });
    //-- Agregar eventos cups ================================= //
    orden_servicios_cups.on("keyup",function(){
        clearInterval(temporizador_cups)
        temporizador_cups = setTimeout(buscarCups,1000);
    });

    orden_servicios_cantidad.on("keyup",function(){
     valorTotal();
    });
    orden_servicios_copago.on("keyup",function(){
     valorTotal();
    });
    orden_servicios_valor_unitario.on("keyup",function(){
     valorTotal();
    });

    orden_servicios_añadir.on("click",function () {
        servicios = orden_servicios_servicios.html();
        orden_servicios_servicios.html(servicios);
        var trs=$("#orden_servicios_servicios tr").length;
        console.log(trs);
        $('#orden_servicios_servicios tr:last').after(orden_servicios_servicios_campos);
        //orden_servicios_servicios.append(orden_servicios_servicios_campos);
    });

    orden_servicios_eliminar.on("click",function () {
        // Obtenemos el total de columnas (tr) del id "tabla"
        var trs=$("#orden_servicios_servicios tr").length;
        if(trs>1)
        {
            // Eliminamos la ultima columna
            $("#orden_servicios_servicios tr:last").remove();
        }
    });

    //-- declarar funciones auxiliares------------------------------------//

    function valorTotal(){
        var cantidad= parseInt(orden_servicios_cantidad.val());
        var valor_unitario = parseFloat(orden_servicios_valor_unitario.val());
        var copago = parseFloat(orden_servicios_copago.val());
        var valor_total = 0;
        if(Number.isNaN(cantidad)){
        cantidad = 0;
        }
         if(Number.isNaN(copago)){
        copago = 0;
        }
         if(Number.isNaN(valor_unitario)){
        valor_unitario= 0;
        }

        valor_total=(valor_unitario * cantidad) - copago;

        orden_servicios_valor_total.val(valor_total.toFixed(2));
    }

    function buscarPaciente(){
        var url = "/pacientes/documento/"+orden_documento.val();
        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            success: function(respuesta){
                if(respuesta.success){
                    orden_nombre.val(respuesta.paciente.nombre);
                    orden_contrato.val(respuesta.paciente.contrato);
                    var aseguradora_id = respuesta.paciente.aseguradora_id;
                    var url= "/Aseguradora/"+respuesta.paciente.aseguradora_id;
                    $.ajax({
                        url: url,
                        type: "GET",
                        dataType: "json",
                        success: function(respuesta){
                            if(respuesta.success){
                                orden_aseguradora.html("<option value='"+aseguradora_id+"'>"+respuesta.aseguradora.nombre+"</option>");
                                // orden_aseguradora.html(respuesta.aseguradora.nombre);

                            }else{
                                orden_aseguradora.html("<option value=''></option>");
                            }
                        },error: function(e){
                            console.log(e);
                        }
                    });

                }else{
                    orden_nombre.val("");
                    orden_aseguradora.html("<option value=''></option>");
                    orden_contrato.val("");
                }
            },error: function(e){
                orden_nombre.val("");
                orden_aseguradora.html("<option value=''></option>");
                orden_contrato.val("");
            }
        });
    }

    function buscarCups(){
        var url = "/servicios/cups/"+orden_servicios_cups.val();
        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            success: function(respuesta){
                if(respuesta.success){
                    orden_servicios_descripcion.val(respuesta.servicio.descripcion);
                }
                else{
                    orden_servicios_descripcion.val("");
                }
            },error: function(e){
                orden_servicios_descripcion.val("");
            }
        });
    }

});<commit_msg>nada añadido<commit_after>//función que se ejecuta al cargar la pagina
$(function(){
    //-- Declarar variables =============================== //
    var orden_documento = $("#orden-documento");
    var orden_nombre = $("#orden-nombre");
    var orden_aseguradora = $("#orden-aseguradora");
    var orden_contrato = $("#orden-contrato");
    var orden_servicios_cups = $("#orden_servicios_cups");
    var orden_servicios_descripcion = $("#orden_servicios_descripcion");
    var orden_servicios_cantidad = $("#orden_servicios_cantidad");
    var orden_servicios_copago = $("#orden_servicios_copago");
    var orden_servicios_valor_unitario = $("#orden_servicios_valor_unitario");
    var orden_servicios_valor_total = $("#orden_servicios_valor_total");
    var temporizador_documento = 0;
    var temporizador_cups = 0;
    var orden_servicios_añadir = $("#orden_servicios_añadir");
    var orden_servicios_eliminar = $("#orden_servicios_eliminar");
    var orden_servicios_servicios = $("#orden_servicios_servicios");
    const orden_servicios_servicios_campos = $('
<input type="text" name="cups" id="orden_servicios_cups" class="form-control" >	<input type="text" name="descripcion" readonly id="orden_servicios_descripcion" class="form-control" >	<input type="number" name="cantidad" id="orden_servicios_cantidad" class="form-control" >	<input type="number" step="0.01" name="copago" id="orden_servicios_copago" class="form-control" >	<input type="number" step="0.01" name="valor_unitario" id="orden_servicios_valor_unitario" class="form-control" >	<input type="number" step="0.01" name="valor_total" readonly id="orden_servicios_valor_total" class="form-control" >
');

    //-- Fin de declarar variables ======================= //

    //-- Agregar eventos ================================= //
    orden_documento.on("keyup",function(){
        clearInterval(temporizador_documento)
        temporizador_documento = setTimeout(buscarPaciente,1000);

    });
    //-- Agregar eventos cups ================================= //
    orden_servicios_cups.on("keyup",function(){
        clearInterval(temporizador_cups)
        temporizador_cups = setTimeout(buscarCups,1000);
    });

    orden_servicios_cantidad.on("keyup",function(){
     valorTotal();
    });
    orden_servicios_copago.on("keyup",function(){
     valorTotal();
    });
    orden_servicios_valor_unitario.on("keyup",function(){
     valorTotal();
    });

    orden_servicios_añadir.on("click",function () {
        guardarValorAnterior();
        servicios = orden_servicios_servicios.html();
        orden_servicios_servicios.html(servicios);
        var trs=$("#orden_servicios_servicios tr").length;
        console.log(trs);
        $('#orden_servicios_servicios tr:last').after(orden_servicios_servicios_campos);
        //orden_servicios_servicios.append(orden_servicios_servicios_campos);
    });

    orden_servicios_eliminar.on("click",function () {
        // Obtenemos el total de columnas (tr) del id "tabla"
        var trs=$("#orden_servicios_servicios tr").length;
        if(trs>1)
        {
            // Eliminamos la ultima columna
            $("#orden_servicios_servicios tr:last").remove();
        }
    });

    //-- declarar funciones auxiliares------------------------------------//

    function valorTotal(){
        var cantidad= parseInt(orden_servicios_cantidad.val());
        var valor_unitario = parseFloat(orden_servicios_valor_unitario.val());
        var copago = parseFloat(orden_servicios_copago.val());
        var valor_total = 0;
        if(Number.isNaN(cantidad)){
        cantidad = 0;
        }
         if(Number.isNaN(copago)){
        copago = 0;
        }
         if(Number.isNaN(valor_unitario)){
        valor_unitario= 0;
        }

        valor_total=(valor_unitario * cantidad) - copago;

        orden_servicios_valor_total.val(valor_total.toFixed(2));
    }

    function buscarPaciente(){
        var url = "/pacientes/documento/"+orden_documento.val();
        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            success: function(respuesta){
                if(respuesta.success){
                    orden_nombre.val(respuesta.paciente.nombre);
                    orden_contrato.val(respuesta.paciente.contrato);
                    var aseguradora_id = respuesta.paciente.aseguradora_id;
                    var url= "/Aseguradora/"+respuesta.paciente.aseguradora_id;
                    $.ajax({
                        url: url,
                        type: "GET",
                        dataType: "json",
                        success: function(respuesta){
                            if(respuesta.success){
                                orden_aseguradora.html("<option value='"+aseguradora_id+"'>"+respuesta.aseguradora.nombre+"</option>");
                                // orden_aseguradora.html(respuesta.aseguradora.nombre);

                            }else{
                                orden_aseguradora.html("<option value=''></option>");
                            }
                        },error: function(e){
                            console.log(e);
                        }
                    });

                }else{
                    orden_nombre.val("");
                    orden_aseguradora.html("<option value=''></option>");
                    orden_contrato.val("");
                }
            },error: function(e){
                orden_nombre.val("");
                orden_aseguradora.html("<option value=''></option>");
                orden_contrato.val("");
            }
        });
    }

    function buscarCups(){
        var url = "/servicios/cups/"+orden_servicios_cups.val();
        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            success: function(respuesta){
                if(respuesta.success){
                    orden_servicios_descripcion.val(respuesta.servicio.descripcion);
                }
                else{
                    orden_servicios_descripcion.val("");
                }
            },error: function(e){
                orden_servicios_descripcion.val("");
            }
        });
    }

});<|endoftext|>


<commit_before>/**
 * ajaxPaginator es un plugin que permite hacer paginación vía Ajax.
 * Copyright Javi <elretirao@elretirao.net>
 * Ver http://docs.jquery.com/License para la licencia.
 *
 * Opciones:
 * paginador: string con el elemento que tiene los enlaces de paginación.
 *				Por defecto, '#paginador'.
 * table:	string con el elemento que tiene los datos. Por defecto, 'table'.
 * image: la imagen a mostrar mientras se ejecuta la operación.
 */

jQuery.fn.ajaxPaginator = function( options )
{
  var defaults =
  {
    paginator: '#paginador',
    table: 'table',
    beforeSend: function()
    {
      $('#flashMessage').remove();
    },
    cargando: 'Cargando...',
    history: true
  };

  jQuery.extend( defaults, options );

  return this.each( function()
  {
    var $element = jQuery(this);
    defaults['success'] = function(data) { $element.html(data); }

    if(defaults.history)
    {
      $.history.init(function(hash)
      {
        if(hash != '')
        {
          load_page($element, hash, defaults)
        }
      })
    }

    jQuery(defaults.paginator + ' a,' + defaults.table + ' th a', $element).live('click', function()
    {
      var url = jQuery(this).attr("href");
      if(defaults.history)
      {
        $.history.load(url);
      }
      else
      {
        load_page($element, url, defaults);
      }
      return false;
    });
  });
}

function load_page(element, url, options)
{
  options['url'] = url;
  element.empty().html('
' + options.cargando + '
');
  $.ajax(options);
}<commit_msg>Aprovechamos la nueva funcionalidad de los navegadores para cambiar la URL completa por javascript en el paginador AJAX.<commit_after>/**
 * ajaxPaginator es un plugin que permite hacer paginación vía Ajax.
 * Copyright Javi <elretirao@elretirao.net>
 * Ver http://docs.jquery.com/License para la licencia.
 *
 * Opciones:
 * paginador: string con el elemento que tiene los enlaces de paginación.
 *				Por defecto, '#paginador'.
 * table:	string con el elemento que tiene los datos. Por defecto, 'table'.
 * image: la imagen a mostrar mientras se ejecuta la operación.
 */

jQuery.fn.ajaxPaginator = function( options )
{
  var defaults =
  {
    paginator: '#paginador',
    table: 'table',
    beforeSend: function()
    {
      $('#flashMessage').remove();
    },
    cargando: 'Cargando...',
    history: true
  };

  jQuery.extend( defaults, options );

  return this.each( function()
  {
    var $element = jQuery(this);
    defaults['success'] = function(data) { $element.html(data); }

    if(defaults.history)
    {
      if(history && history.pushState)
      {
        $(window).bind("popstate", function()
        {
          load_page($element, location.href, defaults);
        });
      }
      else
      {
        $.history.init(function(hash)
        {
          if(hash != '')
          {
            load_page($element, hash, defaults)
          }
        });
      }
    }

    jQuery(defaults.paginator + ' a,' + defaults.table + ' th a', $element).live('click', function()
    {
      var url = jQuery(this).attr("href");
      if(defaults.history)
      {
        if(history && history.pushState)
        {
          history.pushState(null, document.title, this.href);
          load_page($element, url, defaults);
        }
        else
        {
          $.history.load(url);
        }
      }
      else
      {
        load_page($element, url, defaults);
      }
      return false;
    });
  });
}

function load_page(element, url, options)
{
  options['url'] = url;
  element.empty().html('
' + options.cargando + '
');
  $.ajax(options);
}<|endoftext|>


<commit_before>require(["jquery", "jquery.gridster"], function($, gridster) {
  var g = $("#notebook-panels");
  var scrollWidth = 15;
  var w = ($(document.body).width() - scrollWidth) * (3.0 / 12);
  var m = 0;
  var nbCols = 2;
  var b = (w - (2 * nbCols)*m) / nbCols

  var ul = $("#notebook-panels .gridster > ul");

  var site = $("#site");
  var nb = $("#notebook");
  var sb = $("#sidebar");
  var hh = $("#header").height();
  function sticky_relocate() {
    if (nb.is(":visible")) {
      var t = nb.offset().top;
      if (t < 0) {
        // allow to scroll the part of notebook which don't fit into window
        // otherwise the sidebar would make the window scrollable forever
        var maxOffset = Math.max(hh + nb.height() - $(window).height(), 0);
        var offset = Math.min(maxOffset, Math.abs(t) + hh);
        sb.css("top", offset+"px");
      } else if (t < hh) {
        sb.css("top", (hh-t)+"px");
      } else {
        sb.css("top", "20px");
      }
    }
  }

  site.scroll(sticky_relocate);

  var g = ul.gridster({
    widget_margins: [m, m],
    widget_base_dimensions: [b, 50],
    max_size_x: 2,
    helper: 'clone',
    resize: {
      enabled: true
    }
  }).data("gridster");

  var sizeContent = function(id) {
    var td = $("#"+id);
    var wid = td.parents(".widget:first");
    td.height((wid.data().sizey * 50 /*compute widget height*/) - (28+2*4 /*h4*/) + "px");
  };

  sizeContent("termDefinitions");
  sizeContent("logsPanel");
});

require(["jquery", "underscore", "base/js/events", "knockout"], function($, _, events, ko) {
  // http://lions-mark.com/jquery/scrollTo/
  $.fn.scrollTo = function( target, options, callback ){
    if(typeof options == 'function' && arguments.length == 2){ callback = options; options = target; }
    var settings = $.extend({
      scrollTarget  : target,
      offsetTop     : 50,
      duration      : 500,
      easing        : 'swing'
    }, options);
    return this.each(function(){
      var scrollPane = $(this);
      var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget);
      var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop);
      scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){
        if (typeof callback == 'function') { callback.call(this); }
      });
    });
  };

  var td = $("#termDefinitions");

  if (!td.find("table").length) {
    function viewModel() {
      var self = this;
      self.checkClash = ko.observable(true);
      self.definitions = {};
      self.definitions.data = ko.observableArray([]);
      self.clearDefinitions = function() {
        self.definitions.data.remove(function(e) { return true });
      };
      self.findDirty = function(v) {
        if (!v) return [];
        var defs = self.definitions.data();
        var findDirtyInDef = function(def, v) {
          if (def.refs) {
            return _.find(def.refs, function(r) { return r === v.name });
          } else return [];
        };
        var findDirtyInDefs = function(defs, v) {
          return _.filter(defs, function(def) { return findDirtyInDef(def, v)});
        }
        var catchThemAll = function(vs, acc) {
          if (!vs || !vs.length) return acc;
          else {
            var dirty = _.flatten(_.map(vs, function(v) { return findDirtyInDefs(defs, v); }));
            return catchThemAll(dirty, _.flatten([acc, dirty]));
          }
        };
        return catchThemAll([v], []);
      };
      self.addDefinition = function(def) {
        var finder = function(e) { return e.name == def.name;};
        var existing = _.find(self.definitions.data(), finder);
        if (existing && self.checkClash() === true) {
          if (existing.cell != def.cell) {
            self.hightlight(existing, "danger", true);
          } else {
            var dirty = self.findDirty(def);
            _.each(dirty, function(d) {
              var cell = self.findCell(d).attr("data-dirty", true);
              if (!cell.find(".validate-output").length){
                var validate = $('Ignore');
                validate.find("a.validate-output").click(function(e) {
                  e.preventDefault();
                  e.stopPropagation();
                  validate.remove();
                  cell.removeClass("alert").removeClass("alert-warning");
                });
                cell.find("div.pull-right.text-info").append(validate);
                self.hightlight(d, "warning", false, false);
              }
            });
          }
        }
        self.definitions.data.remove(finder);
        self.definitions.data.push(def);
      };
      self.findCell = function(def) {
        var cell = $("div.cell[data-cell-id='"+def.cell+"']");
        return cell;
      };
      self.hightlight = function(def, level, scroll, timeout) {
        var cell = self.findCell(def);
        var level = level || "info";
        var scroll = scroll === true || scroll === undefined;
        var timeout = (timeout === false ? false : (timeout || 800));
        cell.addClass("alert alert-"+level);

        if (scroll) $('#site').scrollTo(cell, { duration: 300, offsetTop: 200 });

        if (timeout) {
          setTimeout(function() {
            cell.removeClass("alert alert-"+level)
          }, timeout);
        }
      };
      self.hightlightCell = function() {
        self.hightlight(this);
      };
    };
    var model = new viewModel();

    var tbl = $('
'+
      '
'+
      '
Name	Type
'+
      '
'+
      '
'+
      '
'+
      '            	'+
      '            	'+
      '
'+
      '
'+
      '
')

    ko.applyBindings(model, tbl.get(0));
    td.append(tbl);

    events.on('kernel_restarting.Kernel', function(e, c) {
      // clear sidebar on kernel restart
      // reset term definitions
      model.clearDefinitions();
      // clear old progressbar
      $('#all-jobs-progress-bar').html('');
      // disable link to Spark UI
      $('#link-to-spark-ui').addClass('disabled').find('a').attr('href', '#');
    });

    events.on('kernel_ready.Kernel', function(e, c) {
      var kernel = c.kernel;
      console.debug("kernel", kernel);

      kernel.events.on("new.Definition", function(e, c) {
        console.debug("new def", c);
        if (c.term || c.type) {
          model.addDefinition({name: c.term || c.type, type: c.tpe, cell: c.cell, refs: c.references});
        }
      });
    });

    // toggle sidebar
    $('a#toggle-sidebar').click(function(){
      $('#sidebar').toggleClass('hidden');
      // expand the notebook when sidebar is hidden
      $('#notebook').toggleClass('col-md-9').toggleClass('col-md-12');
    });
  }
});
<commit_msg>Disable buggy dirty cell highlighting<commit_after>require(["jquery", "jquery.gridster"], function($, gridster) {
  var g = $("#notebook-panels");
  var scrollWidth = 15;
  var w = ($(document.body).width() - scrollWidth) * (3.0 / 12);
  var m = 0;
  var nbCols = 2;
  var b = (w - (2 * nbCols)*m) / nbCols

  var ul = $("#notebook-panels .gridster > ul");

  var site = $("#site");
  var nb = $("#notebook");
  var sb = $("#sidebar");
  var hh = $("#header").height();
  function sticky_relocate() {
    if (nb.is(":visible")) {
      var t = nb.offset().top;
      if (t < 0) {
        // allow to scroll the part of notebook which don't fit into window
        // otherwise the sidebar would make the window scrollable forever
        var maxOffset = Math.max(hh + nb.height() - $(window).height(), 0);
        var offset = Math.min(maxOffset, Math.abs(t) + hh);
        sb.css("top", offset+"px");
      } else if (t < hh) {
        sb.css("top", (hh-t)+"px");
      } else {
        sb.css("top", "20px");
      }
    }
  }

  site.scroll(sticky_relocate);

  var g = ul.gridster({
    widget_margins: [m, m],
    widget_base_dimensions: [b, 50],
    max_size_x: 2,
    helper: 'clone',
    resize: {
      enabled: true
    }
  }).data("gridster");

  var sizeContent = function(id) {
    var td = $("#"+id);
    var wid = td.parents(".widget:first");
    td.height((wid.data().sizey * 50 /*compute widget height*/) - (28+2*4 /*h4*/) + "px");
  };

  sizeContent("termDefinitions");
  sizeContent("logsPanel");
});

require(["jquery", "underscore", "base/js/events", "knockout"], function($, _, events, ko) {
  // http://lions-mark.com/jquery/scrollTo/
  $.fn.scrollTo = function( target, options, callback ){
    if(typeof options == 'function' && arguments.length == 2){ callback = options; options = target; }
    var settings = $.extend({
      scrollTarget  : target,
      offsetTop     : 50,
      duration      : 500,
      easing        : 'swing'
    }, options);
    return this.each(function(){
      var scrollPane = $(this);
      var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget);
      var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop);
      scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){
        if (typeof callback == 'function') { callback.call(this); }
      });
    });
  };

  var td = $("#termDefinitions");

  if (!td.find("table").length) {
    function viewModel() {
      var self = this;
      // FIXME: disabled as seem to freeze UI, fix or remove the feature
      self.checkClash = ko.observable(false);
      self.definitions = {};
      self.definitions.data = ko.observableArray([]);
      self.clearDefinitions = function() {
        self.definitions.data.remove(function(e) { return true });
      };
      self.findDirty = function(v) {
        if (!v) return [];
        var defs = self.definitions.data();
        var findDirtyInDef = function(def, v) {
          if (def.refs) {
            return _.find(def.refs, function(r) { return r === v.name });
          } else return [];
        };
        var findDirtyInDefs = function(defs, v) {
          return _.filter(defs, function(def) { return findDirtyInDef(def, v)});
        }
        var catchThemAll = function(vs, acc) {
          if (!vs || !vs.length) return acc;
          else {
            var dirty = _.flatten(_.map(vs, function(v) { return findDirtyInDefs(defs, v); }));
            return catchThemAll(dirty, _.flatten([acc, dirty]));
          }
        };
        return catchThemAll([v], []);
      };
      self.addDefinition = function(def) {
        var finder = function(e) { return e.name == def.name;};
        var existing = _.find(self.definitions.data(), finder);
        if (existing && self.checkClash() === true) {
          if (existing.cell != def.cell) {
            self.hightlight(existing, "danger", true);
          } else {
            var dirty = self.findDirty(def);
            _.each(dirty, function(d) {
              var cell = self.findCell(d).attr("data-dirty", true);
              if (!cell.find(".validate-output").length){
                var validate = $('Ignore');
                validate.find("a.validate-output").click(function(e) {
                  e.preventDefault();
                  e.stopPropagation();
                  validate.remove();
                  cell.removeClass("alert").removeClass("alert-warning");
                });
                cell.find("div.pull-right.text-info").append(validate);
                self.hightlight(d, "warning", false, false);
              }
            });
          }
        }
        self.definitions.data.remove(finder);
        self.definitions.data.push(def);
      };
      self.findCell = function(def) {
        var cell = $("div.cell[data-cell-id='"+def.cell+"']");
        return cell;
      };
      self.hightlight = function(def, level, scroll, timeout) {
        var cell = self.findCell(def);
        var level = level || "info";
        var scroll = scroll === true || scroll === undefined;
        var timeout = (timeout === false ? false : (timeout || 800));
        cell.addClass("alert alert-"+level);

        if (scroll) $('#site').scrollTo(cell, { duration: 300, offsetTop: 200 });

        if (timeout) {
          setTimeout(function() {
            cell.removeClass("alert alert-"+level)
          }, timeout);
        }
      };
      self.hightlightCell = function() {
        self.hightlight(this);
      };
    };
    var model = new viewModel();

    var tbl = $('
'+
      '
'+
      '
Name	Type
'+
      '
'+
      '
'+
      '
'+
      '            	'+
      '            	'+
      '
'+
      '
'+
      '
')

    ko.applyBindings(model, tbl.get(0));
    td.append(tbl);

    events.on('kernel_restarting.Kernel', function(e, c) {
      // clear sidebar on kernel restart
      // reset term definitions
      model.clearDefinitions();
      // clear old progressbar
      $('#all-jobs-progress-bar').html('');
      // disable link to Spark UI
      $('#link-to-spark-ui').addClass('disabled').find('a').attr('href', '#');
    });

    events.on('kernel_ready.Kernel', function(e, c) {
      var kernel = c.kernel;
      console.debug("kernel", kernel);

      kernel.events.on("new.Definition", function(e, c) {
        console.debug("new def", c);
        if (c.term || c.type) {
          model.addDefinition({name: c.term || c.type, type: c.tpe, cell: c.cell, refs: c.references});
        }
      });
    });

    // toggle sidebar
    $('a#toggle-sidebar').click(function(){
      $('#sidebar').toggleClass('hidden');
      // expand the notebook when sidebar is hidden
      $('#notebook').toggleClass('col-md-9').toggleClass('col-md-12');
    });
  }
});
<|endoftext|>


<commit_before>// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form");

frappe.ui.form.Review = class Review {
	constructor({parent, frm}) {
		this.parent = parent;
		this.frm = frm;
		this.fetch_energy_points()
			.then(() => {
				this.make_review_container();
				this.add_review_button();
				this.update_reviewers();
			});
	}
	fetch_energy_points() {
		return frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.get_energy_points', {
			user: frappe.session.user
		}).then(data => {
			this.points = data;
		});
	}
	make_review_container() {
		this.$wrapper = this.parent.append(`

${__('Reviews')}

		`);
		this.review_list_wrapper = this.$wrapper.find('.review-list');
	}
	add_review_button() {

		this.review_list_wrapper.append(`

		`);

		const review_button = this.review_list_wrapper.find('.btn-add-review');

		if (!this.points.review_points) {
			review_button.click(false);
			review_button.popover({
				trigger: 'hover',
				content: () => {
					return `

						${__('You do not have enough review points')}

`;
				},
				html: true
			});
		} else {
			review_button.click(() => this.show_review_dialog());
		}
	}
	get_involved_users() {
		const user_fields = this.frm.meta.fields
			.filter(d => d.fieldtype === 'Link' && d.options === 'User')
			.map(d => d.fieldname);

		user_fields.push('owner');
		let involved_users = user_fields.map(field => this.frm.doc[field]);

		const docinfo = this.frm.get_docinfo();

		involved_users = involved_users.concat(
			docinfo.communications.map(d => d.sender && d.delivery_status==='sent'),
			docinfo.comments.map(d => d.owner),
			docinfo.versions.map(d => d.owner),
			docinfo.assignments.map(d => d.owner)
		);

		return involved_users
			.uniqBy(u => u)
			.filter(user => !['Administrator', frappe.session.user].includes(user))
			.filter(Boolean);
	}
	show_review_dialog() {
		const user_options = this.get_involved_users();
		const doc_owner = this.frm.doc.owner;
		const review_dialog = new frappe.ui.Dialog({
			'title': __('Add Review'),
			'fields': [{
				fieldname: 'to_user',
				fieldtype: 'Autocomplete',
				label: __('To User'),
				options: user_options,
				default: user_options.includes(doc_owner) ? doc_owner : user_options[0],
				description: __('Only users involved in the document are listed')
			}, {
				fieldname: 'review_type',
				fieldtype: 'Select',
				label: __('Action'),
				options: [{
					'label': __('Appreciate'),
					'value': 'Appreciation'
				}, {
					'label': __('Criticize'),
					'value': 'Criticism'
				}],
				default: 'Appreciation'
			}, {
				fieldname: 'points',
				fieldtype: 'Int',
				label: __('Points'),
				reqd: 1,
				description: __(`Currently you have ${this.points.review_points} review points`)
			}, {
				fieldtype: 'Small Text',
				fieldname: 'reason',
				reqd: 1,
				label: __('Reason')
			}],
			primary_action: (values) => {
				if (values.points > this.points.review_points) {
					return frappe.msgprint(__('You do not have enough points'));
				}
				frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.review', {
					doc: {
						doctype: this.frm.doc.doctype,
						name: this.frm.doc.name,
					},
					to_user: values.to_user,
					points: values.points,
					review_type: values.review_type,
					reason: values.reason
				}).then(review => {
					review_dialog.hide();
					review_dialog.clear();
					this.frm.get_docinfo().energy_point_logs.unshift(review);
					this.update_reviewers();
				});
			},
			primary_action_label: __('Submit')
		});
		review_dialog.show();
	}
	update_reviewers() {
		const review_logs = this.frm.get_docinfo().energy_point_logs
			.filter(log => log.type !== 'Auto');

		this.review_list_wrapper.find('.review-pill').remove();
		review_logs.forEach(log => {
			let review_pill = $(`

					${frappe.avatar(log.owner)}
					${frappe.energy_points.get_points(log.points)}

			`);
			this.review_list_wrapper.prepend(review_pill);
			this.setup_detail_popover(review_pill, log);
		});
	}
	setup_detail_popover(el, data) {
		let subject = '';
		let fullname = frappe.user.full_name(data.user);
		let timestamp = `<span class="text-muted">${frappe.datetime.comment_when(data.creation)}</span>`;
		let message_parts = [Math.abs(data.points), fullname, timestamp];
		if (data.type === 'Appreciation') {
			if (data.points == 1) {
				subject = __('{0} appreciation point for {1} {2}', message_parts);
			} else {
				subject = __('{0} appreciation points for {1} {2}', message_parts);
			}
		} else {
			if (data.points == -1) {
				subject = __('{0} criticism point for {1} {2}', message_parts);
			} else {
				subject = __('{0} criticism points for {1} {2}', message_parts);
			}
		}
		el.popover({
			animation: true,
			trigger: 'hover',
			delay: 500,
			placement: 'top',
			template:`

			`,
			content: () => {
				return `

							${subject}

${data.reason}

				`;
			},
			html: true,
			container: 'body'
		});
		return el;
	}
};
<commit_msg>fix: Include only appreciation and criticism logs for review pills<commit_after>// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form");

frappe.ui.form.Review = class Review {
	constructor({parent, frm}) {
		this.parent = parent;
		this.frm = frm;
		this.fetch_energy_points()
			.then(() => {
				this.make_review_container();
				this.add_review_button();
				this.update_reviewers();
			});
	}
	fetch_energy_points() {
		return frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.get_energy_points', {
			user: frappe.session.user
		}).then(data => {
			this.points = data;
		});
	}
	make_review_container() {
		this.$wrapper = this.parent.append(`

${__('Reviews')}

		`);
		this.review_list_wrapper = this.$wrapper.find('.review-list');
	}
	add_review_button() {

		this.review_list_wrapper.append(`

		`);

		const review_button = this.review_list_wrapper.find('.btn-add-review');

		if (!this.points.review_points) {
			review_button.click(false);
			review_button.popover({
				trigger: 'hover',
				content: () => {
					return `

						${__('You do not have enough review points')}

`;
				},
				html: true
			});
		} else {
			review_button.click(() => this.show_review_dialog());
		}
	}
	get_involved_users() {
		const user_fields = this.frm.meta.fields
			.filter(d => d.fieldtype === 'Link' && d.options === 'User')
			.map(d => d.fieldname);

		user_fields.push('owner');
		let involved_users = user_fields.map(field => this.frm.doc[field]);

		const docinfo = this.frm.get_docinfo();

		involved_users = involved_users.concat(
			docinfo.communications.map(d => d.sender && d.delivery_status==='sent'),
			docinfo.comments.map(d => d.owner),
			docinfo.versions.map(d => d.owner),
			docinfo.assignments.map(d => d.owner)
		);

		return involved_users
			.uniqBy(u => u)
			.filter(user => !['Administrator', frappe.session.user].includes(user))
			.filter(Boolean);
	}
	show_review_dialog() {
		const user_options = this.get_involved_users();
		const doc_owner = this.frm.doc.owner;
		const review_dialog = new frappe.ui.Dialog({
			'title': __('Add Review'),
			'fields': [{
				fieldname: 'to_user',
				fieldtype: 'Autocomplete',
				label: __('To User'),
				options: user_options,
				default: user_options.includes(doc_owner) ? doc_owner : user_options[0],
				description: __('Only users involved in the document are listed')
			}, {
				fieldname: 'review_type',
				fieldtype: 'Select',
				label: __('Action'),
				options: [{
					'label': __('Appreciate'),
					'value': 'Appreciation'
				}, {
					'label': __('Criticize'),
					'value': 'Criticism'
				}],
				default: 'Appreciation'
			}, {
				fieldname: 'points',
				fieldtype: 'Int',
				label: __('Points'),
				reqd: 1,
				description: __(`Currently you have ${this.points.review_points} review points`)
			}, {
				fieldtype: 'Small Text',
				fieldname: 'reason',
				reqd: 1,
				label: __('Reason')
			}],
			primary_action: (values) => {
				if (values.points > this.points.review_points) {
					return frappe.msgprint(__('You do not have enough points'));
				}
				frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.review', {
					doc: {
						doctype: this.frm.doc.doctype,
						name: this.frm.doc.name,
					},
					to_user: values.to_user,
					points: values.points,
					review_type: values.review_type,
					reason: values.reason
				}).then(review => {
					review_dialog.hide();
					review_dialog.clear();
					this.frm.get_docinfo().energy_point_logs.unshift(review);
					this.update_reviewers();
				});
			},
			primary_action_label: __('Submit')
		});
		review_dialog.show();
	}
	update_reviewers() {
		const review_logs = this.frm.get_docinfo().energy_point_logs
			.filter(log => ['Appreciation', 'Criticism'].includes(log.type));

		this.review_list_wrapper.find('.review-pill').remove();
		review_logs.forEach(log => {
			let review_pill = $(`

					${frappe.avatar(log.owner)}
					${frappe.energy_points.get_points(log.points)}

			`);
			this.review_list_wrapper.prepend(review_pill);
			this.setup_detail_popover(review_pill, log);
		});
	}
	setup_detail_popover(el, data) {
		let subject = '';
		let fullname = frappe.user.full_name(data.user);
		let timestamp = `<span class="text-muted">${frappe.datetime.comment_when(data.creation)}</span>`;
		let message_parts = [Math.abs(data.points), fullname, timestamp];
		if (data.type === 'Appreciation') {
			if (data.points == 1) {
				subject = __('{0} appreciation point for {1} {2}', message_parts);
			} else {
				subject = __('{0} appreciation points for {1} {2}', message_parts);
			}
		} else {
			if (data.points == -1) {
				subject = __('{0} criticism point for {1} {2}', message_parts);
			} else {
				subject = __('{0} criticism points for {1} {2}', message_parts);
			}
		}
		el.popover({
			animation: true,
			trigger: 'hover',
			delay: 500,
			placement: 'top',
			template:`

			`,
			content: () => {
				return `

							${subject}

${data.reason}

				`;
			},
			html: true,
			container: 'body'
		});
		return el;
	}
};
<|endoftext|>


<commit_before>$(document).ready(function() {
  window.location.origin = window.location.origin || (window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);
  var socket = io.connect(window.location.origin);
  socket.on('update-msg', function (msg) {
  	//console.log(msg);
    var data = jQuery.parseJSON(msg.data);
    //console.log(data);

    // make sure we have some data
    if(data.power) {
      /*var tempStr = data.temp + '\u2103';
      if(data.temp > 90) tempStr += ' Alert! High temperature!';
      $('#temperature').html(tempStr);

      var humidityStr = data.humidity + '%';
      if(data.humidity > 90) humidityStr += ' Alert! High humidity!';
      $('#humidity').html(humidityStr);*/

      var powerStr = data.power + 'W';
      if(data.power >= 5000) powerStr += ' Alert! High power!';
      $('#power').html(powerStr);

      $('#maxpower').html(data.maxPower + 'W');

      $('#deviceid').html(data.DeviceID);

      var latitude = data.LocLat;
      if(latitude < 0) latitude = (-1 * latitude) + '\u00B0S';
      else latitude = latitude + '\u00B0N';
      $('#loclat').html(latitude);

      var longitude = data.LocLong;
      if(longitude < 0) longitude = (-1 * longitude) + '\u00B0W';
      else longitude = longitude + '\u00B0E';
      $('#loclong').html(longitude);

      $('#policyid').html(data.PolicyID);
    }
  });
});

var myLatlng = new google.maps.LatLng(37.349691000239545,-121.977338999795);
var mapOptions = {
  zoom: 10,
  center: myLatlng
};
var map;

var socketaddy = "ws://insuranceiot-build-22-back-end.mybluemix.net/ServiceProviders";
var message = "....";
$(document).ready(function(){

  $('#output').text = message;
  sock = new WebSocket(socketaddy);
  sock.onopen = function(){
    console.log("Connected websocket");
  };
  sock.onerror = function(){
    console.log("Websocket error");
  };
  sock.onclose = function () {};

  sock.onmessage = function(evt){
    console.log("Websocket message", evt);
    message = evt.data;
    var jsonData = JSON.parse('{"IMBIOT":' + message + '}');
    // Create table.
    var table = document.createElement('table');
    for (var i = 0; i < jsonData.IMBIOT.length; i++) {
      var counter = jsonData.IMBIOT[i];
      var provider = table.insertRow(i);
      var provider_id = provider.insertCell(0);
      provider_id.innerHTML = counter.PROVIDER_ID;

      var provider_name = provider.insertCell(1);
      provider_name.innerHTML = counter.PROVIDER_NAME;

      var latitude = provider.insertCell(2);
      latitude.innerHTML = counter.LATITUDE;

      var longitude = provider.insertCell(3);
      longitude.innerHTML = counter.LONGITUDE;

      var div = document.getElementById('text');
      div.innerHTML=table.innerHTML.replace('tbody','table').replace('tbody','table');

      addMarker(counter.LATITUDE,counter.LONGITUDE);
      document.getElementById('map-canvas').style.visibility='visible';
    }
  };
});

function initializeMap() {
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function addMarker(latitude, longitude){
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(latitude, longitude),
    map: map,
    animation: google.maps.Animation.DROP,
	title: 'Service Provider - '
  });
}<commit_msg>added socket in front-end<commit_after>$(document).ready(function() {
  window.location.origin = window.location.origin || (window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);
  var socket = io.connect(window.location.origin);
  socket.on('update-msg', function (msg) {
  	//console.log(msg);
    var data = jQuery.parseJSON(msg.data);
    //console.log(data);

    // make sure we have some data
    if(data.power) {
      /*var tempStr = data.temp + '\u2103';
      if(data.temp > 90) tempStr += ' Alert! High temperature!';
      $('#temperature').html(tempStr);

      var humidityStr = data.humidity + '%';
      if(data.humidity > 90) humidityStr += ' Alert! High humidity!';
      $('#humidity').html(humidityStr);*/

      var powerStr = data.power + 'W';
      if(data.power >= 5000) powerStr += ' Alert! High power!';
      $('#power').html(powerStr);

      $('#maxpower').html(data.maxPower + 'W');

      $('#deviceid').html(data.DeviceID);

      var latitude = data.LocLat;
      if(latitude < 0) latitude = (-1 * latitude) + '\u00B0S';
      else latitude = latitude + '\u00B0N';
      $('#loclat').html(latitude);

      var longitude = data.LocLong;
      if(longitude < 0) longitude = (-1 * longitude) + '\u00B0W';
      else longitude = longitude + '\u00B0E';
      $('#loclong').html(longitude);

      $('#policyid').html(data.PolicyID);
    }
  });
});

var myLatlng = new google.maps.LatLng(37.349691000239545,-121.977338999795);
var mapOptions = {
  zoom: 10,
  center: myLatlng
};
var map;

var socketSP = "ws://insuranceiot-build-22-back-end.mybluemix.net/ServiceProviders";
var message = "....";
$(document).ready(function(){
  $('#output').text = message;
  sock = new WebSocket(socketSP);
  sock.onopen = function(){
    console.log("Connected websocket");
  };
  sock.onerror = function(){
    console.log("Websocket error");
  };
  sock.onclose = function () {};

  sock.onmessage = function(evt){
    console.log("Websocket message", evt);
    message = evt.data;
    var jsonData = JSON.parse('{"IMBIOT":' + message + '}');
    // Create table.
    var table = document.createElement('table');
    for (var i = 0; i < jsonData.IMBIOT.length; i++) {
      var counter = jsonData.IMBIOT[i];
      var provider = table.insertRow(i);
      var provider_id = provider.insertCell(0);
      provider_id.innerHTML = counter.PROVIDER_ID;

      var provider_name = provider.insertCell(1);
      provider_name.innerHTML = counter.PROVIDER_NAME;

      var latitude = provider.insertCell(2);
      latitude.innerHTML = counter.LATITUDE;

      var longitude = provider.insertCell(3);
      longitude.innerHTML = counter.LONGITUDE;

      var div = document.getElementById('text');
      div.innerHTML=table.innerHTML.replace('tbody','table').replace('tbody','table');

      addMarker(counter.LATITUDE,counter.LONGITUDE);
      document.getElementById('map-canvas').style.visibility='visible';
    }
  };
});

var socketScoring = "ws://insuranceiot-build-22-back-end.mybluemix.net/ws/scoring";
$(document).ready(function(){
  sock = new WebSocket(socketScoring);
  sock.onopen = function(){
    console.log("Connected websocket");
  };
  sock.onerror = function(){
    console.log("Websocket error");
  };
  sock.onclose = function () {};

  sock.onmessage = function(evt){
    console.log("Websocket message", evt);
    var boolean = evt.data;
    // Create table.
    $('.boolean').html(boolean);
  };
});

function initializeMap() {
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function addMarker(latitude, longitude){
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(latitude, longitude),
    map: map,
    animation: google.maps.Animation.DROP,
	title: 'Service Provider - '
  });
}<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"dojo/dom-class", "dojo/dom-construct", "dojo/on", "dojo/request",
	"./SummaryWidget", "../util/PathJoin", "./D3HorizontalBarChart"

], function(declare, lang,
			domClass, domConstruct, on, xhr,
			SummaryWidget, PathJoin, D3HorizontalBarChart){

	return declare([SummaryWidget], {
		dataModel: "genome_feature",
		query: "",
		baseQuery: "&limit(1)&facet((field,genome_id),(mincount,1),(limit,-1))&json(nl,map)",
		columns: [
			{label: "Taxon Level", field: "label"},
			{
				label: "Genes", field: "count"
			}
		],
		// TODO:
		// - make D3HorizonalBarChart modular and configurable
		// - make the facet field dynamics (phylum, class, order, family, genus, species)
		// - handle genome level profile
		//
		// onSetQuery: function(attr, oldVal, query){
		// 	// console.log("SummaryWidget Query: ", this.query + this.baseQuery);
		// 	return xhr.post(PathJoin(this.apiServiceUrl, this.dataModel) + "/", {
		// 		handleAs: "json",
		// 		headers: this.headers,
		// 		data: this.query + this.baseQuery
		// 	}).then(lang.hitch(this, "processData"));
		// },
		processData: function(data){

			if(!data || !data.facet_counts || !data.facet_counts.facet_fields['genome_id']){
				console.log("INVALID SUMMARY DATA", data);
				return;
			}

			var genomeFreqMap = data.facet_counts.facet_fields.genome_id;
			var genomeIds = Object.keys(genomeFreqMap);

			xhr.post(PathJoin(this.apiServiceUrl, "/genome/") + "/", {
				handleAs: "json",
				headers: {
					'Accept': "application/solr+json",
					'Content-Type': "application/rqlquery+x-www-form-urlencoded",
					'X-Requested-With': null,
					'Authorization': window.App.authorizationToken || ""
				},
				data: "in(genome_id,(" + genomeIds.join(",") + "))&limit(1)&facet((pivot,(species,genome_id)),(mincount,1),(limit,-1))&json(nl,map)"
			}).then(lang.hitch(this, function(res){

					var facet = res.facet_counts.facet_pivot['species,genome_id'];
					// console.log("facet: ", facet);

					var data = [];
					var keyValueMap = {};

					facet.forEach(function(d){
						var key = d.value;
						var count = 0;
						if(d.pivot){
							d.pivot.forEach(function(g){
								// console.log(genomeFreqMap[g.value], g.count);
								count += genomeFreqMap[g.value] * g.count;
							})
						}
						// console.log(key, count);
						keyValueMap[key] = count;
					});
					// console.log("keyValueMap: ", keyValueMap);

					Object.keys(keyValueMap).forEach(function(key){
						data.push({
							label: key, count: keyValueMap[key]
						});
					});

					var filtered = data.sort(function(a, b){
						return b.count - a.count;
					}).filter(function(d, i){
						return i < 10;
					});

					// console.log("data: ", filtered);
					this.set('data', filtered);
				})
			);
		},

		postCreate: function(){
			this.inherited(arguments);

			on(window, "resize", lang.hitch(this, "resize"));
		},
		resize: function(){
			// console.log("resize is called in TaxonoyProfile");

			if(this.chart){
				this.chart.resize();
			}
			this.inherited(arguments);
		},

		render_chart: function(){

			if(!this.chart){
				this.chart = new D3HorizontalBarChart();
				this.chart.init(this.chartNode, "txProfile");
				this.chart.render(this.data);
			}else{

				this.chart.update(this.data);
			}
		}
		,

		render_table: function(){
			this.inherited(arguments);

			this.grid.refresh();
			this.grid.renderArray(this.data);
			this.grid.sort([{attribute: "count", descending: true}]);
		}
	})
})
;<commit_msg>add null checking<commit_after>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"dojo/dom-class", "dojo/dom-construct", "dojo/on", "dojo/request",
	"./SummaryWidget", "../util/PathJoin", "./D3HorizontalBarChart"

], function(declare, lang,
			domClass, domConstruct, on, xhr,
			SummaryWidget, PathJoin, D3HorizontalBarChart){

	return declare([SummaryWidget], {
		dataModel: "genome_feature",
		query: "",
		baseQuery: "&limit(1)&facet((field,genome_id),(mincount,1),(limit,-1))&json(nl,map)",
		columns: [
			{label: "Taxon Level", field: "label"},
			{
				label: "Genes", field: "count"
			}
		],
		// TODO:
		// - make D3HorizonalBarChart modular and configurable
		// - make the facet field dynamics (phylum, class, order, family, genus, species)
		// - handle genome level profile
		//
		// onSetQuery: function(attr, oldVal, query){
		// 	// console.log("SummaryWidget Query: ", this.query + this.baseQuery);
		// 	return xhr.post(PathJoin(this.apiServiceUrl, this.dataModel) + "/", {
		// 		handleAs: "json",
		// 		headers: this.headers,
		// 		data: this.query + this.baseQuery
		// 	}).then(lang.hitch(this, "processData"));
		// },
		processData: function(data){

			if(!data || !data.facet_counts || !data.facet_counts.facet_fields['genome_id']){
				console.log("INVALID SUMMARY DATA", data);
				return;
			}

			var genomeFreqMap = data.facet_counts.facet_fields.genome_id;
			var genomeIds = Object.keys(genomeFreqMap);

			xhr.post(PathJoin(this.apiServiceUrl, "/genome/") + "/", {
				handleAs: "json",
				headers: {
					'Accept': "application/solr+json",
					'Content-Type': "application/rqlquery+x-www-form-urlencoded",
					'X-Requested-With': null,
					'Authorization': window.App.authorizationToken || ""
				},
				data: "in(genome_id,(" + genomeIds.join(",") + "))&limit(1)&facet((pivot,(species,genome_id)),(mincount,1),(limit,-1))&json(nl,map)"
			}).then(lang.hitch(this, function(res){

					if(res.length == 0){
						return;
					}

					var facet = res.facet_counts.facet_pivot['species,genome_id'];
					// console.log("facet: ", facet);

					var data = [];
					var keyValueMap = {};

					facet.forEach(function(d){
						var key = d.value;
						var count = 0;
						if(d.pivot){
							d.pivot.forEach(function(g){
								// console.log(genomeFreqMap[g.value], g.count);
								count += genomeFreqMap[g.value] * g.count;
							})
						}
						// console.log(key, count);
						keyValueMap[key] = count;
					});
					// console.log("keyValueMap: ", keyValueMap);

					Object.keys(keyValueMap).forEach(function(key){
						data.push({
							label: key, count: keyValueMap[key]
						});
					});

					var filtered = data.sort(function(a, b){
						return b.count - a.count;
					}).filter(function(d, i){
						return i < 10;
					});

					// console.log("data: ", filtered);
					this.set('data', filtered);
				})
			);
		},

		postCreate: function(){
			this.inherited(arguments);

			on(window, "resize", lang.hitch(this, "resize"));
		},
		resize: function(){
			// console.log("resize is called in TaxonoyProfile");

			if(this.chart){
				this.chart.resize();
			}
			this.inherited(arguments);
		},

		render_chart: function(){

			if(!this.chart){
				this.chart = new D3HorizontalBarChart();
				this.chart.init(this.chartNode, "txProfile");
				this.chart.render(this.data);
			}else{

				this.chart.update(this.data);
			}
		}
		,

		render_table: function(){
			this.inherited(arguments);

			this.grid.refresh();
			this.grid.renderArray(this.data);
			this.grid.sort([{attribute: "count", descending: true}]);
		}
	})
})
;<|endoftext|>


<commit_before>/*
 * Copyright (c) $year, Den Norske Turistforening (DNT)
 *
 * https://github.com/Turistforeningen/turadmin
 */

define(function (require, exports, module) {
    "use strict";

    // Dependencies
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        NtbCollection = require('collections/ntb'),
        Picture = require('models/picture');

    var apiUri = function () {
        return '/restProxy/bilder';
    };

    return NtbCollection.extend({

        removedModels: [],

        url: function () {
            return apiUri();
        },

        model: Picture,

        comparator: function (model) {
            return model.get('ordinal');
        },

        nextOrdinal: 0,

        getNextOrdinal: function () {
            this.nextOrdinal = this.nextOrdinal + 1;
            return this.nextOrdinal - 1;
        },

        onAdd: function (model) {

            NtbCollection.prototype.onAdd.apply(this, arguments);

            model.set('ordinal', this.getNextOrdinal());
        },

        reIndex: function (picture, newPosition) {
            console.log('reindexing');
            this.remove(picture, {silent: true}); // NOTE: This causes a bug which removes the picture from POI picture list.
            picture.set('ordinal', newPosition);
            this.each(function (model, index) {
                var ordinal = index;
                if (index >= newPosition) {
                    ordinal = ordinal + 1;
                }
                model.set('ordinal', ordinal);
            });
            this.add(picture, {silent: true, at: newPosition});
            this.sort();
        },

        setPublished: function () {
            this.each(function (model, index) {
                model.setPublished();
            });
        },

        setUnpublished: function () {
            this.each(function (model, index) {
                model.setUnpublished();
            });
        }
    });
});
<commit_msg>Removed console log<commit_after>/*
 * Copyright (c) $year, Den Norske Turistforening (DNT)
 *
 * https://github.com/Turistforeningen/turadmin
 */

define(function (require, exports, module) {
    "use strict";

    // Dependencies
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        NtbCollection = require('collections/ntb'),
        Picture = require('models/picture');

    var apiUri = function () {
        return '/restProxy/bilder';
    };

    return NtbCollection.extend({

        removedModels: [],

        url: function () {
            return apiUri();
        },

        model: Picture,

        comparator: function (model) {
            return model.get('ordinal');
        },

        nextOrdinal: 0,

        getNextOrdinal: function () {
            this.nextOrdinal = this.nextOrdinal + 1;
            return this.nextOrdinal - 1;
        },

        onAdd: function (model) {

            NtbCollection.prototype.onAdd.apply(this, arguments);

            model.set('ordinal', this.getNextOrdinal());
        },

        reIndex: function (picture, newPosition) {
            this.remove(picture, {silent: true}); // NOTE: This causes a bug which removes the picture from POI picture list.
            picture.set('ordinal', newPosition);
            this.each(function (model, index) {
                var ordinal = index;
                if (index >= newPosition) {
                    ordinal = ordinal + 1;
                }
                model.set('ordinal', ordinal);
            });
            this.add(picture, {silent: true, at: newPosition});
            this.sort();
        },

        setPublished: function () {
            this.each(function (model, index) {
                model.setPublished();
            });
        },

        setUnpublished: function () {
            this.each(function (model, index) {
                model.setUnpublished();
            });
        }
    });
});
<|endoftext|>


<commit_before>import axios from 'axios'
const BASE_URL = 'http://localhost:8000/gwells/registries/'

const logging = true

const ApiService = {
  init () {
    axios.defaults.baseURL = BASE_URL
    if (logging) {
      console.log('turning on interceptors')
      axios.interceptors.request.use(function (request) {
        console.log(request)
        return request
      }, function (error) {
        console.log(error)
        return Promise.reject(error)
      })
      axios.interceptors.response.use(function (response) {
        console.log(response)
        return response
      }, function (error) {
        console.log(error)
        return Promise.reject(error)
      })
    }
  },
  authHeader (prefix, token) {
    // set auth header. Expects prefix to be "Bearer", "JWT" etc.
    // deletes auth header if called without a token (useful for logging out)
    if (prefix && token) {
      axios.defaults.headers.common['Authorization'] = `${prefix} ${token}`
    } else if (axios.defaults.headers.common['Authorization']) {
      delete axios.defaults.headers.common['Authorization']
    }
  },
  query (resource, params) {
    return axios.get(resource, { params: params })
  },
  get (resource, uuid) {
    if (uuid.length && uuid.length === 36) {
      return axios.get(`${resource}/${uuid}/`)
    }
    throw new Error(`API get: UUID required to fetch ${resource}`)
  },
  post (resource, params) {
    return axios.post(resource, params)
  }
}

export default ApiService
<commit_msg>switch to relative base url path and turn off logging by default<commit_after>import axios from 'axios'
const BASE_URL = '/gwells/registries/'

const logging = false

const ApiService = {
  init () {
    axios.defaults.baseURL = BASE_URL
    if (logging) {
      console.log('turning on interceptors')
      axios.interceptors.request.use(function (request) {
        console.log(request)
        return request
      }, function (error) {
        console.log(error)
        return Promise.reject(error)
      })
      axios.interceptors.response.use(function (response) {
        console.log(response)
        return response
      }, function (error) {
        console.log(error)
        return Promise.reject(error)
      })
    }
  },
  authHeader (prefix, token) {
    // set auth header. Expects prefix to be "Bearer", "JWT" etc.
    // deletes auth header if called without a token (useful for logging out)
    if (prefix && token) {
      axios.defaults.headers.common['Authorization'] = `${prefix} ${token}`
    } else if (axios.defaults.headers.common['Authorization']) {
      delete axios.defaults.headers.common['Authorization']
    }
  },
  query (resource, params) {
    return axios.get(resource, { params: params })
  },
  get (resource, uuid) {
    if (uuid.length && uuid.length === 36) {
      return axios.get(`${resource}/${uuid}/`)
    }
    throw new Error(`API get: UUID required to fetch ${resource}`)
  },
  post (resource, params) {
    return axios.post(resource, params)
  }
}

export default ApiService
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import { connect } from 'react-redux';
import { Link } from 'react-router';
import take from 'lodash/array/take';
import values from 'lodash/object/values';
import sortBy from 'lodash/collection/sortBy';

import filterCollection from '../lib/filter_collection';
import formatCurrency from '../lib/format_currency';

import roles from '../constants/roles';
import PublicTopBar from '../components/PublicTopBar';
import Notification from '../components/Notification';
import PublicFooter from '../components/PublicFooter';
import PublicGroupThanks from '../components/PublicGroupThanks';
import TransactionItem from '../components/TransactionItem';
import YoutubeVideo from '../components/YoutubeVideo';
import Metric from '../components/Metric';
import UsersList from '../components/UsersList';
import ShareIcon from '../components/ShareIcon';
import Icon from '../components/Icon';
import DisplayUrl from '../components/DisplayUrl';
import PublicGroupSignup from '../components/PublicGroupSignup';
import Tiers from '../components/Tiers';
import Markdown from '../components/Markdown';

import fetchGroup from '../actions/groups/fetch_by_id';
import fetchUsers from '../actions/users/fetch_by_group';
import fetchTransactions from '../actions/transactions/fetch_by_group';
import donate from '../actions/groups/donate';
import notify from '../actions/notification/notify';
import resetNotifications from '../actions/notification/reset';
import appendDonationForm from '../actions/form/append_donation';
import appendProfileForm from '../actions/form/append_profile';
import updateUser from '../actions/users/update_user';
import validateDonationProfile from '../actions/form/validate_donation_profile';
import logout from '../actions/session/logout';
import decodeJWT from '../actions/session/decode_jwt';

// Number of expenses and revenue items to show on the public page
const NUM_TRANSACTIONS_TO_SHOW = 3;

const Media = ({group}) => {
  if (group.video) {
      return (

          <YoutubeVideo video={group.video} />

      );
  } else if (group.image) {
    return (

    );
  } else {
    return (

    );
  }
};

export class PublicGroup extends Component {

  constructor(props) {
    super(props);
    this.state = {
      showThankYouMessage: false,
      showUserForm: false
    };
  }

  render() {
    const {
      group,
      donations,
      expenses,
      shareUrl,
      users,
      isAuthenticated,
      donationForm
    } = this.props;

    var donationSection;
    if (this.state.showThankYouMessage || (isAuthenticated && this.state.showUserForm)) { // we don't handle userform from logged in users) {
      donationSection = <PublicGroupThanks />;
    } else if (this.state.showUserForm) {
      donationSection = <PublicGroupSignup {...this.props} save={saveNewUser.bind(this)} />
    } else {
      donationSection = <Tiers tiers={group.tiers} {...this.props} form={donationForm} onToken={donateToGroup.bind(this)} />
    }
    return (

        <PublicTopBar session={this.props.session} logout={this.props.logout} slug={group.slug}/>
        <Notification {...this.props} />

<DisplayUrl url={group.website} />

Hosted by {group.host.name}

              {group.description}

          <Media group={group} />

              <Metric
                label='Funds Available'
                value={formatCurrency(group.balance, group.currency, {precision: 0})} />
              <Metric
                label='Backers'
                value={group.backersCount} />

              Back us

              <ShareIcon type='twitter' url={shareUrl} name={group.name} description={group.description} />
              <ShareIcon type='facebook' url={shareUrl} name={group.name} description={group.description} />
              <ShareIcon type='mail' url={shareUrl} name={group.name} description={group.description} />

Our collective

              <UsersList users={group.members} />

            <Markdown className='PublicGroup-quoteText' value={group.longDescription} />

          {donationSection}

Expenses

              {(expenses.length === 0) && (

                    <Icon type='expense' />

                    All your approved expenses will show up here

              )}
              {expenses.map(expense => <TransactionItem
                                          key={expense.id}
                                          transaction={expense}
                                          user={users[expense.UserId]} />)}
              {expenses.length >= 3 && (
                <Link className='PublicGroup-tx-link' to={`/${group.slug}/expenses`}>
                  See all expenses
                </Link>
              )}

Revenue

              {(donations.length === 0) && (

                    <Icon type='revenue' />

                    All your latest donations will show up here

              )}
              {donations.map(donation => <TransactionItem
                                            key={donation.id}
                                            transaction={donation}
                                            user={users[donation.UserId]} />)}
              {donations.length >= 3 && (
                <Link className='PublicGroup-tx-link' to={`/${group.slug}/donations`}>
                  See all donations
                </Link>
              )}

        <PublicFooter />

    );
  }

  componentDidMount() {
    const {
      group,
      fetchTransactions,
      fetchUsers,
      fetchGroup
    } = this.props;

    fetchGroup(group.id);

    fetchTransactions(group.id, {
      per_page: NUM_TRANSACTIONS_TO_SHOW,
      sort: 'createdAt',
      direction: 'desc',
      donation: true
    });

    fetchTransactions(group.id, {
      per_page: NUM_TRANSACTIONS_TO_SHOW,
      sort: 'createdAt',
      direction: 'desc',
      expense: true
    });

    fetchUsers(group.id);
  }

  componentWillMount() {
    // decode here because we don't handle auth on the server side yet
    this.props.decodeJWT();
  }
}

export function donateToGroup(amount, frequency, currency, token) {
  const {
    notify,
    donate,
    group,
    fetchGroup,
    fetchUsers,
    fetchTransactions
  } = this.props;

  const payment = {
    stripeToken: token.id,
    email: token.email,
    amount,
    currency
  };

  if (frequency === 'monthly') {
    payment.interval = 'month';
  } else if (frequency === 'yearly') {
    payment.interval = 'year';
  }

  return donate(group.id, payment)
    .then(({json}) => {
      if (json && !json.hasFullAccount) {
        this.setState({ showUserForm: true })
      } else {
        this.setState({ showThankYouMessage: true })
      }
    })
    .then(() => fetchGroup(group.id))
    .then(() => fetchUsers(group.id))
    .then(() => {
      return fetchTransactions(group.id, {
        per_page: NUM_TRANSACTIONS_TO_SHOW,
        sort: 'createdAt',
        direction: 'desc',
        donation: true
      });
    })
    .catch((err) => notify('error', err.message));
}

export function saveNewUser() {
 const {
    users,
    updateUser,
    profileForm,
    validateDonationProfile,
    notify,
    group,
    fetchUsers
  } = this.props;

  return validateDonationProfile(profileForm.attributes)
    .then(() => updateUser(users.newUser.id, profileForm.attributes))
    .then(() => this.setState({
      showUserForm: false,
      showThankYouMessage: true
    }))
    .then(() => fetchUsers(group.id))
    .catch(({message}) => notify('error', message));
}

export default connect(mapStateToProps, {
  donate,
  notify,
  resetNotifications,
  fetchTransactions,
  fetchUsers,
  fetchGroup,
  appendProfileForm,
  updateUser,
  logout,
  validateDonationProfile,
  decodeJWT,
  appendDonationForm
})(PublicGroup);

function mapStateToProps({
  groups,
  form,
  notification,
  transactions,
  users,
  session
}) {

  const group = values(groups)[0] || {stripeAccount: {}}; // to refactor to allow only one group
  const usersByRole = group.usersByRole || {};

  /* @xdamman:
   * We should refactor this. The /api/group route should directly return
   * group.host, group.backers, group.members, group.donations, group.expenses
   */
  group.id = Number(group.id);

  group.hosts = usersByRole[roles.HOST] || [];
  group.members = usersByRole[roles.MEMBER] || [];
  group.backers = usersByRole[roles.BACKER] || [];

  group.host = group.hosts[0] || {};

  group.backersCount = group.backers.length;
  group.transactions = filterCollection(transactions, { GroupId: group.id });

  const donations = group.transactions.filter(({amount}) => amount > 0);
  const expenses = group.transactions.filter(({amount}) => amount < 0);

  return {
    group,
    notification,
    users,
    session,
    donations: take(sortBy(donations, txn => txn.createdAt).reverse(), NUM_TRANSACTIONS_TO_SHOW),
    expenses: take(sortBy(expenses, exp => exp.createdAt).reverse(), NUM_TRANSACTIONS_TO_SHOW),
    inProgress: groups.donateInProgress,
    shareUrl: window.location.href,
    profileForm: form.profile,
    donationForm: form.donation,
    showUserForm: users.showUserForm || false,
    saveInProgress: users.updateInProgress,
    isAuthenticated: session.isAuthenticated
  };
}<commit_msg>making sure we don't load a 3MB image to illustrate a collective<commit_after>import React, { Component } from 'react';

import { connect } from 'react-redux';
import { Link } from 'react-router';
import take from 'lodash/array/take';
import values from 'lodash/object/values';
import sortBy from 'lodash/collection/sortBy';

import filterCollection from '../lib/filter_collection';
import formatCurrency from '../lib/format_currency';

import roles from '../constants/roles';
import PublicTopBar from '../components/PublicTopBar';
import Notification from '../components/Notification';
import PublicFooter from '../components/PublicFooter';
import PublicGroupThanks from '../components/PublicGroupThanks';
import TransactionItem from '../components/TransactionItem';
import YoutubeVideo from '../components/YoutubeVideo';
import Metric from '../components/Metric';
import UsersList from '../components/UsersList';
import ShareIcon from '../components/ShareIcon';
import Icon from '../components/Icon';
import DisplayUrl from '../components/DisplayUrl';
import PublicGroupSignup from '../components/PublicGroupSignup';
import Tiers from '../components/Tiers';
import Markdown from '../components/Markdown';

import fetchGroup from '../actions/groups/fetch_by_id';
import fetchUsers from '../actions/users/fetch_by_group';
import fetchTransactions from '../actions/transactions/fetch_by_group';
import donate from '../actions/groups/donate';
import notify from '../actions/notification/notify';
import resetNotifications from '../actions/notification/reset';
import appendDonationForm from '../actions/form/append_donation';
import appendProfileForm from '../actions/form/append_profile';
import updateUser from '../actions/users/update_user';
import validateDonationProfile from '../actions/form/validate_donation_profile';
import logout from '../actions/session/logout';
import decodeJWT from '../actions/session/decode_jwt';

// Number of expenses and revenue items to show on the public page
const NUM_TRANSACTIONS_TO_SHOW = 3;

const Media = ({group}) => {
  if (group.video) {
      return (

          <YoutubeVideo video={group.video} />

      );
  } else if (group.image) {

    const encodedUrl = encodeURIComponent(group.image);
    group.image = `https://res.cloudinary.com/opencollective/image/fetch/w_720/${encodedUrl}`;

    return (

    );
  } else {
    return (

    );
  }
};

export class PublicGroup extends Component {

  constructor(props) {
    super(props);
    this.state = {
      showThankYouMessage: false,
      showUserForm: false
    };
  }

  render() {
    const {
      group,
      donations,
      expenses,
      shareUrl,
      users,
      isAuthenticated,
      donationForm
    } = this.props;

    var donationSection;
    if (this.state.showThankYouMessage || (isAuthenticated && this.state.showUserForm)) { // we don't handle userform from logged in users) {
      donationSection = <PublicGroupThanks />;
    } else if (this.state.showUserForm) {
      donationSection = <PublicGroupSignup {...this.props} save={saveNewUser.bind(this)} />
    } else {
      donationSection = <Tiers tiers={group.tiers} {...this.props} form={donationForm} onToken={donateToGroup.bind(this)} />
    }
    return (

        <PublicTopBar session={this.props.session} logout={this.props.logout} slug={group.slug}/>
        <Notification {...this.props} />

<DisplayUrl url={group.website} />

Hosted by {group.host.name}

              {group.description}

          <Media group={group} />

              <Metric
                label='Funds Available'
                value={formatCurrency(group.balance, group.currency, {precision: 0})} />
              <Metric
                label='Backers'
                value={group.backersCount} />

              Back us

              <ShareIcon type='twitter' url={shareUrl} name={group.name} description={group.description} />
              <ShareIcon type='facebook' url={shareUrl} name={group.name} description={group.description} />
              <ShareIcon type='mail' url={shareUrl} name={group.name} description={group.description} />

Our collective

              <UsersList users={group.members} />

            <Markdown className='PublicGroup-quoteText' value={group.longDescription} />

          {donationSection}

Expenses

              {(expenses.length === 0) && (

                    <Icon type='expense' />

                    All your approved expenses will show up here

              )}
              {expenses.map(expense => <TransactionItem
                                          key={expense.id}
                                          transaction={expense}
                                          user={users[expense.UserId]} />)}
              {expenses.length >= 3 && (
                <Link className='PublicGroup-tx-link' to={`/${group.slug}/expenses`}>
                  See all expenses
                </Link>
              )}

Revenue

              {(donations.length === 0) && (

                    <Icon type='revenue' />

                    All your latest donations will show up here

              )}
              {donations.map(donation => <TransactionItem
                                            key={donation.id}
                                            transaction={donation}
                                            user={users[donation.UserId]} />)}
              {donations.length >= 3 && (
                <Link className='PublicGroup-tx-link' to={`/${group.slug}/donations`}>
                  See all donations
                </Link>
              )}

        <PublicFooter />

    );
  }

  componentDidMount() {
    const {
      group,
      fetchTransactions,
      fetchUsers,
      fetchGroup
    } = this.props;

    fetchGroup(group.id);

    fetchTransactions(group.id, {
      per_page: NUM_TRANSACTIONS_TO_SHOW,
      sort: 'createdAt',
      direction: 'desc',
      donation: true
    });

    fetchTransactions(group.id, {
      per_page: NUM_TRANSACTIONS_TO_SHOW,
      sort: 'createdAt',
      direction: 'desc',
      expense: true
    });

    fetchUsers(group.id);
  }

  componentWillMount() {
    // decode here because we don't handle auth on the server side yet
    this.props.decodeJWT();
  }
}

export function donateToGroup(amount, frequency, currency, token) {
  const {
    notify,
    donate,
    group,
    fetchGroup,
    fetchUsers,
    fetchTransactions
  } = this.props;

  const payment = {
    stripeToken: token.id,
    email: token.email,
    amount,
    currency
  };

  if (frequency === 'monthly') {
    payment.interval = 'month';
  } else if (frequency === 'yearly') {
    payment.interval = 'year';
  }

  return donate(group.id, payment)
    .then(({json}) => {
      if (json && !json.hasFullAccount) {
        this.setState({ showUserForm: true })
      } else {
        this.setState({ showThankYouMessage: true })
      }
    })
    .then(() => fetchGroup(group.id))
    .then(() => fetchUsers(group.id))
    .then(() => {
      return fetchTransactions(group.id, {
        per_page: NUM_TRANSACTIONS_TO_SHOW,
        sort: 'createdAt',
        direction: 'desc',
        donation: true
      });
    })
    .catch((err) => notify('error', err.message));
}

export function saveNewUser() {
 const {
    users,
    updateUser,
    profileForm,
    validateDonationProfile,
    notify,
    group,
    fetchUsers
  } = this.props;

  return validateDonationProfile(profileForm.attributes)
    .then(() => updateUser(users.newUser.id, profileForm.attributes))
    .then(() => this.setState({
      showUserForm: false,
      showThankYouMessage: true
    }))
    .then(() => fetchUsers(group.id))
    .catch(({message}) => notify('error', message));
}

export default connect(mapStateToProps, {
  donate,
  notify,
  resetNotifications,
  fetchTransactions,
  fetchUsers,
  fetchGroup,
  appendProfileForm,
  updateUser,
  logout,
  validateDonationProfile,
  decodeJWT,
  appendDonationForm
})(PublicGroup);

function mapStateToProps({
  groups,
  form,
  notification,
  transactions,
  users,
  session
}) {

  const group = values(groups)[0] || {stripeAccount: {}}; // to refactor to allow only one group
  const usersByRole = group.usersByRole || {};

  /* @xdamman:
   * We should refactor this. The /api/group route should directly return
   * group.host, group.backers, group.members, group.donations, group.expenses
   */
  group.id = Number(group.id);

  group.hosts = usersByRole[roles.HOST] || [];
  group.members = usersByRole[roles.MEMBER] || [];
  group.backers = usersByRole[roles.BACKER] || [];

  group.host = group.hosts[0] || {};

  group.backersCount = group.backers.length;
  group.transactions = filterCollection(transactions, { GroupId: group.id });

  const donations = group.transactions.filter(({amount}) => amount > 0);
  const expenses = group.transactions.filter(({amount}) => amount < 0);

  return {
    group,
    notification,
    users,
    session,
    donations: take(sortBy(donations, txn => txn.createdAt).reverse(), NUM_TRANSACTIONS_TO_SHOW),
    expenses: take(sortBy(expenses, exp => exp.createdAt).reverse(), NUM_TRANSACTIONS_TO_SHOW),
    inProgress: groups.donateInProgress,
    shareUrl: window.location.href,
    profileForm: form.profile,
    donationForm: form.donation,
    showUserForm: users.showUserForm || false,
    saveInProgress: users.updateInProgress,
    isAuthenticated: session.isAuthenticated
  };
}<|endoftext|>


<commit_before>/*
* A* algorithm implementation.
*/

 function Astar(){
 };

 //Compute the best path to go to the destination.
 //Parameters description :
 // - map is a Map object it contains all data that the algorithm will use to determine if each point is available for the path destination.
 // - destinationX and destinationY is the location in the map the player has to go.
 // - forbidenArea is an array of some values that you decide the player cannot go in (the algorithm will consider these value as forbidden and will make a path avoiding those points)
 Astar.compute = function(map, destinationX, destinationY, forbiddenArea){

 }<commit_msg>Add findPath function in Astar object<commit_after>/*
* A* algorithm implementation.
*/

function Astar(){

    /*Compute the best path to go to the destination.
    *Parameters description :
    * - map is a Map object it contains all data that the algorithm will use to determine if each point is available for the path destination.
    * - startX and startY is the start location.
    * - endX and endY is the end location.
    * - forbidenArea is an array of some values. The algorithm will consider these value as forbidden and will make the path avoiding those points.
    */
    this.findPath = function(map, startX, startY, endX, endY, forbiddenArea){

    };

};<|endoftext|>


<commit_before>/*
 * Radio Paradise player
 * Copyright (c) 2014-2017 Alexey Michurin <a.michurin@gmail.com>
 * MIT License [http://www.opensource.org/licenses/mit-license.php]
 */

/*exported streams */

'use strict';

var streams = {};

streams.list =   [
  [ 'ogg-192k', {
    url: 'http://stream-tx3.radioparadise.com:80/ogg-192',
    title: 'ogg 192k',
    hidden_by_default: false
  } ],
  [ 'ogg-192k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/ogg-192',
    title: 'ogg 192k (us)',
    hidden_by_default: false
  } ],
  [ 'ogg-192k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/ogg-192',
    title: 'ogg 192k (uk)',
    hidden_by_default: false
  } ],
  [ 'ogg-192k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/ogg-192',
    title: 'ogg 192k (ru)',
    hidden_by_default: true
  } ],
  [ 'ogg-96k', {
    url: 'http://stream-tx3.radioparadise.com:80/ogg-96',
    title: 'ogg 96k',
    hidden_by_default: false
  } ],
  [ 'ogg-96k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/ogg-96',
    title: 'ogg 96k (us)',
    hidden_by_default: false
  } ],
  [ 'ogg-96k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/ogg-96',
    title: 'ogg 96k (uk)',
    hidden_by_default: false
  } ],
  [ 'ogg-96k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/ogg-96',
    title: 'ogg 96k (ru)',
    hidden_by_default: true
  } ],
  [ 'ogg-32k', {
    url: 'http://stream-tx3.radioparadise.com:80/ogg-32',
    title: 'ogg 32k',
    hidden_by_default: false
  } ],
  [ 'ogg-32k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/ogg-32',
    title: 'ogg 32k (us)',
    hidden_by_default: true
  } ],
  [ 'ogg-32k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/ogg-32',
    title: 'ogg 32k (uk)',
    hidden_by_default: true
  } ],
  [ 'mp3-192k', {
    url: 'http://stream-tx3.radioparadise.com:80/mp3-192',
    title: 'mp3 192k',
    hidden_by_default: true
  } ],
  [ 'mp3-192k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/mp3-192',
    title: 'mp3 192k (us)',
    hidden_by_default: true
  } ],
  [ 'mp3-192k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/mp3-192',
    title: 'mp3 192k (uk)',
    hidden_by_default: true
  } ],
  [ 'mp3-192k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/mp3-192',
    title: 'mp3 192k (ru)',
    hidden_by_default: true
  } ],
  [ 'mp3-128k', {
    url: 'http://stream-tx3.radioparadise.com:80/mp3-128',
    title: 'mp3 128k',
    hidden_by_default: true
  } ],
  [ 'mp3-128k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/mp3-128',
    title: 'mp3 128k (us)',
    hidden_by_default: true
  } ],
  [ 'mp3-128k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/mp3-128',
    title: 'mp3 128k (uk)',
    hidden_by_default: true
  } ],
  [ 'mp3-128k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/mp3-128',
    title: 'mp3 128k (ru)',
    hidden_by_default: true
  } ],
  [ 'mp3-32k', {
    url: 'http://stream-tx3.radioparadise.com:80/mp3-32',
    title: 'mp3 32k',
    hidden_by_default: true
  } ],
  [ 'mp3-32k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/mp3-32',
    title: 'mp3 32k (us)',
    hidden_by_default: true
  } ],
  [ 'mp3-32k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/mp3-32',
    title: 'mp3 32k (uk)',
    hidden_by_default: true
  } ] ];

streams.map = (function (x) {
  var i, v, d = {};
  for (i = 0; i < x.length; ++i) {
    v = x[i];
    d[v[0]] = v[1];
  }
  return d;
}(streams.list));

streams.def = {
  stream: 'ogg-96k',
  hidden: (function (x) {
    // used only as generator in storage.js
    return function () {
      var i, v, r = {};
      for (i = 0; i < x.length; ++i) {
        v = x[i];
        if (v[1].hidden_by_default) {
          r[v[0]] = true;
        }
      }
      return r;
    };
  }(streams.list))
};
<commit_msg>Add AAC streams to stream list; disabled by default<commit_after>/*
 * Radio Paradise player
 * Copyright (c) 2014-2017 Alexey Michurin <a.michurin@gmail.com>
 * MIT License [http://www.opensource.org/licenses/mit-license.php]
 */

/*exported streams */

'use strict';

var streams = {};

streams.list =   [
  [ 'ogg-192k', {
    url: 'http://stream-tx3.radioparadise.com:80/ogg-192',
    title: 'ogg 192k',
    hidden_by_default: false
  } ],
  [ 'ogg-192k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/ogg-192',
    title: 'ogg 192k (us)',
    hidden_by_default: false
  } ],
  [ 'ogg-192k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/ogg-192',
    title: 'ogg 192k (uk)',
    hidden_by_default: false
  } ],
  [ 'ogg-192k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/ogg-192',
    title: 'ogg 192k (ru)',
    hidden_by_default: true
  } ],
  [ 'ogg-96k', {
    url: 'http://stream-tx3.radioparadise.com:80/ogg-96',
    title: 'ogg 96k',
    hidden_by_default: false
  } ],
  [ 'ogg-96k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/ogg-96',
    title: 'ogg 96k (us)',
    hidden_by_default: false
  } ],
  [ 'ogg-96k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/ogg-96',
    title: 'ogg 96k (uk)',
    hidden_by_default: false
  } ],
  [ 'ogg-96k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/ogg-96',
    title: 'ogg 96k (ru)',
    hidden_by_default: true
  } ],
  [ 'ogg-32k', {
    url: 'http://stream-tx3.radioparadise.com:80/ogg-32',
    title: 'ogg 32k',
    hidden_by_default: false
  } ],
  [ 'ogg-32k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/ogg-32',
    title: 'ogg 32k (us)',
    hidden_by_default: true
  } ],
  [ 'ogg-32k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/ogg-32',
    title: 'ogg 32k (uk)',
    hidden_by_default: true
  } ],
  [ 'mp3-192k', {
    url: 'http://stream-tx3.radioparadise.com:80/mp3-192',
    title: 'mp3 192k',
    hidden_by_default: true
  } ],
  [ 'mp3-192k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/mp3-192',
    title: 'mp3 192k (us)',
    hidden_by_default: true
  } ],
  [ 'mp3-192k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/mp3-192',
    title: 'mp3 192k (uk)',
    hidden_by_default: true
  } ],
  [ 'mp3-192k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/mp3-192',
    title: 'mp3 192k (ru)',
    hidden_by_default: true
  } ],
  [ 'mp3-128k', {
    url: 'http://stream-tx3.radioparadise.com:80/mp3-128',
    title: 'mp3 128k',
    hidden_by_default: true
  } ],
  [ 'mp3-128k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/mp3-128',
    title: 'mp3 128k (us)',
    hidden_by_default: true
  } ],
  [ 'mp3-128k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/mp3-128',
    title: 'mp3 128k (uk)',
    hidden_by_default: true
  } ],
  [ 'mp3-128k-ru', {
    url: 'http://stream-ru1.radioparadise.com:9000/mp3-128',
    title: 'mp3 128k (ru)',
    hidden_by_default: true
  } ],
  [ 'mp3-32k', {
    url: 'http://stream-tx3.radioparadise.com:80/mp3-32',
    title: 'mp3 32k',
    hidden_by_default: true
  } ],
  [ 'mp3-32k-us', {
    url: 'http://stream-dc1.radioparadise.com:80/mp3-32',
    title: 'mp3 32k (us)',
    hidden_by_default: true
  } ],
  [ 'mp3-32k-uk', {
    url: 'http://stream-uk1.radioparadise.com:80/mp3-32',
    title: 'mp3 32k (uk)',
    hidden_by_default: true
  } ],

  [
    'aac-320k',
    {
      hidden_by_default: true,
      title: 'aac 320k (us-tx)',
      url: 'http://stream-tx3.radioparadise.com:80/aac-320'
    }
  ],
  [
    'aac-320k-us',
    {
      hidden_by_default: true,
      title: 'aac 320k (us-dc)',
      url: 'http://stream-dc1.radioparadise.com:80/aac-320'
    }
  ],
  [
    'aac-320k-uk',
    {
      hidden_by_default: true,
      title: 'aac 320k (uk)',
      url: 'http://stream-uk1.radioparadise.com:80/aac-320'
    }
  ],
  [
    'aac-320k-ru',
    {
      hidden_by_default: true,
      title: 'aac 320k (ru)',
      url: 'http://stream-ru1.radioparadise.com:9000/aac-320'
    }
  ],
  [
    'aac-128k',
    {
      hidden_by_default: true,
      title: 'aac 128k (us-tx)',
      url: 'http://stream-tx3.radioparadise.com:80/aac-128'
    }
  ],
  [
    'aac-128k-us',
    {
      hidden_by_default: true,
      title: 'aac 128k (us-dc)',
      url: 'http://stream-dc1.radioparadise.com:80/aac-128'
    }
  ],
  [
    'aac-128k-uk',
    {
      hidden_by_default: true,
      title: 'aac 128k (uk)',
      url: 'http://stream-uk1.radioparadise.com:80/aac-128'
    }
  ],
  [
    'aac-128k-ru',
    {
      hidden_by_default: true,
      title: 'aac 128k (ru)',
      url: 'http://stream-ru1.radioparadise.com:9000/aac-128'
    }
  ],
  [
    'aac-64k',
    {
      hidden_by_default: true,
      title: 'aac 64k (us-tx)',
      url: 'http://stream-tx3.radioparadise.com:80/aac-64'
    }
  ],
  [
    'aac-64k-us',
    {
      hidden_by_default: true,
      title: 'aac 64k (us-dc)',
      url: 'http://stream-dc1.radioparadise.com:80/aac-64'
    }
  ],
  [
    'aac-64k-uk',
    {
      hidden_by_default: true,
      title: 'aac 64k (uk)',
      url: 'http://stream-uk1.radioparadise.com:80/aac-64'
    }
  ],
  [
    'aac-64k-ru',
    {
      hidden_by_default: true,
      title: 'aac 64k (ru)',
      url: 'http://stream-ru1.radioparadise.com:9000/aac-64'
    }
  ],
  [
    'aac-32k',
    {
      hidden_by_default: true,
      title: 'aac 32k (us-tx)',
      url: 'http://stream-tx3.radioparadise.com:80/aac-32'
    }
  ],
  [
    'aac-32k-us',
    {
      hidden_by_default: true,
      title: 'aac 32k (us-dc)',
      url: 'http://stream-dc1.radioparadise.com:80/aac-32'
    }
  ],
  [
    'aac-32k-uk',
    {
      hidden_by_default: true,
      title: 'aac 32k (uk)',
      url: 'http://stream-uk1.radioparadise.com:80/aac-32'
    }
  ],
  [
    'aac-32k-ru',
    {
      hidden_by_default: true,
      title: 'aac 32k (ru)',
      url: 'http://stream-ru1.radioparadise.com:9000/aac-32'
    }
  ],
  [
    'aac-24k',
    {
      hidden_by_default: true,
      title: 'aac 24k (us-tx)',
      url: 'http://stream-tx3.radioparadise.com:80/aac-24'
    }
  ],
  [
    'aac-24k-us',
    {
      hidden_by_default: true,
      title: 'aac 24k (us-dc)',
      url: 'http://stream-dc1.radioparadise.com:80/aac-24'
    }
  ],
  [
    'aac-24k-uk',
    {
      hidden_by_default: true,
      title: 'aac 24k (uk)',
      url: 'http://stream-uk1.radioparadise.com:80/aac-24'
    }
  ],
  [
    'aac-24k-ru',
    {
      hidden_by_default: true,
      title: 'aac 24k (ru)',
      url: 'http://stream-ru1.radioparadise.com:9000/aac-24'
    }
  ]

];

streams.map = (function (x) {
  var i, v, d = {};
  for (i = 0; i < x.length; ++i) {
    v = x[i];
    d[v[0]] = v[1];
  }
  return d;
}(streams.list));

streams.def = {
  stream: 'ogg-96k',
  hidden: (function (x) {
    // used only as generator in storage.js
    return function () {
      var i, v, r = {};
      for (i = 0; i < x.length; ++i) {
        v = x[i];
        if (v[1].hidden_by_default) {
          r[v[0]] = true;
        }
      }
      return r;
    };
  }(streams.list))
};
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file contains type definitions for the viewer plugin. It is used only
// with JSCompiler to verify the type-correctness of our code.

/** @suppress {duplicate} */
var remoting = remoting || {};

/** @constructor
 *  @extends HTMLElement
 */
remoting.ViewerPlugin = function() {};

/** @param {string} iq The Iq stanza received from the host. */
remoting.ViewerPlugin.prototype.onIq = function(iq) {};

/** @param {boolean} scale True to enable scaling, false to disable. */
remoting.ViewerPlugin.prototype.setScaleToFit = function(scale) {};

/** Release all keys currently pressed by this client. */
remoting.ViewerPlugin.prototype.releaseAllKeys = function() {};

/**
 * @param {string} hostJid The host's JID.
 * @param {string} hostPublicKey The host's public key.
 * @param {string} clientJid The client's JID.
 * @param {string} sharedSecret The access code for IT2Me or the
 *     PIN for Me2Me.
 * @param {string=} authenticationMethods Comma-separated list of
 *     authentication methods the client should attempt to use.
 * @param {string=} authenticationTag A host-specific tag to mix into
 *     authentication hashes.
 * @return {void} Nothing.
*/
remoting.ViewerPlugin.prototype.connect =
    function(hostJid, hostPublicKey, clientJid, sharedSecret,
             authenticationMethod, authenticationTag) {};

/** @type {function(number, number): void} State change callback function. */
remoting.ViewerPlugin.prototype.connectionInfoUpdate;

/** @type {number} */ remoting.ViewerPlugin.prototype.apiMinVersion;
/** @type {number} */ remoting.ViewerPlugin.prototype.apiVersion;

/** @type {number} */ remoting.ViewerPlugin.prototype.desktopHeight;
/** @type {number} */ remoting.ViewerPlugin.prototype.desktopWidth;

/** @type {number} */ remoting.ViewerPlugin.prototype.status;
/** @type {number} */ remoting.ViewerPlugin.prototype.error;

/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_UNKNOWN;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_CONNECTING;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_INITIALIZING;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_CONNECTED;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_CLOSED;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_FAILED;

/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_NONE;
/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_HOST_IS_OFFLINE;
/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_SESSION_REJECTED;
/** @type {number} */
    remoting.ViewerPlugin.prototype.ERROR_INCOMPATIBLE_PROTOCOL;
/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_NETWORK_FAILURE;

/** @type {number} */ remoting.ViewerPlugin.prototype.videoBandwidth;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoCaptureLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoDecodeLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoEncodeLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoFrameRate;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoRenderLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.roundTripLatency;
<commit_msg>Chromoting: Fix jscompiler warning<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file contains type definitions for the viewer plugin. It is used only
// with JSCompiler to verify the type-correctness of our code.

/** @suppress {duplicate} */
var remoting = remoting || {};

/** @constructor
 *  @extends HTMLElement
 */
remoting.ViewerPlugin = function() {};

/** @param {string} iq The Iq stanza received from the host. */
remoting.ViewerPlugin.prototype.onIq = function(iq) {};

/** @param {boolean} scale True to enable scaling, false to disable. */
remoting.ViewerPlugin.prototype.setScaleToFit = function(scale) {};

/** Release all keys currently pressed by this client. */
remoting.ViewerPlugin.prototype.releaseAllKeys = function() {};

/**
 * @param {string} hostJid The host's JID.
 * @param {string} hostPublicKey The host's public key.
 * @param {string} clientJid The client's JID.
 * @param {string} sharedSecret The access code for IT2Me or the
 *     PIN for Me2Me.
 * @param {string=} authenticationMethod Comma-separated list of
 *     authentication methods the client should attempt to use.
 * @param {string=} authenticationTag A host-specific tag to mix into
 *     authentication hashes.
 * @return {void} Nothing.
*/
remoting.ViewerPlugin.prototype.connect =
    function(hostJid, hostPublicKey, clientJid, sharedSecret,
             authenticationMethod, authenticationTag) {};

/** @type {function(number, number): void} State change callback function. */
remoting.ViewerPlugin.prototype.connectionInfoUpdate;

/** @type {number} */ remoting.ViewerPlugin.prototype.apiMinVersion;
/** @type {number} */ remoting.ViewerPlugin.prototype.apiVersion;

/** @type {number} */ remoting.ViewerPlugin.prototype.desktopHeight;
/** @type {number} */ remoting.ViewerPlugin.prototype.desktopWidth;

/** @type {number} */ remoting.ViewerPlugin.prototype.status;
/** @type {number} */ remoting.ViewerPlugin.prototype.error;

/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_UNKNOWN;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_CONNECTING;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_INITIALIZING;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_CONNECTED;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_CLOSED;
/** @type {number} */ remoting.ViewerPlugin.prototype.STATUS_FAILED;

/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_NONE;
/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_HOST_IS_OFFLINE;
/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_SESSION_REJECTED;
/** @type {number} */
    remoting.ViewerPlugin.prototype.ERROR_INCOMPATIBLE_PROTOCOL;
/** @type {number} */ remoting.ViewerPlugin.prototype.ERROR_NETWORK_FAILURE;

/** @type {number} */ remoting.ViewerPlugin.prototype.videoBandwidth;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoCaptureLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoDecodeLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoEncodeLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoFrameRate;
/** @type {number} */ remoting.ViewerPlugin.prototype.videoRenderLatency;
/** @type {number} */ remoting.ViewerPlugin.prototype.roundTripLatency;
<|endoftext|>