<commit_before>/* -*- coding: utf-8 -*-

Copyright (c) 2016 Ministerio de Fomento
                   Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>,
           Daniel Jiménez González <dani@ietcc.csic.es>
*/

import { compute_balance, weighted_energy,
         readenergystring, readfactors,
         ep2string } from './energycalculations.js';
import * as fs from 'fs';
import * as path from 'path';

const TESTFP = readfactors(`vector, fuente, uso, step, ren, nren

ELECTRICIDAD, grid, input, A, 0.5, 2.0

ELECTRICIDAD, INSITU, input,   A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, B, 0.5, 2.0
ELECTRICIDAD, INSITU, to_nEPB, B, 0.5, 2.0

GASNATURAL, grid, input,A, 0.0, 1.1

BIOCARBURANTE, grid, input, A, 1.1, 0.1

MEDIOAMBIENTE, INSITU, input,  A, 1.0, 0.0

ELECTRICIDAD, COGENERACION, input,   A, 0.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, B, 0.5, 2.0
ELECTRICIDAD, COGENERACION, to_nEPB, B, 0.5, 2.0`);

const CTEFP = readfactors(`vector, fuente, uso, step, ren, nren
#valores de la propuesta del documento reconocido del IDAE de 03/02/2014, página 14

ELECTRICIDAD, grid, input, A, 0.341, 2.082

ELECTRICIDADBALEARES, grid, input, A, 0.094, 3.060
ELECTRICIDADCANARIAS, grid, input, A, 0.059, 3.058
ELECTRICIDADCEUTAMELILLA, grid, input, A, 0.066, 2.759

ELECTRICIDAD, INSITU, input,   A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, B, 0.5, 2.0
ELECTRICIDAD, INSITU, to_nEPB, B, 0.5, 2.0

GASOLEO, grid, input, A, 0.003, 1.179

GLP, grid, input, A, 0.03, 1.201

GASNATURAL, grid, input,A, 0.005, 1.190

CARBON, grid, input, A, 0.002, 1.082

BIOCARBURANTE, grid, input, A, 1.028, 0.085 #BIOMASA DENSIFICADA (PELLETS)

MEDIOAMBIENTE, INSITU, input,  A, 1.0, 0.0

ELECTRICIDAD, COGENERACION, input,   A, 0.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, B, 0.5, 2.0
ELECTRICIDAD, COGENERACION, to_nEPB, B, 0.5, 2.0`);

// data from ejemplo3PVBdC_normativo
const ENERGYDATALIST = [
  { values: [9.67, 7.74, 4.84, 4.35, 2.42, 2.9, 3.87, 3.39, 2.42, 3.87, 5.8, 7.74],
    carrier: 'ELECTRICIDAD', ctype: 'CONSUMO', originoruse: 'EPB' },
  { values: [1.13, 1.42, 1.99, 2.84, 4.82, 5.39, 5.67, 5.11, 4.54, 3.40, 2.27, 1.42],
    carrier: 'ELECTRICIDAD', ctype: 'PRODUCCION', originoruse: 'INSITU' },
  { values: [21.48, 17.18, 10.74, 9.66, 5.37, 6.44, 8.59, 7.52, 5.37, 8.59, 12.89, 17.18],
    carrier: 'MEDIOAMBIENTE', ctype: 'CONSUMO', originoruse: 'EPB' },
  { values: [21.48, 17.18, 10.74, 9.66, 5.37, 6.44, 8.59, 7.52, 5.37, 8.59, 12.89, 17.18],
    carrier: 'MEDIOAMBIENTE', ctype: 'PRODUCCION', originoruse: 'INSITU' }
];

const TESTKRDEL = 1.0;
const TESTKEXP = 1.0;

// Utilities ------------------------------------------------------------

const myround = (num, ndigits = 2) => Math.round(num * Math.pow(10, ndigits)) / Math.pow(10, ndigits);

// Check that result is within valid range
// isok is true if result must match to succeed
function check(casename, EPB, result, shouldpass = true) {
  const ep = EPB.EP;
  const reserr = Math.sqrt(Math.pow(ep.ren - result[0], 2)
                           + Math.pow((ep.nren - result[1]), 2));
  const gotvalue = myround(result[0] + result[1]);
  const expectedvalue = myround(ep.ren + ep.nren);
  let outstr = `${ casename } (${ EPB.path })`;
  if ((shouldpass && reserr > 2.0) || (!shouldpass && !(reserr > 2.0))) {
    outstr = `ERROR - ${ outstr }\n`
             + `-- Found: ${ gotvalue.toFixed(1) } = `
             + `(ren: ${myround(result[0])} + nren: ${myround(result[1])})\n`
             + `-- Expected: ${ expectedvalue.toFixed(1) }, `
             + `(ren: ${myround(ep.ren)} + nren: ${myround(ep.nren)})\n`
             + `-- (ren, nren) residual: ${ reserr }\n`
             + `${ ep2string(EPB) }`;
  } else {
    outstr = `OK - ${ outstr }`;
  }
  console.log(outstr);
}

// Compute primary energy (weighted energy) from data in filename
function epfromfile(filename, krdel, kexp, fp) {
  const datapath = path.resolve(__dirname, 'examples', filename);
  const datastring = fs.readFileSync(datapath, 'utf-8');
  const datalist = readenergystring(datastring).components;
  const balance = compute_balance(datalist, krdel);
  return { ...weighted_energy(balance, fp, kexp), path: filename };
}

// Compute primary energy (weighted energy) from datalist
function epfromdata(datalist, krdel, kexp, fp) {
  const balance = compute_balance(datalist, krdel);
  return { ...weighted_energy(balance, fp, kexp), path: 'data' };
}

// Tests ----------------------------------------------------------
console.log("*** Ejemplos ISO/TR 52000-2:2016 ***");

check('ejemploJ1_base',
      epfromfile('ejemploJ1_base.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [50.0, 200.0]);

check('ejemploJ1_basePV',
      epfromfile('ejemploJ1_basePV.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [75.0, 100.0]);

check('ejemploJ1_basePVexcess',
      epfromfile('ejemploJ1_basePVexcess.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [120, -80.0]);

console.log("*** Ejemplos FprEN 15603:2014 ***");

check('ejemplo1base',
      epfromfile('ejemplo1base.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [50.0, 200.0]);

check('ejemplo1base_fail',
      epfromfile('ejemplo1base.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [53.0, 200.0], false);

check('ejemplo1base_normativo',
      epfromfile('ejemplo1base.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [34.1, 208.20]);

check('ejemplo1PV',
      epfromfile('ejemplo1PV.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [75.0, 100.0]);

check('ejemplo1PV_normativo',
      epfromfile('ejemplo1PV.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [67.1, 104.1]);

check('ejemplo1xPV',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [120.0, -80.0]);

check('ejemplo1xPV_normativo',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [120.0, -80.0]);

check('ejemplo1xPVk0',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, 0.0, TESTFP),
      [100.0, 0.0]);

check('ejemplo1xPVk0_normativo',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, 0.0, CTEFP),
      [100.0, 0.0]);

check('ejemplo2xPVgas',
      epfromfile('ejemplo2xPVgas.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [30.0, 169.0]);

check('ejemplo2xPVgas_normativo',
      epfromfile('ejemplo2xPVgas.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [30.9, 186.1]);

check('ejemplo3PVBdC',
      epfromfile('ejemplo3PVBdC.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [180.0, 38.0]);

check('ejemplo3PVBdC_normativo',
      epfromfile('ejemplo3PVBdC.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [177.5, 39.6]);

check('ejemplo4cgnfosil',
      epfromfile('ejemplo4cgnfosil.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [-14.0, 227.0]);

check('ejemplo4cgnfosil_normativo',
      epfromfile('ejemplo4cgnfosil.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [-12.7, 251]);

check('ejemplo5cgnbiogas',
      epfromfile('ejemplo5cgnbiogas.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [159.0, 69.0]);

check('ejemplo5cgnbiogas_normativo',
      epfromfile('ejemplo5cgnbiogas.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [148.9, 76.4]);

check('ejemplo6K3',
      epfromfile('ejemplo6K3.csv', TESTKRDEL, TESTKEXP, TESTFP),
      [1385.5, -662]);

check('ejemplo6K3_normativo',
      epfromfile('ejemplo6K3.csv', TESTKRDEL, TESTKEXP, CTEFP),
      [1385.5, -662]);

check('ejemplo3PVBdC_normativo_from_data',
      epfromdata(ENERGYDATALIST, TESTKRDEL, TESTKEXP, CTEFP),
      [177.5, 39.6]);

// ---------------------------------------------------------------

// console.log(TESTFP);
// console.log(CTEFP);
<commit_msg>tests: modifica formato de comprobación<commit_after>/* -*- coding: utf-8 -*-

Copyright (c) 2016 Ministerio de Fomento
                   Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>,
           Daniel Jiménez González <dani@ietcc.csic.es>
*/

import { compute_balance, weighted_energy,
         readenergystring, readfactors,
         ep2string } from './energycalculations.js';
import * as fs from 'fs';
import * as path from 'path';

const TESTFP = readfactors(`vector, fuente, uso, step, ren, nren

ELECTRICIDAD, grid, input, A, 0.5, 2.0

ELECTRICIDAD, INSITU, input,   A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, B, 0.5, 2.0
ELECTRICIDAD, INSITU, to_nEPB, B, 0.5, 2.0

GASNATURAL, grid, input,A, 0.0, 1.1

BIOCARBURANTE, grid, input, A, 1.1, 0.1

MEDIOAMBIENTE, INSITU, input,  A, 1.0, 0.0

ELECTRICIDAD, COGENERACION, input,   A, 0.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, B, 0.5, 2.0
ELECTRICIDAD, COGENERACION, to_nEPB, B, 0.5, 2.0`);

const CTEFP = readfactors(`vector, fuente, uso, step, ren, nren
#valores de la propuesta del documento reconocido del IDAE de 03/02/2014, página 14

ELECTRICIDAD, grid, input, A, 0.341, 2.082

ELECTRICIDADBALEARES, grid, input, A, 0.094, 3.060
ELECTRICIDADCANARIAS, grid, input, A, 0.059, 3.058
ELECTRICIDADCEUTAMELILLA, grid, input, A, 0.066, 2.759

ELECTRICIDAD, INSITU, input,   A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, INSITU, to_grid, B, 0.5, 2.0
ELECTRICIDAD, INSITU, to_nEPB, B, 0.5, 2.0

GASOLEO, grid, input, A, 0.003, 1.179

GLP, grid, input, A, 0.03, 1.201

GASNATURAL, grid, input,A, 0.005, 1.190

CARBON, grid, input, A, 0.002, 1.082

BIOCARBURANTE, grid, input, A, 1.028, 0.085 #BIOMASA DENSIFICADA (PELLETS)

MEDIOAMBIENTE, INSITU, input,  A, 1.0, 0.0

ELECTRICIDAD, COGENERACION, input,   A, 0.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_nEPB, A, 1.0, 0.0
ELECTRICIDAD, COGENERACION, to_grid, B, 0.5, 2.0
ELECTRICIDAD, COGENERACION, to_nEPB, B, 0.5, 2.0`);

// data from ejemplo3PVBdC_normativo
const ENERGYDATALIST = [
  { values: [9.67, 7.74, 4.84, 4.35, 2.42, 2.9, 3.87, 3.39, 2.42, 3.87, 5.8, 7.74],
    carrier: 'ELECTRICIDAD', ctype: 'CONSUMO', originoruse: 'EPB' },
  { values: [1.13, 1.42, 1.99, 2.84, 4.82, 5.39, 5.67, 5.11, 4.54, 3.40, 2.27, 1.42],
    carrier: 'ELECTRICIDAD', ctype: 'PRODUCCION', originoruse: 'INSITU' },
  { values: [21.48, 17.18, 10.74, 9.66, 5.37, 6.44, 8.59, 7.52, 5.37, 8.59, 12.89, 17.18],
    carrier: 'MEDIOAMBIENTE', ctype: 'CONSUMO', originoruse: 'EPB' },
  { values: [21.48, 17.18, 10.74, 9.66, 5.37, 6.44, 8.59, 7.52, 5.37, 8.59, 12.89, 17.18],
    carrier: 'MEDIOAMBIENTE', ctype: 'PRODUCCION', originoruse: 'INSITU' }
];

const TESTKRDEL = 1.0;
const TESTKEXP = 1.0;

// Utilities ------------------------------------------------------------

const myround = (num, ndigits = 2) => Math.round(num * Math.pow(10, ndigits)) / Math.pow(10, ndigits);

// Check that result is within valid range
// isok is true if result must match to succeed
function check(casename, EPB, result, shouldpass = true) {
  const ep = EPB.EP;
  const resB = result.EP;
  const reserr = Math.sqrt(Math.pow(ep.ren - resB.ren, 2)
    + Math.pow((ep.nren - resB.nren), 2));

  let outstr;
  if ((shouldpass && reserr > 2.0) || (!shouldpass && !(reserr > 2.0))) {
    outstr = `ERROR - ${casename} (${EPB.path})\n`
             + `-- Found: ${myround(resB.ren + resB.nren).toFixed(1)} = `
             + `(ren: ${myround(resB.ren)} + nren: ${myround(resB.nren)})\n`
             + `-- Expected: ${myround(ep.ren + ep.nren).toFixed(1)}, `
             + `(ren: ${myround(ep.ren)} + nren: ${myround(ep.nren)})\n`
             + `-- (ren, nren) residual: ${reserr}\n`
             + `${ep2string(EPB)}\n${JSON.stringify(EPB, null, 4)}`;
  } else {
    outstr = `OK - ${casename} (${EPB.path})`;
  }
  console.log(outstr);
}

// Compute primary energy (weighted energy) from data in filename
function epfromfile(filename, krdel, kexp, fp) {
  const datapath = path.resolve(__dirname, 'examples', filename);
  const datastring = fs.readFileSync(datapath, 'utf-8');
  const datalist = readenergystring(datastring).components;
  const balance = compute_balance(datalist, krdel);
  return { ...weighted_energy(balance, fp, kexp), path: filename };
}

// Compute primary energy (weighted energy) from datalist
function epfromdata(datalist, krdel, kexp, fp) {
  const balance = compute_balance(datalist, krdel);
  return { ...weighted_energy(balance, fp, kexp), path: 'data' };
}

// Tests ----------------------------------------------------------
console.log("*** Ejemplos ISO/TR 52000-2:2016 ***");

check('ejemploJ1_base',
      epfromfile('ejemploJ1_base.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 50.0, nren: 200.0 } });

check('ejemploJ1_basePV',
      epfromfile('ejemploJ1_basePV.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 75.0, nren: 100.0 } });

check('ejemploJ1_basePVexcess',
      epfromfile('ejemploJ1_basePVexcess.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 120, nren: -80.0 } });

console.log("*** Ejemplos FprEN 15603:2014 ***");

check('ejemplo1base',
      epfromfile('ejemplo1base.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 50.0, nren: 200.0 } });

check('ejemplo1base_fail',
      epfromfile('ejemplo1base.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 53.0, nren: 200.0 } }, false);

check('ejemplo1base_normativo',
      epfromfile('ejemplo1base.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 34.1, nren: 208.20 } });

check('ejemplo1PV',
      epfromfile('ejemplo1PV.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 75.0, nren: 100.0 } });

check('ejemplo1PV_normativo',
      epfromfile('ejemplo1PV.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 67.1, nren: 104.1 } });

check('ejemplo1xPV',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 120.0, nren: -80.0 } });

check('ejemplo1xPV_normativo',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 120.0, nren: -80.0 } });

check('ejemplo1xPVk0',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, 0.0, TESTFP),
      { EP: { ren: 100.0, nren: 0.0 } });

check('ejemplo1xPVk0_normativo',
      epfromfile('ejemplo1xPV.csv', TESTKRDEL, 0.0, CTEFP),
      { EP: { ren: 100.0, nren: 0.0 } });

check('ejemplo2xPVgas',
      epfromfile('ejemplo2xPVgas.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 30.0, nren: 169.0 } });

check('ejemplo2xPVgas_normativo',
      epfromfile('ejemplo2xPVgas.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 30.9, nren: 186.1 } });

check('ejemplo3PVBdC',
      epfromfile('ejemplo3PVBdC.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 180.0, nren: 38.0 } });

check('ejemplo3PVBdC_normativo',
      epfromfile('ejemplo3PVBdC.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 177.5, nren: 39.6 } });

check('ejemplo4cgnfosil',
      epfromfile('ejemplo4cgnfosil.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: -14.0, nren: 227.0 } });

check('ejemplo4cgnfosil_normativo',
      epfromfile('ejemplo4cgnfosil.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: -12.7, nren: 251 } });

check('ejemplo5cgnbiogas',
      epfromfile('ejemplo5cgnbiogas.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 159.0, nren: 69.0 } });

check('ejemplo5cgnbiogas_normativo',
      epfromfile('ejemplo5cgnbiogas.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 148.9, nren: 76.4 } });

check('ejemplo6K3',
      epfromfile('ejemplo6K3.csv', TESTKRDEL, TESTKEXP, TESTFP),
      { EP: { ren: 1385.5, nren: -662 } });

check('ejemplo6K3_normativo',
      epfromfile('ejemplo6K3.csv', TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 1385.5, nren: -662 } });

check('ejemplo3PVBdC_normativo_from_data',
      epfromdata(ENERGYDATALIST, TESTKRDEL, TESTKEXP, CTEFP),
      { EP: { ren: 177.5, nren: 39.6 } });

// ---------------------------------------------------------------

// console.log(TESTFP);
// console.log(CTEFP);
<|endoftext|>


<commit_before>window.astreetview = {};

astreetview.id = "astreetview";
astreetview.name = "Awesome Street-View (WIP)";
astreetview.stylesheet = "./stylesheets/themes/astreetview.css";

astreetview.locations = [];
astreetview.refreshLocations_cb = null;

astreetview.refreshLocations = function(data, cb) {
  if (!data) {
    astreetview.refreshLocations_cb = cb;
    $.ajax({
      url: "https://peaceful-shelf-4149.herokuapp.com/?callback=astreetview.refreshLocations&url=https://raw.githubusercontent.com/Jam3/awesome-streetview/master/locations.json?callback=?",
      type: "GET",
      cache: true,
      dataType: "jsonp text json",
      crossDomain: true,
      jsonp: false,
      jsonpCallback: "astreetview.refreshLocations"
    });
    return;
  }

  astreetview.locations = data;
  if (astreetview.refreshLocations_cb) {astreetview.refreshLocations_cb(data);};
  astreetview.refreshLocations_cb = null;
}

astreetview.showRandomLocation = function(locations) {
  if (!locations) {
    astreetview.refreshLocations(null, function(data) {astreetview.showRandomLocation(data);});
    return;
  }

  var location = locations[Math.floor(Math.random() * (locations.length - 1))];

  var latlng = new google.maps.LatLng(location[0], location[1]);
  var mapOptions = {
    center: latlng,
    zoom: 14
  };
  var map = new google.maps.Map($("#astreetview-pano")[0], mapOptions);
  var panoramaOptions = {
    position: latlng,
    pov: {
      heading: 0,
      pitch: 0
    }
  };
  var panorama = new google.maps.StreetViewPanorama($("#astreetview-pano")[0], panoramaOptions);
  map.setStreetView(panorama);
}

astreetview.init = function() {
  $(".header").append($("

"));

  astreetview.showRandomLocation();
};

astreetview.unload = function() {
  $(".theme-astreetview").remove();
};

window.themes = window.themes || [];
window.themes.push(astreetview);
<commit_msg>Add awesome-streetview JSONP proxy timeout<commit_after>window.astreetview = {};

astreetview.id = "astreetview";
astreetview.name = "Awesome Street-View (WIP)";
astreetview.stylesheet = "./stylesheets/themes/astreetview.css";

astreetview.locations = [];
astreetview.refreshLocations_cb = null;

astreetview.refreshLocations = function(data, cb) {
  if (!data) {
    astreetview.refreshLocations_cb = cb;
    setTimeout(function() {if (astreetview.refreshLocations_cb == cb) {astreetview.refreshLocations(data, cb);}}, 2500);
    $.ajax({
      url: "https://peaceful-shelf-4149.herokuapp.com/?callback=astreetview.refreshLocations&url=https://raw.githubusercontent.com/Jam3/awesome-streetview/master/locations.json?callback=?",
      type: "GET",
      cache: true,
      dataType: "jsonp text json",
      crossDomain: true,
      jsonp: false,
      jsonpCallback: "astreetview.refreshLocations"
    });
    return;
  }

  astreetview.locations = data;
  if (astreetview.refreshLocations_cb) {astreetview.refreshLocations_cb(data);};
  astreetview.refreshLocations_cb = null;
}

astreetview.showRandomLocation = function(locations) {
  if (!locations) {
    astreetview.refreshLocations(null, function(data) {astreetview.showRandomLocation(data);});
    return;
  }

  var location = locations[Math.floor(Math.random() * (locations.length - 1))];

  var latlng = new google.maps.LatLng(location[0], location[1]);
  var mapOptions = {
    center: latlng,
    zoom: 14
  };
  var map = new google.maps.Map($("#astreetview-pano")[0], mapOptions);
  var panoramaOptions = {
    position: latlng,
    pov: {
      heading: 0,
      pitch: 0
    }
  };
  var panorama = new google.maps.StreetViewPanorama($("#astreetview-pano")[0], panoramaOptions);
  map.setStreetView(panorama);
}

astreetview.init = function() {
  $(".header").append($("

"));

  astreetview.showRandomLocation();
};

astreetview.unload = function() {
  $(".theme-astreetview").remove();
};

window.themes = window.themes || [];
window.themes.push(astreetview);
<|endoftext|>


<commit_before>import Eventable  from './Eventable';
import defaults   from './defaultOptions';
import * as utils from '@interactjs/utils';
import domObjects from '@interactjs/utils/domObjects';

import InteractEvent    from './InteractEvent';
import InteractableBase from './Interactable';

const {
  win,
  browser,
  raf,
  Signals,
  events,
} = utils;

export function createScope () {
  const scope = {
    Signals,
    signals: new Signals(),
    browser,
    events,
    utils,
    defaults: utils.clone(defaults),
    Eventable,

    InteractEvent: InteractEvent,
    Interactable: class Interactable extends InteractableBase {
      get _defaults () { return scope.defaults; }

      set (options) {
        super.set(options);

        scope.signals.fire('set', {
          options,
          interactable: this,
        });

        return this;
      }

      unset () {
        super.unset();
        scope.interactables.signals.fire('unset', { interactable: this });
      }
    },

    interactables: {
      // all set interactables
      list: [],

      new (target, options) {
        options = utils.extend(options || {}, {
          actions: scope.actions,
        });

        const interactable = new scope.Interactable(target, options, scope.document);

        scope.addDocument(interactable._doc);

        scope.interactables.list.push(interactable);

        scope.interactables.signals.fire('new', {
          target,
          options,
          interactable: interactable,
          win: this._win,
        });

        return interactable;
      },

      indexOfElement (target, context) {
        context = context || scope.document;

        const list = this.list;

        for (let i = 0; i < list.length; i++) {
          const interactable = list[i];

          if (interactable.target === target && interactable._context === context) {
            return i;
          }
        }

        return -1;
      },

      get (element, options, dontCheckInContext) {
        const ret = this.list[this.indexOfElement(element, options && options.context)];

        return ret && (utils.is.string(element) || dontCheckInContext || ret.inContext(element))? ret : null;
      },

      forEachMatch (element, callback) {
        for (const interactable of this.list) {
          let ret;

          if ((utils.is.string(interactable.target)
            // target is a selector and the element matches
            ? (utils.is.element(element) && utils.dom.matchesSelector(element, interactable.target))
            // target is the element
            : element === interactable.target)
            // the element is in context
            && (interactable.inContext(element))) {
            ret = callback(interactable);
          }

          if (ret !== undefined) {
            return ret;
          }
        }
      },

      signals: new utils.Signals(),
    },

    // main document
    document: null,
    // all documents being listened to
    documents: [/* { doc, options } */],

    init (window) {
      return initScope(scope, window);
    },

    addDocument (doc, options) {
      // do nothing if document is already known
      if (scope.getDocIndex(doc) !== -1) { return false; }

      const window = win.getWindow(doc);

      scope.documents.push({ doc, options });
      events.documents.push(doc);

      // don't add an unload event for the main document
      // so that the page may be cached in browser history
      if (doc !== scope.document) {
        events.add(window, 'unload', scope.onWindowUnload);
      }

      scope.signals.fire('add-document', { doc, window, scope, options });
    },

    removeDocument (doc) {
      const index = scope.getDocIndex(doc);

      const window = win.getWindow(doc);
      const options = scope.documents[index].options;

      events.remove(window, 'unload', scope.onWindowUnload);

      scope.documents.splice(index, 1);
      events.documents.splice(index, 1);

      scope.signals.fire('remove-document', { doc, window, scope, options });
    },

    onWindowUnload (event) {
      scope.removeDocument(event.target.document);
    },

    getDocIndex (doc) {
      for (let i = 0; i < scope.documents.length; i++) {
        if (scope.documents[i].doc === doc) {
          return i;
        }
      }

      return -1;
    },
  };

  return scope;
}

export function initScope (scope, window) {
  win.init(window);
  domObjects.init(window);
  browser.init(window);
  raf.init(window);

  scope.document = window.document;

  return scope;
}
<commit_msg>scope: use unload event.currentTarget<commit_after>import Eventable  from './Eventable';
import defaults   from './defaultOptions';
import * as utils from '@interactjs/utils';
import domObjects from '@interactjs/utils/domObjects';

import InteractEvent    from './InteractEvent';
import InteractableBase from './Interactable';

const {
  win,
  browser,
  raf,
  Signals,
  events,
} = utils;

export function createScope () {
  const scope = {
    Signals,
    signals: new Signals(),
    browser,
    events,
    utils,
    defaults: utils.clone(defaults),
    Eventable,

    InteractEvent: InteractEvent,
    Interactable: class Interactable extends InteractableBase {
      get _defaults () { return scope.defaults; }

      set (options) {
        super.set(options);

        scope.signals.fire('set', {
          options,
          interactable: this,
        });

        return this;
      }

      unset () {
        super.unset();
        scope.interactables.signals.fire('unset', { interactable: this });
      }
    },

    interactables: {
      // all set interactables
      list: [],

      new (target, options) {
        options = utils.extend(options || {}, {
          actions: scope.actions,
        });

        const interactable = new scope.Interactable(target, options, scope.document);

        scope.addDocument(interactable._doc);

        scope.interactables.list.push(interactable);

        scope.interactables.signals.fire('new', {
          target,
          options,
          interactable: interactable,
          win: this._win,
        });

        return interactable;
      },

      indexOfElement (target, context) {
        context = context || scope.document;

        const list = this.list;

        for (let i = 0; i < list.length; i++) {
          const interactable = list[i];

          if (interactable.target === target && interactable._context === context) {
            return i;
          }
        }

        return -1;
      },

      get (element, options, dontCheckInContext) {
        const ret = this.list[this.indexOfElement(element, options && options.context)];

        return ret && (utils.is.string(element) || dontCheckInContext || ret.inContext(element))? ret : null;
      },

      forEachMatch (element, callback) {
        for (const interactable of this.list) {
          let ret;

          if ((utils.is.string(interactable.target)
            // target is a selector and the element matches
            ? (utils.is.element(element) && utils.dom.matchesSelector(element, interactable.target))
            // target is the element
            : element === interactable.target)
            // the element is in context
            && (interactable.inContext(element))) {
            ret = callback(interactable);
          }

          if (ret !== undefined) {
            return ret;
          }
        }
      },

      signals: new utils.Signals(),
    },

    // main document
    document: null,
    // all documents being listened to
    documents: [/* { doc, options } */],

    init (window) {
      return initScope(scope, window);
    },

    addDocument (doc, options) {
      // do nothing if document is already known
      if (scope.getDocIndex(doc) !== -1) { return false; }

      const window = win.getWindow(doc);

      scope.documents.push({ doc, options });
      events.documents.push(doc);

      // don't add an unload event for the main document
      // so that the page may be cached in browser history
      if (doc !== scope.document) {
        events.add(window, 'unload', scope.onWindowUnload);
      }

      scope.signals.fire('add-document', { doc, window, scope, options });
    },

    removeDocument (doc) {
      const index = scope.getDocIndex(doc);

      const window = win.getWindow(doc);
      const options = scope.documents[index].options;

      events.remove(window, 'unload', scope.onWindowUnload);

      scope.documents.splice(index, 1);
      events.documents.splice(index, 1);

      scope.signals.fire('remove-document', { doc, window, scope, options });
    },

    onWindowUnload (event) {
      scope.removeDocument(event.currentTarget.document);
    },

    getDocIndex (doc) {
      for (let i = 0; i < scope.documents.length; i++) {
        if (scope.documents[i].doc === doc) {
          return i;
        }
      }

      return -1;
    },
  };

  return scope;
}

export function initScope (scope, window) {
  win.init(window);
  domObjects.init(window);
  browser.init(window);
  raf.init(window);

  scope.document = window.document;

  return scope;
}
<|endoftext|>


<commit_before>'use strict';
import Immutable from 'immutable';
import uuid from "./uuid";
import isArray from 'lodash/isArray'
import {defaultValue} from "./index";
import {getFieldConfig, getWidgetForFieldOp, getOperatorConfig, getFieldWidgetConfig, getFieldPath, getFieldPathLabels} from './configUtils';
import omit from 'lodash/omit';
import pick from 'lodash/pick';

/*
 Build tree to http://querybuilder.js.org/ like format

 Example:
 {
 "condition": "AND",
 "rules": [
 {
 "id": "price",
 "field": "price",
 "type": "double",
 "input": "text",
 "operator": "less",
 "value": "10.25"
 },
 {
 "condition": "OR",
 "rules": [
 {
 "id": "category",
 "field": "category",
 "type": "integer",
 "input": "select",
 "operator": "equal",
 "value": "2"
 },
 {
 "id": "category",
 "field": "category",
 "type": "integer",
 "input": "select",
 "operator": "equal",
 "value": "1"
 }
 ]}
 ]
 }
 */
export const queryBuilderFormat = (item, config) => {

    const type = item.get('type');
    const properties = item.get('properties');
    const children = item.get('children1');
    const id = item.get('id')

    var resultQuery = {}

    if (type === 'group' && children && children.size) {
        const conjunction = properties.get('conjunction');
        const conjunctionDefinition = config.conjunctions[conjunction];

        const list = children
            .map((currentChild) => {
                return queryBuilderFormat(currentChild, config)
            })
            .filter((currentChild) => typeof currentChild !== 'undefined')
        if (!list.size)
            return undefined;
        resultQuery['rules'] = list.toList();
        resultQuery['condition'] = conjunction.toUpperCase();

        return resultQuery;
    } else if (type === 'rule') {
        const field = properties.get('field');
        const operator = properties.get('operator');
        const options = properties.get('operatorOptions');
        let value = properties.get('value');
        if (field == null || operator == null)
            return undefined;

        const fieldDefinition = getFieldConfig(field, config) || {};
        const operatorDefinition = getOperatorConfig(config, operator, field) || {};
        //const reversedOp = operatorDefinition.reversedOp;
        //const revOperatorDefinition = getOperatorConfig(config, reversedOp, field) || {};
        const fieldType = fieldDefinition.type || "undefined";
        const cardinality = operatorDefinition.cardinality || 1;
        const widget = getWidgetForFieldOp(config, field, operator);
        const fieldWidgetDefinition = omit(getFieldWidgetConfig(config, field, operator, widget), ['factory']);
        const typeConfig = config.types[fieldDefinition.type] || {};

        if (value.size < cardinality)
            return undefined;
        value = cardinality == 1 ? value.first() : value.toArray();

        var ruleQuery = {
            id,
            field,
            operator,
            value,
            type: fieldType,
            input: Object.keys(typeConfig.widgets)[0],
        };
        return ruleQuery
    }
    return undefined;
};

//untested!
export const queryBuilderToTree = (ruleset) => {
    const condition = ruleset.condition;
    var tree = {}
    tree.id = uuid()
    if (condition) {
        tree.type = 'group';
        var childrens = new Immutable.List(ruleset.rules)
            .map(queryBuilderToTree)
        childrens = childrens.reduce((result, item) => {
            return result.set(item.get('id'), item)
        }, new Immutable.OrderedMap())
        tree.children1 = childrens;
        tree.properties = new Immutable.Map({conjunction: condition, id: uuid()})
    } else {
        const {id, field, input, type, value, operator} = ruleset;
        var list_value = value;
        if (isArray(value)) {
            list_value = new Immutable.List(value)
        } else {
            list_value = new Immutable.List([value])
        }
        var properties = new Immutable.Map({
            type,
            operator,
            field: field || id,
            widget: input || type,
            value: list_value,
        })
        tree.properties = properties;
        tree.type = 'rule'
    }
    return new Immutable.Map(tree)

}

<commit_msg><commit_after>'use strict';
import Immutable from 'immutable';
import uuid from "./uuid";
import isArray from 'lodash/isArray'
import {defaultValue} from "./index";
import {getFieldConfig, getWidgetForFieldOp, getOperatorConfig, getFieldWidgetConfig, getFieldPath, getFieldPathLabels} from './configUtils';
import omit from 'lodash/omit';
import pick from 'lodash/pick';

/*
 Build tree to http://querybuilder.js.org/ like format

 Example:
 {
 "condition": "AND",
 "rules": [
 {
 "id": "price",
 "field": "price",
 "type": "double",
 "input": "text",
 "operator": "less",
 "value": "10.25"
 },
 {
 "condition": "OR",
 "rules": [
 {
 "id": "category",
 "field": "category",
 "type": "integer",
 "input": "select",
 "operator": "equal",
 "value": "2"
 },
 {
 "id": "category",
 "field": "category",
 "type": "integer",
 "input": "select",
 "operator": "equal",
 "value": "1"
 }
 ]}
 ]
 }
 */
export const queryBuilderFormat = (item, config, rootQuery = null) => {
    const type = item.get('type');
    const properties = item.get('properties');
    const children = item.get('children1');
    const id = item.get('id')

    var resultQuery = {};
    var isRoot = (rootQuery === null);
    if (isRoot) {
        rootQuery = resultQuery;
        rootQuery.usedFields = [];
    }

    if (type === 'group' && children && children.size) {
        const conjunction = properties.get('conjunction');
        const conjunctionDefinition = config.conjunctions[conjunction];

        const list = children
            .map((currentChild) => {
                return queryBuilderFormat(currentChild, config, rootQuery)
            })
            .filter((currentChild) => typeof currentChild !== 'undefined')
        if (!list.size)
            return undefined;
        resultQuery['rules'] = list.toList();
        resultQuery['condition'] = conjunction.toUpperCase();

        return resultQuery;
    } else if (type === 'rule') {
        const field = properties.get('field');
        const operator = properties.get('operator');
        const options = properties.get('operatorOptions');
        let value = properties.get('value');
        if (field == null || operator == null)
            return undefined;

        const fieldDefinition = getFieldConfig(field, config) || {};
        const operatorDefinition = getOperatorConfig(config, operator, field) || {};
        //const reversedOp = operatorDefinition.reversedOp;
        //const revOperatorDefinition = getOperatorConfig(config, reversedOp, field) || {};
        const fieldType = fieldDefinition.type || "undefined";
        const cardinality = operatorDefinition.cardinality || 1;
        const widget = getWidgetForFieldOp(config, field, operator);
        const fieldWidgetDefinition = omit(getFieldWidgetConfig(config, field, operator, widget), ['factory']);
        const typeConfig = config.types[fieldDefinition.type] || {};

        if (value.size < cardinality)
            return undefined;

        if (rootQuery.usedFields.indexOf(field) == -1)
            rootQuery.usedFields.push(field);
        value = cardinality == 1 ? value.first() : value.toArray();

        var ruleQuery = {
            id,
            field,
            operator,
            value,
            type: fieldType,
            input: Object.keys(typeConfig.widgets)[0],
        };
        return ruleQuery
    }
    return undefined;
};

//not tested!
export const queryBuilderToTree = (ruleset) => {
    const condition = ruleset.condition;
    var tree = {}
    tree.id = uuid()
    if (condition) {
        tree.type = 'group';
        var childrens = new Immutable.List(ruleset.rules)
            .map(queryBuilderToTree)
        childrens = childrens.reduce((result, item) => {
            return result.set(item.get('id'), item)
        }, new Immutable.OrderedMap())
        tree.children1 = childrens;
        tree.properties = new Immutable.Map({conjunction: condition, id: uuid()})
    } else {
        const {id, field, input, type, value, operator} = ruleset;
        var list_value = value;
        if (isArray(value)) {
            list_value = new Immutable.List(value)
        } else {
            list_value = new Immutable.List([value])
        }
        var properties = new Immutable.Map({
            type,
            operator,
            field: field || id,
            widget: input || type,
            value: list_value,
        })
        tree.properties = properties;
        tree.type = 'rule'
    }
    return new Immutable.Map(tree)

}

<|endoftext|>


<commit_before>'use strict';

//
// Compatibility with older node.js as path.exists got moved to `fs`.
//
var fs = require('fs')
  , path = require('path')
  , os = require('os')
  , hook = path.join(__dirname, 'hook')
  , root = path.resolve(__dirname, '..', '..')
  , exists = fs.existsSync || path.existsSync;

//
// Gather the location of the possible hidden .git directory, the hooks
// directory which contains all git hooks and the absolute location of the
// `pre-commit` file. The path needs to be absolute in order for the symlinking
// to work correctly.
//
var git;

//new recursive upward type of search .git
var currentDir, newCurrentDir =  __dirname;
do {
  currentDir = newCurrentDir;
  git = path.resolve(newCurrentDir, '.git');
  newCurrentDir = path.resolve(currentDir, '..');
} while (!(exists(git) || (newCurrentDir == currentDir)));

var hooks = path.resolve(git, 'hooks')
  , precommit = path.resolve(hooks, 'pre-commit');

//
// Bail out if we don't have an `.git` directory as the hooks will not get
// triggered. If we do have directory create a hooks folder if it doesn't exist.
//
if (!exists(git) || !fs.lstatSync(git).isDirectory()) return;
if (!exists(hooks)) fs.mkdirSync(hooks);

//
// If there's an existing `pre-commit` hook we want to back it up instead of
// overriding it and losing it completely as it might contain something
// important.
//
if (exists(precommit) && !fs.lstatSync(precommit).isSymbolicLink()) {
  console.log('pre-commit:');
  console.log('pre-commit: Detected an existing git pre-commit hook');
  fs.writeFileSync(precommit +'.old', fs.readFileSync(precommit));
  console.log('pre-commit: Old pre-commit hook backuped to pre-commit.old');
  console.log('pre-commit:');
}

//
// We cannot create a symlink over an existing file so make sure it's gone and
// finish the installation process.
//
try { fs.unlinkSync(precommit); }
catch (e) {}

// Create generic precommit hook that launches this modules hook (as well
// as stashing - unstashing the unstaged changes)
// TODO: we could keep launching the old pre-commit scripts
var hookRelativeUnixPath = hook.replace(root, '.\$ENV_DIR');

if(os.platform() === 'win32') {
  hookRelativeUnixPath = hookRelativeUnixPath.replace(/[\\\/]+/g, '/');
}

var precommitContent = '#!/bin/bash' + os.EOL
  + 'ENV_DIR=`git config --local --get core.envDir`' + os.EOL
  +  hookRelativeUnixPath + os.EOL
  + 'RESULT=$?' + os.EOL
  + '[ $RESULT -ne 0 ] && exit 1' + os.EOL
  + 'exit 0' + os.EOL;

//
// It could be that we do not have rights to this folder which could cause the
// installation of this module to completely fail. We should just output the
// error instead destroying the whole npm install process.
//
try { fs.writeFileSync(precommit, precommitContent); }
catch (e) {
  console.error('pre-commit:');
  console.error('pre-commit: Failed to create the hook file in your .git/hooks folder because:');
  console.error('pre-commit: '+ e.message);
  console.error('pre-commit: The hook was not installed.');
  console.error('pre-commit:');
}

try { fs.chmodSync(precommit, '777'); }
catch (e) {
  console.error('pre-commit:');
  console.error('pre-commit: chmod 0777 the pre-commit file in your .git/hooks folder because:');
  console.error('pre-commit: '+ e.message);
  console.error('pre-commit:');
}
<commit_msg>envDir lookup on commit<commit_after>'use strict';

//
// Compatibility with older node.js as path.exists got moved to `fs`.
//
var fs = require('fs')
  , path = require('path')
  , os = require('os')
  , hook = path.join(__dirname, 'hook')
  , root = path.resolve(__dirname, '..', '..')
  , exists = fs.existsSync || path.existsSync;

//
// Gather the location of the possible hidden .git directory, the hooks
// directory which contains all git hooks and the absolute location of the
// `pre-commit` file. The path needs to be absolute in order for the symlinking
// to work correctly.
//
var git;

//new recursive upward type of search .git
var currentDir, newCurrentDir =  __dirname;
do {
  currentDir = newCurrentDir;
  git = path.resolve(newCurrentDir, '.git');
  newCurrentDir = path.resolve(currentDir, '..');
} while (!(exists(git) || (newCurrentDir == currentDir)));

var hooks = path.resolve(git, 'hooks')
  , precommit = path.resolve(hooks, 'pre-commit');

//
// Bail out if we don't have an `.git` directory as the hooks will not get
// triggered. If we do have directory create a hooks folder if it doesn't exist.
//
if (!exists(git) || !fs.lstatSync(git).isDirectory()) return;
if (!exists(hooks)) fs.mkdirSync(hooks);

//
// If there's an existing `pre-commit` hook we want to back it up instead of
// overriding it and losing it completely as it might contain something
// important.
//
if (exists(precommit) && !fs.lstatSync(precommit).isSymbolicLink()) {
  console.log('pre-commit:');
  console.log('pre-commit: Detected an existing git pre-commit hook');
  fs.writeFileSync(precommit +'.old', fs.readFileSync(precommit));
  console.log('pre-commit: Old pre-commit hook backuped to pre-commit.old');
  console.log('pre-commit:');
}

//
// We cannot create a symlink over an existing file so make sure it's gone and
// finish the installation process.
//
try { fs.unlinkSync(precommit); }
catch (e) {}

// Create generic precommit hook that launches this modules hook (as well
// as stashing - unstashing the unstaged changes)
// TODO: we could keep launching the old pre-commit scripts
var hookRelativeUnixPath = hook.replace(root, '.\$ENV_DIR');

if(os.platform() === 'win32') {
  hookRelativeUnixPath = hookRelativeUnixPath.replace(/[\\\/]+/g, '/');
}

var precommitContent = '#!/bin/bash' + os.EOL
  + 'ENV_DIR=`git config --local --get core.envDir`' + os.EOL
  + 'if [ -n $ENV_DIR ]' + os.EOL
  + 'then' + os.EOL
  + 'cd ./$ENV_DIR' + os.EOL
  + 'fi' + os.EOL
  +  hookRelativeUnixPath + os.EOL
  + 'RESULT=$?' + os.EOL
  + '[ $RESULT -ne 0 ] && exit 1' + os.EOL
  + 'exit 0' + os.EOL;

//
// It could be that we do not have rights to this folder which could cause the
// installation of this module to completely fail. We should just output the
// error instead destroying the whole npm install process.
//
try { fs.writeFileSync(precommit, precommitContent); }
catch (e) {
  console.error('pre-commit:');
  console.error('pre-commit: Failed to create the hook file in your .git/hooks folder because:');
  console.error('pre-commit: '+ e.message);
  console.error('pre-commit: The hook was not installed.');
  console.error('pre-commit:');
}

try { fs.chmodSync(precommit, '777'); }
catch (e) {
  console.error('pre-commit:');
  console.error('pre-commit: chmod 0777 the pre-commit file in your .git/hooks folder because:');
  console.error('pre-commit: '+ e.message);
  console.error('pre-commit:');
}
<|endoftext|>


<commit_before>/*

 Copyright 2015 Comcast Cable Communications Management, LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 */

var UserModel = function($rootScope, messageModel) {

    var user = {};
    user.loaded = false;
    this.user = user;

    this.setUser = function(userData) {
        user.loaded = true;
        user = angular.extend(user, userData);
        if (user.newUser) {
            user.username = ''; // new users were given a temp username that needs to be ditched
        }
        if (!user.localUser) {
            messageModel.setMessages([ { level: 'success', text: 'Logged in as LDAP user.' } ], false);
        }
        $rootScope.$broadcast('userModel::userUpdated', user);
    };

    this.resetUser = function() {
        user = {};
        user.loaded = false;
        this.user = user;
        $rootScope.$broadcast('userModel::userUpdated', user);
    };

};

UserModel.$inject = ['$rootScope', 'messageModel'];
module.exports = UserModel;<commit_msg>changed login verbiage when user not found in database<commit_after>/*

 Copyright 2015 Comcast Cable Communications Management, LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 */

var UserModel = function($rootScope, messageModel) {

    var user = {};
    user.loaded = false;
    this.user = user;

    this.setUser = function(userData) {
        user.loaded = true;
        user = angular.extend(user, userData);
        if (user.newUser) {
            user.username = ''; // new users were given a temp username that needs to be ditched
        }
        if (!user.localUser) {
            messageModel.setMessages([ { level: 'success', text: 'Logged in as read-only user.' } ], false);
        }
        $rootScope.$broadcast('userModel::userUpdated', user);
    };

    this.resetUser = function() {
        user = {};
        user.loaded = false;
        this.user = user;
        $rootScope.$broadcast('userModel::userUpdated', user);
    };

};

UserModel.$inject = ['$rootScope', 'messageModel'];
module.exports = UserModel;<|endoftext|>


<commit_before>(function() {
  // "use strict";
  chart.$inject = [ "$http", "$q" ];
  function chart($http, $q) {
    var obj = {
      "foo": 1,
      "bar": 2
    },
    columnsData = [],
    executeNames = ["Symbicort", "Aggrenox"],
    uniqueNames = {},
    finalcount = [],
    jeezy = [],
    tempData = [],
    jeezy2 = [];
    // http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/
    var uniqueFilter = function(ref) {
      var o = ref, i, l = ref.length, r = [];
      for(i=0; i<l;i++) o[this[i]] = this[i];
      for(i in o) r.push(o[i]);
      return r;
    };
    var populateData = function(ref){
      var o = ref, i, l=ref.length, r = [];
      for(i=0; i<l; i++)
      {
        drugName = ref[i].toString();
        var url = "https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:" + drugName + "&count=patient.reaction.reactionmeddrapt.exact";
        $http.get(url)
        .success(function(data) {
          console.log(data);
          var gw = data.results;
          tempData.push({ label: "label", value: gw})
          for (var key in gw) {
            uniqueNames[gw[key].term] = gw[key].term;
          }
          console.log(tempData);
          validation(tempData);
        })
      }
    }
    var validation = function(ref){
      for (var drug in ref) {
        gb = new Array();
        for(var jk in ref[drug].value){
          gb.push(ref[drug].value[jk].term);
        }
        ref[drug]["term"] = gb;
      }
      finalizeData(tempData)
    }
    var finalizeData = function(ref){
      var finalXAxis = uniqueFilter(uniqueNames);
      console.log(finalXAxis);
      for(drug in tempData){
        tempData[drug].tempvalue = new Array();
        for(var tick in tempData[drug].value){
          var tempTerm, tempCount, tub = {};
          tempTerm = tempData[drug].value[tick].term;
          tempCount = tempData[drug].value[tick].count;
          tub[tempTerm] = tempCount;
          tempData[drug].tempvalue.push(tub);
        }
        for(var symptom in finalXAxis){
          if (tempData[drug].term.indexOf(finalXAxis[symptom]) < 0) {
            var sub = {};
            sub[finalXAxis[symptom]] = 0;
            tempData[drug].tempvalue.push(sub);
          } else {
            console.log("match");
          }
        }
        console.log(tempData);
      }
      // publishData();
    }
    // var publishData = function(){
    //   var finalXAxis = uniqueFilter(uniqueNames);
    //   for (var i = 0; i < executeNames.length; i++) {
    //     var finalcount = new Array(),
    //     finalDrug = executeNames[i];
    //     finalcount.push(finalDrug);
    //     for(var symptom in finalXAxis){
    //       finalcount.push("jeezy");
    //     }
    //     columnsData[i] = (finalcount);
    //   }
    //   console.log(columnsData);
    // }
    populateData(executeNames);
  }
  angular.module("myApp")
  .controller("chart", chart)
}());

//
//   function chart ($http) {
//     var
//     u ={},
//     a = [],
//     effectsName = [],
//     effectsCount = [],
//     rxcui = [ "1191", "3521" ];
//
//
//
//
//
//
//
//     var getdata = function(rxcui) {
//       for (var i = 0; i < rxcui.length; i++) {
//         var url = "https://api.fda.gov/drug/event.json?search=patient.drug.openfda.rxcui." + rxcui[i] + "&count=patient.reaction.reactionmeddrapt.exact";
//         $http.get(url)
//         .success(function(data) {
//           console.log(data);
//           for (var j = 0; j <= data.results.length; j++) {
//             processEffects(data.results[j], j, data.results.length, i, rxcui.length);
//             if (!u.hasOwnProperty(effectsName[j])) {
//               a.push(effectsName[j]);
//               u[effectsName[j]] = 1;
//             }
//           }
//           return a;
//         })
//         .error(function(err) {
//           console.log(err);
//         });
//       }
//     }
//     // var unique = function(arr) {
//     //   var u = {}, a = [];
//     //   for(var i = 0, l = arr.length; i < l; ++i){
//     //     if(!u.hasOwnProperty(arr[i])) {
//     //       a.push(arr[i]);
//     //       u[arr[i]] = 1;
//     //     }
//     //   }
//     //   return a;
//     //   }
//     // }
//     var dataName = function(effectsName) {
//       for (var i = 0; i < effectsName.length; i++) {
//
//       }
//     }
//     var processEffects = function(effect, iterate, limit, ver, vertotal) {
//
//         } else if (iterate === limit && ver === vertotal) {
//           for (var l = 0; l < effectsCountHolder.length; l++) {
//             effectsCount.push(effectsCountHolder[l]);
//             console.log("effects count holder");
//             console.log(effectsCountHolder);
//             console.log(effectsCount);
//           }
//
//         } else {
//           effectsName.push(effect.term);
//           effectsCountHolder[rxcui[i]].push(effect.count);
//         }
//       }
//     }
//     var chart = c3.generate({
//       data: {
//         json: {
//           ASPIRIN: [450, 0, 50, 40, 60, 50],
//           data2: [200, 130, 90, 240, 130, 220],
//           data3: [300, 200, 160, 400, 250, 250]
//         }
//       },
//       zoom: true,
//       axis: {
//         x: {
//           type: "category",
//           categories: a,
//           tick: {
//             rotate: 75,
//             multiline: false
//           },
//           height: 130
//         }
//       }
//     });
//     getdata(rxcui);
//   }
//   angular.module("myApp")
//   .controller  ("chart", chart)
// }());
<commit_msg>dynamic search by name now works<commit_after>(function() {
  // "use strict";
  chart.$inject = [ "$http", "$q" ];
  function chart($http, $q) {
    var obj = {
      "foo": 1,
      "bar": 2
    },
    columnsData = [],
    executeNames = ["Aggrenox", "Symbicort"],
    uniqueNames = {},
    finalcount = [],
    drugName = [],
    jeezy = [],
    tempData = [],
    finalXAxis = [],
    jeezy2 = [];
    executeNames = executeNames.sort();
    // http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/
    var uniqueFilter = function(ref) {
      var o = ref, i, l = ref.length, r = [];
      for(i=0; i<l;i++) o[this[i]] = this[i];
      for(i in o) r.push(o[i]);
      return r;
    };
    var populateData = function(ref){
      var o = ref, i, l=ref.length, r = [];
      for(i=0; i<l; i++)
      {
        drugName.push(ref[i]);
        var url = "https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:" + "\"" + drugName[i] + "\"" + "&count=patient.reaction.reactionmeddrapt.exact";
        $http.get(url)
        .success(function(data) {
          console.log(data);
          var gw = data.results;
          tempData.push({ label: "label", value: gw})
          for (var key in gw) {
            uniqueNames[gw[key].term] = gw[key].term;
          }
          console.log(tempData);
          validation(tempData);
        })
      }
    }
    var validation = function(ref){
      for (var i = 0; i < ref.length; i++) {
        tempData[i].label = executeNames[i];
        gb = new Array();
        for(var jk in ref[i].value){
          gb.push(ref[i].value[jk].term);
        }
        ref[i]["term"] = gb;
      }
      finalizeData(tempData)
    }
    var finalizeData = function(ref){
      finalXAxis = uniqueFilter(uniqueNames);
      console.log(finalXAxis);
      for(drug in tempData){
        tempData[drug].tempvalue = new Array();
        for(var tick in tempData[drug].value){
          var tempTerm, tempCount, tub = {};
          tempTerm = tempData[drug].value[tick].term;
          tempCount = tempData[drug].value[tick].count;
          tub[tempTerm] = tempCount;
          tempData[drug].tempvalue.push(tub);
        }
        for(var symptom in finalXAxis){
          if (tempData[drug].term.indexOf(finalXAxis[symptom]) < 0) {
            var sub = {};
            sub[finalXAxis[symptom]] = 0;
            tempData[drug].tempvalue.push(sub);
          } else {
            console.log("match");
          }
        }
        console.log(tempData);
      }
    }
    populateData(executeNames);
  }
  angular.module("myApp")
  .controller("chart", chart)
}());

//
//   function chart ($http) {
//     var
//     u ={},
//     a = [],
//     effectsName = [],
//     effectsCount = [],
//     rxcui = [ "1191", "3521" ];
//
//
//
//
//
//
//
//     var getdata = function(rxcui) {
//       for (var i = 0; i < rxcui.length; i++) {
//         var url = "https://api.fda.gov/drug/event.json?search=patient.drug.openfda.rxcui." + rxcui[i] + "&count=patient.reaction.reactionmeddrapt.exact";
//         $http.get(url)
//         .success(function(data) {
//           console.log(data);
//           for (var j = 0; j <= data.results.length; j++) {
//             processEffects(data.results[j], j, data.results.length, i, rxcui.length);
//             if (!u.hasOwnProperty(effectsName[j])) {
//               a.push(effectsName[j]);
//               u[effectsName[j]] = 1;
//             }
//           }
//           return a;
//         })
//         .error(function(err) {
//           console.log(err);
//         });
//       }
//     }
//     // var unique = function(arr) {
//     //   var u = {}, a = [];
//     //   for(var i = 0, l = arr.length; i < l; ++i){
//     //     if(!u.hasOwnProperty(arr[i])) {
//     //       a.push(arr[i]);
//     //       u[arr[i]] = 1;
//     //     }
//     //   }
//     //   return a;
//     //   }
//     // }
//     var dataName = function(effectsName) {
//       for (var i = 0; i < effectsName.length; i++) {
//
//       }
//     }
//     var processEffects = function(effect, iterate, limit, ver, vertotal) {
//
//         } else if (iterate === limit && ver === vertotal) {
//           for (var l = 0; l < effectsCountHolder.length; l++) {
//             effectsCount.push(effectsCountHolder[l]);
//             console.log("effects count holder");
//             console.log(effectsCountHolder);
//             console.log(effectsCount);
//           }
//
//         } else {
//           effectsName.push(effect.term);
//           effectsCountHolder[rxcui[i]].push(effect.count);
//         }
//       }
//     }
//     var chart = c3.generate({
//       data: {
//         json: {
//           ASPIRIN: [450, 0, 50, 40, 60, 50],
//           data2: [200, 130, 90, 240, 130, 220],
//           data3: [300, 200, 160, 400, 250, 250]
//         }
//       },
//       zoom: true,
//       axis: {
//         x: {
//           type: "category",
//           categories: a,
//           tick: {
//             rotate: 75,
//             multiline: false
//           },
//           height: 130
//         }
//       }
//     });
//     getdata(rxcui);
//   }
//   angular.module("myApp")
//   .controller  ("chart", chart)
// }());
<|endoftext|>


<commit_before>/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	var css = __webpack_require__(1);

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	// style-loader: Adds some css to the DOM by adding a <style> tag

	// load the styles
	var content = __webpack_require__(2);
	if(typeof content === 'string') content = [[module.id, content, '']];
	// add the styles to the DOM
	var update = __webpack_require__(4)(content, {});
	if(content.locals) module.exports = content.locals;
	// Hot Module Replacement
	if(false) {
		// When the styles change, update the <style> tags
		if(!content.locals) {
			module.hot.accept("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./main.css", function() {
				var newContent = require("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./main.css");
				if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
				update(newContent);
			});
		}
		// When the module is disposed, remove the <style> tags
		module.hot.dispose(function() { update(); });
	}

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	exports = module.exports = __webpack_require__(3)();
	// imports

	// module
	exports.push([module.id, "body {\n\tmargin: 100px;\n}\n\nbody {\n\tbackground: #EEE;\n}", ""]);

	// exports

/***/ },
/* 3 */
/***/ function(module, exports) {

	/*
		MIT License http://www.opensource.org/licenses/mit-license.php
		Author Tobias Koppers @sokra
	*/
	// css base code, injected by the css-loader
	module.exports = function() {
		var list = [];

		// return the list of modules as css string
		list.toString = function toString() {
			var result = [];
			for(var i = 0; i < this.length; i++) {
				var item = this[i];
				if(item[2]) {
					result.push("@media " + item[2] + "{" + item[1] + "}");
				} else {
					result.push(item[1]);
				}
			}
			return result.join("");
		};

		// import a list of modules into the list
		list.i = function(modules, mediaQuery) {
			if(typeof modules === "string")
				modules = [[null, modules, ""]];
			var alreadyImportedModules = {};
			for(var i = 0; i < this.length; i++) {
				var id = this[i][0];
				if(typeof id === "number")
					alreadyImportedModules[id] = true;
			}
			for(i = 0; i < modules.length; i++) {
				var item = modules[i];
				// skip already imported module
				// this implementation is not 100% perfect for weird media query combinations
				//  when a module is imported multiple times with different media queries.
				//  I hope this will never occur (Hey this way we have smaller bundles)
				if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
					if(mediaQuery && !item[2]) {
						item[2] = mediaQuery;
					} else if(mediaQuery) {
						item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
					}
					list.push(item);
				}
			}
		};
		return list;
	};

/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {

	/*
		MIT License http://www.opensource.org/licenses/mit-license.php
		Author Tobias Koppers @sokra
	*/
	var stylesInDom = {},
		memoize = function(fn) {
			var memo;
			return function () {
				if (typeof memo === "undefined") memo = fn.apply(this, arguments);
				return memo;
			};
		},
		isOldIE = memoize(function() {
			return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
		}),
		getHeadElement = memoize(function () {
			return document.head || document.getElementsByTagName("head")[0];
		}),
		singletonElement = null,
		singletonCounter = 0,
		styleElementsInsertedAtTop = [];

	module.exports = function(list, options) {
		if(false) {
			if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
		}

		options = options || {};
		// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
		// tags it will allow on a page
		if (typeof options.singleton === "undefined") options.singleton = isOldIE();

		// By default, add <style> tags to the bottom of <head>.
		if (typeof options.insertAt === "undefined") options.insertAt = "bottom";

		var styles = listToStyles(list);
		addStylesToDom(styles, options);

		return function update(newList) {
			var mayRemove = [];
			for(var i = 0; i < styles.length; i++) {
				var item = styles[i];
				var domStyle = stylesInDom[item.id];
				domStyle.refs--;
				mayRemove.push(domStyle);
			}
			if(newList) {
				var newStyles = listToStyles(newList);
				addStylesToDom(newStyles, options);
			}
			for(var i = 0; i < mayRemove.length; i++) {
				var domStyle = mayRemove[i];
				if(domStyle.refs === 0) {
					for(var j = 0; j < domStyle.parts.length; j++)
						domStyle.parts[j]();
					delete stylesInDom[domStyle.id];
				}
			}
		};
	}

	function addStylesToDom(styles, options) {
		for(var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];
			if(domStyle) {
				domStyle.refs++;
				for(var j = 0; j < domStyle.parts.length; j++) {
					domStyle.parts[j](item.parts[j]);
				}
				for(; j < item.parts.length; j++) {
					domStyle.parts.push(addStyle(item.parts[j], options));
				}
			} else {
				var parts = [];
				for(var j = 0; j < item.parts.length; j++) {
					parts.push(addStyle(item.parts[j], options));
				}
				stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
			}
		}
	}

	function listToStyles(list) {
		var styles = [];
		var newStyles = {};
		for(var i = 0; i < list.length; i++) {
			var item = list[i];
			var id = item[0];
			var css = item[1];
			var media = item[2];
			var sourceMap = item[3];
			var part = {css: css, media: media, sourceMap: sourceMap};
			if(!newStyles[id])
				styles.push(newStyles[id] = {id: id, parts: [part]});
			else
				newStyles[id].parts.push(part);
		}
		return styles;
	}

	function insertStyleElement(options, styleElement) {
		var head = getHeadElement();
		var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
		if (options.insertAt === "top") {
			if(!lastStyleElementInsertedAtTop) {
				head.insertBefore(styleElement, head.firstChild);
			} else if(lastStyleElementInsertedAtTop.nextSibling) {
				head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
			} else {
				head.appendChild(styleElement);
			}
			styleElementsInsertedAtTop.push(styleElement);
		} else if (options.insertAt === "bottom") {
			head.appendChild(styleElement);
		} else {
			throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
		}
	}

	function removeStyleElement(styleElement) {
		styleElement.parentNode.removeChild(styleElement);
		var idx = styleElementsInsertedAtTop.indexOf(styleElement);
		if(idx >= 0) {
			styleElementsInsertedAtTop.splice(idx, 1);
		}
	}

	function createStyleElement(options) {
		var styleElement = document.createElement("style");
		styleElement.type = "text/css";
		insertStyleElement(options, styleElement);
		return styleElement;
	}

	function createLinkElement(options) {
		var linkElement = document.createElement("link");
		linkElement.rel = "stylesheet";
		insertStyleElement(options, linkElement);
		return linkElement;
	}

	function addStyle(obj, options) {
		var styleElement, update, remove;

		if (options.singleton) {
			var styleIndex = singletonCounter++;
			styleElement = singletonElement || (singletonElement = createStyleElement(options));
			update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
			remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
		} else if(obj.sourceMap &&
			typeof URL === "function" &&
			typeof URL.createObjectURL === "function" &&
			typeof URL.revokeObjectURL === "function" &&
			typeof Blob === "function" &&
			typeof btoa === "function") {
			styleElement = createLinkElement(options);
			update = updateLink.bind(null, styleElement);
			remove = function() {
				removeStyleElement(styleElement);
				if(styleElement.href)
					URL.revokeObjectURL(styleElement.href);
			};
		} else {
			styleElement = createStyleElement(options);
			update = applyToTag.bind(null, styleElement);
			remove = function() {
				removeStyleElement(styleElement);
			};
		}

		update(obj);

		return function updateStyle(newObj) {
			if(newObj) {
				if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
					return;
				update(obj = newObj);
			} else {
				remove();
			}
		};
	}

	var replaceText = (function () {
		var textStore = [];

		return function (index, replacement) {
			textStore[index] = replacement;
			return textStore.filter(Boolean).join('\n');
		};
	})();

	function applyToSingletonTag(styleElement, index, remove, obj) {
		var css = remove ? "" : obj.css;

		if (styleElement.styleSheet) {
			styleElement.styleSheet.cssText = replaceText(index, css);
		} else {
			var cssNode = document.createTextNode(css);
			var childNodes = styleElement.childNodes;
			if (childNodes[index]) styleElement.removeChild(childNodes[index]);
			if (childNodes.length) {
				styleElement.insertBefore(cssNode, childNodes[index]);
			} else {
				styleElement.appendChild(cssNode);
			}
		}
	}

	function applyToTag(styleElement, obj) {
		var css = obj.css;
		var media = obj.media;
		var sourceMap = obj.sourceMap;

		if(media) {
			styleElement.setAttribute("media", media)
		}

		if(styleElement.styleSheet) {
			styleElement.styleSheet.cssText = css;
		} else {
			while(styleElement.firstChild) {
				styleElement.removeChild(styleElement.firstChild);
			}
			styleElement.appendChild(document.createTextNode(css));
		}
	}

	function updateLink(linkElement, obj) {
		var css = obj.css;
		var media = obj.media;
		var sourceMap = obj.sourceMap;

		if(sourceMap) {
			// http://stackoverflow.com/a/26603875
			css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
		}

		var blob = new Blob([css], { type: "text/css" });

		var oldSrc = linkElement.href;

		linkElement.href = URL.createObjectURL(blob);

		if(oldSrc)
			URL.revokeObjectURL(oldSrc);
	}

/***/ }
/******/ ]);<commit_msg>Removed bundle.js<commit_after><|endoftext|>


<commit_before>Tree.prototype.species = ""; //String
Tree.prototype.name = ""; //String
Tree.prototype.diameter = 0; //Integer
Tree.prototype.trunks = 0; //Integer
Tree.prototype.location = ""; //String
Tree.prototype.coordinates = {
	'latitude': 0.0,
	'longitude': 0.0
}; //Object of Doubles/Floats

function Tree(data){
	this.species = data['tree_species'] || this.species;
	this.name = data['common_name'] || this.name;
	this.diameter = parseInt(data['diameter_at_breast_height'], 10) || this.diameter;
	this.trunks = parseInt(data['number_of_trunks'], 10) || this.trunks;
	this.location = data['location_type'] || this.location;
	this.coordinates = {
		'latitude': parseFloat(data['location']['latitude']),
		'longitude': parseFloat(data['location']['longitude'])
	} || this.coordinates;
}

function cloudAlert(numberCleaned){
	document.getElementById('numberCloudsCleaned').innerHTML = numberCleaned;
	document.getElementById('cleanedCloudsAlert').style.height = '10vh';
	setTimeout(function(){
		document.getElementById('cleanedCloudsAlert').style.height = '0vh';
	}, 1000);
}

function absorb(sweepIndex){
	var cloudsCleaned = 0;
	var sweeper = $('#sweeper' + sweepIndex);
	for(var c = 0; c < cloudIDList.length; c++){
		if($('#' + cloudIDList[c])){
			var currentCloud = $('#' + cloudIDList[c]);
			if(collision(sweeper, currentCloud)){
				var domCloud = document.getElementById('cloud' + c);
				domCloud.style.backgroundImage = "url('style/cleanCloud.png')";
				cloudsCleaned++;
				/*var parent = document.getElementById(board.id + '-clouds');
				parent.removeChild(domCloud);*/
			}
		}
		else{
			console.log('error')
		}
	}
	if(cloudsCleaned > 0){
		cloudAlert(cloudsCleaned);
	}
}

Tree.prototype.toSweeperHTML = function(){
	var t = 0;
	var html = '';
	html += '
';
		html +='<button onclick="absorb(' + t + ');">O</button>';
		html += '

';
	html += '
';
	return html;
}

Tree.prototype.toWindowHTML = function(){
	var html = '';
		html += '
'
			html += ''
			html += '
' + this.getCommonName(true) + '
' + this.formatCoordinates() + '
'
		html += '
'
	return html;
}

Tree.prototype.getCommonName = function(formatted){
	var nameSplit = this.name.split(",");
	var commonName = nameSplit[0];
	if(formatted){
		commonName = commonName.charAt(0).toUpperCase() + commonName.substr(1);
	}
	return commonName;
}

Tree.prototype.formatCoordinates = function(){
	return '(' + this.coordinates.latitude.toFixed(3) + ', ' + this.coordinates.longitude.toFixed(3) + ')';
}

Tree.prototype.toString = function(){
	var plural = "";
	if(this.trunks > 1){
		plural = "s";
	}
	return this.diameter + "' "
		+ this.name + " (" + this.species + ") "
		+ "with " + this.trunks + " trunk" + plural + " "
		+ "at {" + this.coordinates.latitude.toFixed(3) + ", "
		+ this.coordinates.longitude.toFixed(3) + "}";
}<commit_msg>Completed alertbox<commit_after>Tree.prototype.species = ""; //String
Tree.prototype.name = ""; //String
Tree.prototype.diameter = 0; //Integer
Tree.prototype.trunks = 0; //Integer
Tree.prototype.location = ""; //String
Tree.prototype.coordinates = {
	'latitude': 0.0,
	'longitude': 0.0
}; //Object of Doubles/Floats

function Tree(data){
	this.species = data['tree_species'] || this.species;
	this.name = data['common_name'] || this.name;
	this.diameter = parseInt(data['diameter_at_breast_height'], 10) || this.diameter;
	this.trunks = parseInt(data['number_of_trunks'], 10) || this.trunks;
	this.location = data['location_type'] || this.location;
	this.coordinates = {
		'latitude': parseFloat(data['location']['latitude']),
		'longitude': parseFloat(data['location']['longitude'])
	} || this.coordinates;
}

function cloudAlert(numberCleaned){
	document.getElementById('numberCloudsCleaned').innerHTML = numberCleaned;
	document.getElementById('cleanedCloudsAlert').style.height = '10vh';
	setTimeout(function(){
		document.getElementById('cleanedCloudsAlert').style.height = '0vh';
	}, 3000);
}

function absorb(sweepIndex){
	var cloudsCleaned = 0;
	var sweeper = $('#sweeper' + sweepIndex);
	for(var c = 0; c < cloudIDList.length; c++){
		if($('#' + cloudIDList[c])){
			var currentCloud = $('#' + cloudIDList[c]);
			if(collision(sweeper, currentCloud)){
				var domCloud = document.getElementById('cloud' + c);
				domCloud.style.backgroundImage = "url('style/cleanCloud.png')";
				cloudsCleaned++;
				/*var parent = document.getElementById(board.id + '-clouds');
				parent.removeChild(domCloud);*/
			}
		}
		else{
			console.log('error')
		}
	}
	if(cloudsCleaned > 0){
		cloudAlert(cloudsCleaned);
	}
}

Tree.prototype.toSweeperHTML = function(){
	var t = 0;
	var html = '';
	html += '
';
		html +='<button onclick="absorb(' + t + ');">O</button>';
		html += '

';
	html += '
';
	return html;
}

Tree.prototype.toWindowHTML = function(){
	var html = '';
		html += '
'
			html += ''
			html += '
' + this.getCommonName(true) + '
' + this.formatCoordinates() + '
'
		html += '
'
	return html;
}

Tree.prototype.getCommonName = function(formatted){
	var nameSplit = this.name.split(",");
	var commonName = nameSplit[0];
	if(formatted){
		commonName = commonName.charAt(0).toUpperCase() + commonName.substr(1);
	}
	return commonName;
}

Tree.prototype.formatCoordinates = function(){
	return '(' + this.coordinates.latitude.toFixed(3) + ', ' + this.coordinates.longitude.toFixed(3) + ')';
}

Tree.prototype.toString = function(){
	var plural = "";
	if(this.trunks > 1){
		plural = "s";
	}
	return this.diameter + "' "
		+ this.name + " (" + this.species + ") "
		+ "with " + this.trunks + " trunk" + plural + " "
		+ "at {" + this.coordinates.latitude.toFixed(3) + ", "
		+ this.coordinates.longitude.toFixed(3) + "}";
}<|endoftext|>


<commit_before>if (process.platform === 'darwin') {
  var spawn = require('child_process').spawn;
  var args = ['install', '--fallback-to-build'];
  var options = {stdio: 'inherit'};
  var child = spawn('node-pre-gyp', args, options);
  child.on('close', process.exit);
}<commit_msg>Use require.resolve to resolve node-pre-gyp.<commit_after>if (process.platform === 'darwin') {
  var spawn = require('child_process').spawn;
  var args = ['install', '--fallback-to-build'];
  var options = {stdio: 'inherit'};
  var child = spawn(require.resolve('node-pre-gyp/bin/node-pre-gyp'), args, options);
  child.on('close', process.exit);
}
<|endoftext|>


<commit_before><commit_msg>Move listing page header to separate component<commit_after>import React from 'react'

const ListingHeader = (props) => {
    return (

            Display

                 props.setListType('list')}>
                    List

                 props.setListType('grid')}>
                    Grid

    );
};

export default ListingHeader<|endoftext|>