<commit_before>app.rest = {

    spinnerFunct: function(){
    },

    get: function (url, successCallback, errorCallback, urlParams, headers) {
        app.rest.getDelete(url, 'GET', successCallback, errorCallback, urlParams, headers);
    },

    delete: function (url, successCallback, errorCallback, urlParams, headers) {
        app.rest.getDelete(url, 'DELETE', successCallback, errorCallback, urlParams, headers);
    },

    update: function (url, request, successCallback, errorCallback, urlParams, headers) {
        app.rest.postPut(url, 'PUT', request, successCallback, errorCallback, urlParams, headers);
    },

    post: function (url, request, successCallback, errorCallback, urlParams, headers) {
        app.rest.postPut(url, 'POST', request, successCallback, errorCallback, urlParams, headers);
    },

    isMock: function(url, method, request, successCallback, callBackIsnt){

        if(app.config.mockApi){
            var result = app.mock.execByUrl(url, method, request);
            successCallback(result);
        }else{
            callBackIsnt();
        }

    },

    getDelete: function (url, method, successCallback, errorCallback, urlParams, headers) {

        app.rest.isMock(url, method, urlParams, successCallback, function(){

            var preparedUrl = null;

            if(urlParams !== undefined && urlParams !== null){
                preparedUrl = app.util.System.prepareUrl(url, urlParams);
            }else{
                preparedUrl = url;
            }

            $.ajax({
                url: preparedUrl,
                type: method,
                beforeSend: function () {
                    app.rest.spinnerFunct();
                },
                complete: function () {
                    app.rest.spinnerFunct = function () {};
                },
                headers: headers,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    successCallback(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {

                    if(errorCallback !== undefined){

                        console.log(jqXHR);

                        errorCallback(jqXHR.responseJSON, jqXHR.status, jqXHR);

                    }

                }
            });

        });

    },

    postPut: function (url, method, request, successCallback, errorCallback, urlParams, headers) {

        app.rest.isMock(url, method, request, successCallback, function(){

            console.log(headers);

            var preparedUrl = null;

            if(urlParams !== undefined && urlParams !== null){
                preparedUrl = app.util.System.prepareUrl(url, urlParams);
            }else{
                preparedUrl = url;
            }

            var jsonData = JSON.stringify(request);

            $.ajax({
                url: preparedUrl,
                type: method,
                beforeSend: function () {
                    app.rest.spinnerFunct();
                },
                complete: function () {
                    app.rest.spinnerFunct = function () {};
                },
                headers: headers,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: jsonData,
                success: function (data, textStatus, jqXHR) {
                    successCallback(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {

                    if(errorCallback !== undefined){

                        console.log(jqXHR);

                        errorCallback(jqXHR.responseJSON, jqXHR.status, jqXHR);

                    }

                }
            });

        });

    }

};<commit_msg>+ fix<commit_after>app.rest = {

    spinnerShow: function(){
    },

    spinnerHide: function(){
    },

    get: function (url, successCallback, errorCallback, urlParams, headers) {
        app.rest.getDelete(url, 'GET', successCallback, errorCallback, urlParams, headers);
    },

    delete: function (url, successCallback, errorCallback, urlParams, headers) {
        app.rest.getDelete(url, 'DELETE', successCallback, errorCallback, urlParams, headers);
    },

    update: function (url, request, successCallback, errorCallback, urlParams, headers) {
        app.rest.postPut(url, 'PUT', request, successCallback, errorCallback, urlParams, headers);
    },

    post: function (url, request, successCallback, errorCallback, urlParams, headers) {
        app.rest.postPut(url, 'POST', request, successCallback, errorCallback, urlParams, headers);
    },

    isMock: function(url, method, request, successCallback, callBackIsnt){

        if(app.config.mockApi){
            var result = app.mock.execByUrl(url, method, request);
            successCallback(result);
        }else{
            callBackIsnt();
        }

    },

    getDelete: function (url, method, successCallback, errorCallback, urlParams, headers) {

        app.rest.isMock(url, method, urlParams, successCallback, function(){

            var preparedUrl = null;

            if(urlParams !== undefined && urlParams !== null){
                preparedUrl = app.util.System.prepareUrl(url, urlParams);
            }else{
                preparedUrl = url;
            }

            $.ajax({
                url: preparedUrl,
                type: method,
                beforeSend: function () {
                    app.rest.spinnerShow(url);
                },
                complete: function () {
                    app.rest.spinnerHide(url);
                },
                headers: headers,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    successCallback(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {

                    if(errorCallback !== undefined){

                        console.log(jqXHR);

                        errorCallback(jqXHR.responseJSON, jqXHR.status, jqXHR);

                    }

                }
            });

        });

    },

    postPut: function (url, method, request, successCallback, errorCallback, urlParams, headers) {

        app.rest.isMock(url, method, request, successCallback, function(){

            console.log(headers);

            var preparedUrl = null;

            if(urlParams !== undefined && urlParams !== null){
                preparedUrl = app.util.System.prepareUrl(url, urlParams);
            }else{
                preparedUrl = url;
            }

            var jsonData = JSON.stringify(request);

            $.ajax({
                url: preparedUrl,
                type: method,
                beforeSend: function () {
                    app.rest.spinnerShow(url);
                },
                complete: function () {
                    app.rest.spinnerHide(url);
                },
                headers: headers,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: jsonData,
                success: function (data, textStatus, jqXHR) {
                    successCallback(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {

                    if(errorCallback !== undefined){

                        console.log(jqXHR);

                        errorCallback(jqXHR.responseJSON, jqXHR.status, jqXHR);

                    }

                }
            });

        });

    }

};<|endoftext|>


<commit_before>import React from 'react';
import Immutable from 'immutable';
import ImmutablePropTypes from 'react-immutable-proptypes';
import IconButton from '../../../components/icon_button';

const storageKey = 'announcements_dismissed';

class Announcements extends React.PureComponent {

  static propTypes = {
    account: ImmutablePropTypes.map.isRequired,
  };

  componentDidUpdate (prevProps, prevState) {
    if (prevState.dismissed !== this.state.dismissed) {
      try {
        localStorage.setItem(storageKey, JSON.stringify(this.state.dismissed));
      } catch (e) {}
    }
  }

  componentWillMount () {
    try {
      const dismissed = JSON.parse(localStorage.getItem(storageKey));
      this.state = { dismissed: Array.isArray(dismissed) ? dismissed : [] };
    } catch (e) {
      this.state = { dismissed: [] };
    }

    const announcements = [];

    announcements.push(
      {
        id: 1,
        icon: '/announcements/icon_2x_360.png',
        body: '8月中旬に土有利古戦場が開催予定、土パ装備特集記事を公開中！',
        link: [
          {
            inline: false,
            href: 'http://gran-matome.com/archives/27579',
            body: '記事を読む',
          },
        ],
      }
      // NOTE: id: 6 まで使用した
    );

    this.announcements = Immutable.fromJS(announcements);
  }

  handleDismiss = (event) => {
    const id = +event.currentTarget.getAttribute('title');

    if (Number.isInteger(id)) {
      this.setState({ dismissed: [].concat(this.state.dismissed, id) });
    }
  }

  render () {
    return (

        {this.announcements.map(announcement => this.state.dismissed.indexOf(announcement.get('id')) === -1 && (

                <IconButton icon='close' title={`${announcement.get('id')}`} onClick={this.handleDismiss} />

{announcement.get('body')}

                {announcement.get('link').map((link) => {
                  const classNames = ['announcements__link'];

                  if (link.get('inline')) {
                    classNames.push('announcements__link-inline');
                  }

                  return (

                      {link.get('body')}

                  );
                })}

        ))}

    );
  }

};

export default Announcements;
<commit_msg>Modify announcements data<commit_after>import React from 'react';
import Immutable from 'immutable';
import ImmutablePropTypes from 'react-immutable-proptypes';
import IconButton from '../../../components/icon_button';

const storageKey = 'announcements_dismissed';

class Announcements extends React.PureComponent {

  static propTypes = {
    account: ImmutablePropTypes.map.isRequired,
  };

  componentDidUpdate (prevProps, prevState) {
    if (prevState.dismissed !== this.state.dismissed) {
      try {
        localStorage.setItem(storageKey, JSON.stringify(this.state.dismissed));
      } catch (e) {}
    }
  }

  componentWillMount () {
    try {
      const dismissed = JSON.parse(localStorage.getItem(storageKey));
      this.state = { dismissed: Array.isArray(dismissed) ? dismissed : [] };
    } catch (e) {
      this.state = { dismissed: [] };
    }

    const announcements = [];

    announcements.push(
      {
        id: 1,
        icon: '/announcements/icon_2x_360.png',
        body: '8月中旬に土有利古戦場が開催予定、土パ装備特集記事を公開中！',
        link: [
          {
            inline: false,
            href: 'http://gran-matome.com/archives/27579',
            body: '記事を読む',
          },
        ],
      },
      {
        id: 7,
        icon: '/announcements/info_03.png',
        body: 'やること迷ったらまず確認！夏の半額特集',
        link: [
          {
            inline: false,
            href: 'http://gran-matome.com/page-27913',
            body: '記事を読む',
          },
        ],
      }
      // NOTE: id: 7 まで使用した
    );

    this.announcements = Immutable.fromJS(announcements);
  }

  handleDismiss = (event) => {
    const id = +event.currentTarget.getAttribute('title');

    if (Number.isInteger(id)) {
      this.setState({ dismissed: [].concat(this.state.dismissed, id) });
    }
  }

  render () {
    return (

        {this.announcements.map(announcement => this.state.dismissed.indexOf(announcement.get('id')) === -1 && (

                <IconButton icon='close' title={`${announcement.get('id')}`} onClick={this.handleDismiss} />

{announcement.get('body')}

                {announcement.get('link').map((link) => {
                  const classNames = ['announcements__link'];

                  if (link.get('inline')) {
                    classNames.push('announcements__link-inline');
                  }

                  return (

                      {link.get('body')}

                  );
                })}

        ))}

    );
  }

};

export default Announcements;
<|endoftext|>


<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>import React from 'react';
import I18n from 'i18n-js';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import tagComponent from '../../../utils/helpers/tags';

import Icon from './../../icon';
/**
 * Adds an 's' to pluralise (keys will always be error or warning)
 *
 * @param {string} key
 * @return {string} pluralized key
 */
const pluralize = (key) => {
  return `${key}s`;
};

/**
 * decides whether the warning message should be appended to the sentence or output as a sentence on it's own
 *
 * @param {object} props
 * @param {string} key
 * @return {boolean} true if the warning message needs to be appended
 */
const warningAppend = (props, key) => {
  return props.errors > 0 && props.warnings > 0 && key === 'warning';
};

/**
 * finds the correct translation key
 *
 * @param {object} props
 * @param {string} key
 * @return {string} correct key
 */
const translationKey = (props, key) => {
  return warningAppend(props, key) ? 'errors_and_warnings' : pluralize(key);
};

/**
 * Returns the default translation set
 *
 * @param {number} errorCount
 * @param {number} warningCount
 * @return {object} default translations
 */
const defaultTranslations = (errorCount, warningCount) => {
  return {
    errors: {
      defaultValue: {
        one: `There is ${errorCount} error`,
        other: `There are ${errorCount} errors`
      },
      count: parseInt(errorCount, 10)
    },
    warnings: {
      defaultValue: {
        one: `There is ${warningCount} warning`,
        other: `There are ${warningCount} warnings`
      },
      count: parseInt(warningCount, 10)
    },
    errors_and_warnings: {
      defaultValue: {
        one: `and ${warningCount} warning`,
        other: `and ${warningCount} warnings`
      },
      count: parseInt(warningCount, 10)
    }
  };
};

/**
 * gets the correct translation
 *
 * @param {object} props
 * @param {string} key
 * @return {string} correct translation
 */
const translation = (props, key) => {
  const parsedKey = translationKey(props, key);

  const defaultTranslation = defaultTranslations(props.errors, props.warnings)[parsedKey],
      location = `errors.messages.form_summary.${parsedKey}`;

  return I18n.t(location, defaultTranslation);
};

/**
 * builds a summary in JSX
 *
 * @param {object} props
 * @param {string} key
 * @return {JSX}
 */
const summary = (props, key) => {
  if (props[pluralize(key)] > 0) {
    return (
      <span className={ `carbon-form-summary__summary carbon-form-summary__${key}-summary` }>
        <Icon className='carbon-form-summary__icon' type={ key } />

    );
  }
  return null;
};

const summaryClasses = (props) => {
  return classNames(
    'carbon-form-summary',
    'carbon-form-save', {
      'carbon-form-save--invalid': props.errors || props.warnings
    }
  );
};

const FormSummary = props =>

    { summary(props, 'error') }
    { summary(props, 'warning') }
    { props.children }

;

FormSummary.propTypes = {
  children: PropTypes.node,
  errors: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number
  ]),
  warnings: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number
  ])
};

export default FormSummary;
<commit_msg>Fix ESLint errors in FormSummary<commit_after>import React from 'react';
import I18n from 'i18n-js';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import tagComponent from '../../../utils/helpers/tags';

import Icon from './../../icon';
/**
 * Adds an 's' to pluralise (keys will always be error or warning)
 *
 * @param {string} key
 * @return {string} pluralized key
 */
const pluralize = (key) => {
  return `${key}s`;
};

/**
 * decides whether the warning message should be appended to the sentence or output as a sentence on it's own
 *
 * @param {object} props
 * @param {string} key
 * @return {boolean} true if the warning message needs to be appended
 */
const warningAppend = (props, key) => {
  return props.errors > 0 && props.warnings > 0 && key === 'warning';
};

/**
 * finds the correct translation key
 *
 * @param {object} props
 * @param {string} key
 * @return {string} correct key
 */
const translationKey = (props, key) => {
  return warningAppend(props, key) ? 'errors_and_warnings' : pluralize(key);
};

/**
 * Returns the default translation set
 *
 * @param {number} errorCount
 * @param {number} warningCount
 * @return {object} default translations
 */
const defaultTranslations = (errorCount, warningCount) => {
  return {
    errors: {
      defaultValue: {
        one: `There is ${errorCount} error`,
        other: `There are ${errorCount} errors`
      },
      count: parseInt(errorCount, 10)
    },
    warnings: {
      defaultValue: {
        one: `There is ${warningCount} warning`,
        other: `There are ${warningCount} warnings`
      },
      count: parseInt(warningCount, 10)
    },
    errors_and_warnings: {
      defaultValue: {
        one: `and ${warningCount} warning`,
        other: `and ${warningCount} warnings`
      },
      count: parseInt(warningCount, 10)
    }
  };
};

/**
 * gets the correct translation
 *
 * @param {object} props
 * @param {string} key
 * @return {string} correct translation
 */
const translation = (props, key) => {
  const parsedKey = translationKey(props, key);

  const defaultTranslation = defaultTranslations(props.errors, props.warnings)[parsedKey],
      location = `errors.messages.form_summary.${parsedKey}`;

  return I18n.t(location, defaultTranslation);
};

/**
 * builds a summary in JSX
 *
 * @param {object} props
 * @param {string} key
 * @return {JSX}
 */
const summary = (props, key) => {
  if (props[pluralize(key)] > 0) {
    return (
      <span className={ `carbon-form-summary__summary carbon-form-summary__${key}-summary` }>
        <Icon className='carbon-form-summary__icon' type={ key } />

    );
  }
  return null;
};

const summaryClasses = (props) => {
  return classNames(
    'carbon-form-summary',
    'carbon-form-save', {
      'carbon-form-save--invalid': props.errors || props.warnings
    }
  );
};

const FormSummary = props =>

    { summary(props, 'error') }
    { summary(props, 'warning') }
    { props.children }

;

FormSummary.propTypes = {
  children: PropTypes.node,
  errors: PropTypes.oneOfType([ // eslint-disable-line react/no-unused-prop-types
    PropTypes.string,
    PropTypes.number
  ]),
  warnings: PropTypes.oneOfType([ // eslint-disable-line react/no-unused-prop-types
    PropTypes.string,
    PropTypes.number
  ])
};

export default FormSummary;
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject = buildbug.buildProject;
var buildProperties = buildbug.buildProperties;
var buildTarget = buildbug.buildTarget;
var enableModule = buildbug.enableModule;
var series = buildbug.series;
var targetTask = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws = enableModule("aws");
var bugpack = enableModule("bugpack");
var core = enableModule("core");
var nodejs = enableModule("nodejs");

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    packageJson: {
        name: "bugunit",
        version: "0.0.4",
        main: "./lib/bug-unit-cli-module.js",
        private: true,
        bin: "bin/bugunit",
        scripts: {
            start: "node ./scripts/bugunit-cli-start.js"
        },
        dependencies: {
            npm: "1.2.x",
            tar: "0.1.x",
            bugpack: "https://s3.amazonaws.com/airbug/bugpack-0.0.3.tgz"
        }
    },
    sourcePaths: [
        "../bugjs/projects/bugjs/js/src",
        "../bugjs/projects/bugfs/js/src",
        "../bugjs/projects/bugflow/js/src",
        '../bugjs/projects/bugtrace/js/src',
        "../bugjs/projects/bugboil/js/src",
        "./projects/bugunit-cli/js/src"
    ],
    scriptPaths: [
        "./projects/bugunit-cli/js/scripts"
    ],
    binPaths: [
        "./projects/bugunit-cli/bin"
    ]
});

//-------------------------------------------------------------------------------
// Declare Tasks
//-------------------------------------------------------------------------------

//-------------------------------------------------------------------------------
// Declare Flows
//-------------------------------------------------------------------------------

// Clean Flow
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local Flow
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths"),
                binPaths: buildProject.getProperty("binPaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3EnsureBucket", {
            properties: {
                bucket: buildProject.getProperty("local-bucket")
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        ACL: 'public-read'
                    }
                });
            },
            properties: {
                bucket: buildProject.getProperty("local-bucket")
            }
        })
    ])
).makeDefault();

// Prod Flow
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3EnsureBucket", {
            properties: {
                bucket: "airbug"
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        ACL: 'public-read'
                    }
                });
            },
            properties: {
                bucket: "airbug"
            }
        })
    ])
);<commit_msg>[#9] Setup production EC2 server - AwsModule task now requires lowercase acl - bump version number to 0.0.5<commit_after>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject = buildbug.buildProject;
var buildProperties = buildbug.buildProperties;
var buildTarget = buildbug.buildTarget;
var enableModule = buildbug.enableModule;
var series = buildbug.series;
var targetTask = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws = enableModule("aws");
var bugpack = enableModule("bugpack");
var core = enableModule("core");
var nodejs = enableModule("nodejs");

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    packageJson: {
        name: "bugunit",
        version: "0.0.5",
        main: "./lib/bug-unit-cli-module.js",
        private: true,
        bin: "bin/bugunit",
        scripts: {
            start: "node ./scripts/bugunit-cli-start.js"
        },
        dependencies: {
            npm: "1.2.x",
            tar: "0.1.x",
            bugpack: "https://s3.amazonaws.com/airbug/bugpack-0.0.4.tgz"
        }
    },
    sourcePaths: [
        "../bugjs/projects/bugjs/js/src",
        "../bugjs/projects/bugfs/js/src",
        "../bugjs/projects/bugflow/js/src",
        '../bugjs/projects/bugtrace/js/src',
        "../bugjs/projects/bugboil/js/src",
        "./projects/bugunit-cli/js/src"
    ],
    scriptPaths: [
        "./projects/bugunit-cli/js/scripts"
    ],
    binPaths: [
        "./projects/bugunit-cli/bin"
    ]
});

//-------------------------------------------------------------------------------
// Declare Tasks
//-------------------------------------------------------------------------------

//-------------------------------------------------------------------------------
// Declare Flows
//-------------------------------------------------------------------------------

// Clean Flow
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local Flow
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths"),
                binPaths: buildProject.getProperty("binPaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3EnsureBucket", {
            properties: {
                bucket: buildProject.getProperty("local-bucket")
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        acl: 'public-read'
                    }
                });
            },
            properties: {
                bucket: buildProject.getProperty("local-bucket")
            }
        })
    ])
).makeDefault();

// Prod Flow
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3EnsureBucket", {
            properties: {
                bucket: "airbug"
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        acl: 'public-read'
                    }
                });
            },
            properties: {
                bucket: "airbug"
            }
        })
    ])
);<|endoftext|>


<commit_before>var CM = require('codemirror');

require('codemirror/addon/display/panel');
require('codemirror/addon/search/search.js');
require('codemirror/addon/search/searchcursor.js');
require('codemirror/addon/dialog/dialog.js');
require('codemirror/addon/hint/show-hint.js');
require('codemirror/addon/selection/active-line');
require('./automarkup.js');
require('./ire-hint.js');

var milestones=require("./milestones");
var React = require('react');
var ReactDOM = require('react-dom');
var E=React.createElement;

var applyMarkups=require("./markups").applyMarkups;

var randomKey=function() {
	return 'm'+Math.random().toString().substr(2,5);
}
var eventKeys=["altKey","ctrlKey","shiftKey","clientX","clientY","pageX","pageY","screenX","screenY","type"];
var CodeMirrorComponent = React.createClass({
	displayName :"CodeMirror"
	,propTypes: {
		onChange: React.PropTypes.func,
		onFocusChange: React.PropTypes.func,
		onCursorActivity: React.PropTypes.func,
		options: React.PropTypes.object,
		path: React.PropTypes.string,
		value: React.PropTypes.string,
		onBeforeCopy:React.PropTypes.func
	}
	,getInitialState:function () {
		return {
			isFocused: false
		};
	}
	,cursorActivity:function(cm) {
		this.props.onCursorActivity&&this.props.onCursorActivity(cm);
	}
	,componentDidMount:function () {
		var textareaNode = ReactDOM.findDOMNode(this.refs.editor);
		this.codeMirror = CM(textareaNode, {
  		value: this.props.value
  		//,mode:  "javascript"
  		//inputStyle:"contenteditable",
  		,styleActiveLine:true
  		,undoDepth: Infinity
  		,lineWrapping:true
  		,readOnly:!!this.props.readOnly
  		,lineNumbers: true
  		,theme:this.props.theme||""
  		,gutters: ["CodeMirror-linenumbers"]
  		,lineSeparator:this.props.lineSeparator||null
  		,extraKeys: {
  			"Ctrl-I": function(cm){
  				cm.showHint({hint: CM.hint.ire});
  			}
  		}
		});

		this.codeMirror.setOption("lineNumberFormatter",milestones.lineNumberFormatter.bind(this));

		//CM.fromTextArea(textareaNode, this.props.options);
		if (this.props.onBeforeCopy) this.codeMirror.on('beforeCopyToClipboard', this.props.onBeforeCopy);
		this.codeMirror.getDoc().on('change', this.props.onChange);
		if (this.props.onBeforeChange) this.codeMirror.on('beforeChange', this.props.onBeforeChange);
		this.codeMirror.on('focus', this.focusChanged.bind(this, true));
		this.codeMirror.on('blur', this.focusChanged.bind(this, false));
		this.codeMirror.on('cursorActivity',this.cursorActivity);
		this.codeMirror.on('mousedown',this.onMouseDown);

		setTimeout(function(){
			this.props.markups&&applyMarkups(this.codeMirror,this.props.markups,true);
			this.props.onMarkupReady&&this.props.onMarkupReady(this.codeMirror);
		}.bind(this),30);//need to wait for this.codeMirror.react ready (dirty hack)
	}

	,componentWillUnmount:function () {
		// todo: is there a lighter-weight way to remove the cm instance?
		if (this.codeMirror&& this.codeMirror.toTextArea) {
			this.codeMirror.toTextArea();
		}
		clearTimeout(this.timermove);
	}

	,onMouseDown:function(cm,e) {
		this.props.onMouseDown&&this.props.onMouseDown(cm,e);
	}

	,shouldComponentUpdate:function(nextProps) {
		var update= (nextProps.value!==this.props.value || nextProps.history!==this.props.history
				||nextProps.markups!==this.props.markups);
		return update;
	}

	,componentWillReceiveProps:function (nextProps) {
		if (this.codeMirror) {

			if (this.props.history !== nextProps.history) {
				//this.codeMirror.setHistory(nextProps.history);
			}

			if (this.props.markups !== nextProps.markups) {
				nextProps.markups&&applyMarkups(this.codeMirror,nextProps.markups);
			}
		}
	}

	,getCodeMirror:function () {
		return this.codeMirror;
	}

	,markText:function(opts) {
		var doc=this.codeMirror.getDoc();
		var selections=doc.listSelections();

		for (var i=0;i<selections.length;i++) {
			var sel=selections[i];
			if (sel.anchor===sel.head) continue; //empty
			if (typeof opts.key!=="string") {
				opts.key=randomKey();
			}
			this.codeMirror.markText(sel.anchor,sel.head, opts );
		}
	}

	,focus:function () {
		if (this.codeMirror) {
			this.codeMirror.focus();
		}
	}

	,focusChanged:function (focused) {
		if (!this.isMounted())return;//no longer available
		this.setState({isFocused: focused});
		this.props.onFocusChange && this.props.onFocusChange(focused);
	}
	,onMouseMove:function(e) {
		if (!this.props.onMouseMove)return;
		clearTimeout(this.timermove);
		var ev={};
		eventKeys.forEach(function(k) {ev[k]=e[k]});
		this.timermove=setTimeout(function() {
			this.props.onMouseMove(ev);
		}.bind(this),100);
	}
	,render:function () {
		var obj={ref:"editor"};
		if (this.props.onMouseMove) obj.onMouseMove=this.onMouseMove;
		return E("span",obj);
	}

});

module.exports = CodeMirrorComponent;<commit_msg>optional load ire-hint<commit_after>var CM = require('codemirror');

require('codemirror/addon/display/panel');
require('codemirror/addon/search/search.js');
require('codemirror/addon/search/searchcursor.js');
require('codemirror/addon/dialog/dialog.js');
require('codemirror/addon/hint/show-hint.js');
require('codemirror/addon/selection/active-line');
require('./automarkup.js');

var milestones=require("./milestones");
var React = require('react');
var ReactDOM = require('react-dom');
var E=React.createElement;

var applyMarkups=require("./markups").applyMarkups;

var randomKey=function() {
	return 'm'+Math.random().toString().substr(2,5);
}
var eventKeys=["altKey","ctrlKey","shiftKey","clientX","clientY","pageX","pageY","screenX","screenY","type"];
var CodeMirrorComponent = React.createClass({
	displayName :"CodeMirror"
	,propTypes: {
		onChange: React.PropTypes.func,
		onFocusChange: React.PropTypes.func,
		onCursorActivity: React.PropTypes.func,
		options: React.PropTypes.object,
		path: React.PropTypes.string,
		value: React.PropTypes.string,
		onBeforeCopy:React.PropTypes.func
	}
	,getInitialState:function () {
		return {
			isFocused: false
		};
	}
	,cursorActivity:function(cm) {
		this.props.onCursorActivity&&this.props.onCursorActivity(cm);
	}
	,componentDidMount:function () {
		if (this.props.enableIRE) {
			var name='./ire-hint.js';
			require(name);
		}
		var textareaNode = ReactDOM.findDOMNode(this.refs.editor);
		this.codeMirror = CM(textareaNode, {
  		value: this.props.value
  		//,mode:  "javascript"
  		//inputStyle:"contenteditable",
  		,styleActiveLine:true
  		,undoDepth: Infinity
  		,lineWrapping:true
  		,readOnly:!!this.props.readOnly
  		,lineNumbers: true
  		,theme:this.props.theme||""
  		,gutters: ["CodeMirror-linenumbers"]
  		,lineSeparator:this.props.lineSeparator||null
  		,extraKeys: {
  			"Ctrl-I": function(cm){
  				cm.showHint({hint: CM.hint.ire});
  			}
  		}
		});

		this.codeMirror.setOption("lineNumberFormatter",milestones.lineNumberFormatter.bind(this));

		//CM.fromTextArea(textareaNode, this.props.options);
		if (this.props.onBeforeCopy) this.codeMirror.on('beforeCopyToClipboard', this.props.onBeforeCopy);
		this.codeMirror.getDoc().on('change', this.props.onChange);
		if (this.props.onBeforeChange) this.codeMirror.on('beforeChange', this.props.onBeforeChange);
		this.codeMirror.on('focus', this.focusChanged.bind(this, true));
		this.codeMirror.on('blur', this.focusChanged.bind(this, false));
		this.codeMirror.on('cursorActivity',this.cursorActivity);
		this.codeMirror.on('mousedown',this.onMouseDown);

		setTimeout(function(){
			this.props.markups&&applyMarkups(this.codeMirror,this.props.markups,true);
			this.props.onMarkupReady&&this.props.onMarkupReady(this.codeMirror);
		}.bind(this),30);//need to wait for this.codeMirror.react ready (dirty hack)
	}

	,componentWillUnmount:function () {
		// todo: is there a lighter-weight way to remove the cm instance?
		if (this.codeMirror&& this.codeMirror.toTextArea) {
			this.codeMirror.toTextArea();
		}
		clearTimeout(this.timermove);
	}

	,onMouseDown:function(cm,e) {
		this.props.onMouseDown&&this.props.onMouseDown(cm,e);
	}

	,shouldComponentUpdate:function(nextProps) {
		var update= (nextProps.value!==this.props.value || nextProps.history!==this.props.history
				||nextProps.markups!==this.props.markups);
		return update;
	}

	,componentWillReceiveProps:function (nextProps) {
		if (this.codeMirror) {

			if (this.props.history !== nextProps.history) {
				//this.codeMirror.setHistory(nextProps.history);
			}

			if (this.props.markups !== nextProps.markups) {
				nextProps.markups&&applyMarkups(this.codeMirror,nextProps.markups);
			}
		}
	}

	,getCodeMirror:function () {
		return this.codeMirror;
	}

	,markText:function(opts) {
		var doc=this.codeMirror.getDoc();
		var selections=doc.listSelections();

		for (var i=0;i<selections.length;i++) {
			var sel=selections[i];
			if (sel.anchor===sel.head) continue; //empty
			if (typeof opts.key!=="string") {
				opts.key=randomKey();
			}
			this.codeMirror.markText(sel.anchor,sel.head, opts );
		}
	}

	,focus:function () {
		if (this.codeMirror) {
			this.codeMirror.focus();
		}
	}

	,focusChanged:function (focused) {
		if (!this.isMounted())return;//no longer available
		this.setState({isFocused: focused});
		this.props.onFocusChange && this.props.onFocusChange(focused);
	}
	,onMouseMove:function(e) {
		if (!this.props.onMouseMove)return;
		clearTimeout(this.timermove);
		var ev={};
		eventKeys.forEach(function(k) {ev[k]=e[k]});
		this.timermove=setTimeout(function() {
			this.props.onMouseMove(ev);
		}.bind(this),100);
	}
	,render:function () {
		var obj={ref:"editor"};
		if (this.props.onMouseMove) obj.onMouseMove=this.onMouseMove;
		return E("span",obj);
	}

});

module.exports = CodeMirrorComponent;<|endoftext|>


<commit_before>import Content from './Content'

export default class OptionsContent extends Content {
  constructor ({music, gameEvents}) {
    super()
    this.music = music
    this.gameEvents = gameEvents
  }

  musicOn() {
    this.music.mute = false
  }

  musicOff() {
    this.music.mute = true
  }

  incVolume() {
    if (this.music.volume < 0.9 ) { this.music.volume += 0.1 }
    if (this.music.volume > 0.9) { this.music.volume = 1 }
  }

  decVolume() {
    if (this.music.volume > 0.1) { this.music.volume -= 0.1 }
    if (this.music.volume < 0.1) { this.music.volume = 0.1 }
  }

  createSections () {
    this.sectionName('options')
    console.log(this.music.volume)
    if (this.music.mute) {
      this.button('Äänet päälle', this.musicOn, this)
    } else {
      this.button('Äänet pois', this.musicOff, this)
    }
    this.button('Volyymi +', this.incVolume, this)
    this.button('Volyymi -', this.decVolume, this)
    this.button('Lopeta', this.gameEvents.finishGame, this.gameEvents,)
  }
}
<commit_msg>äänen voimakkuuden säätö<commit_after>import Content from './Content'

export default class OptionsContent extends Content {
  constructor ({music, gameEvents}) {
    super()
    this.music = music
    this.gameEvents = gameEvents
  }

  musicOn() {
    this.music.mute = false
  }

  musicOff() {
    this.music.mute = true
  }

  incVolume() {
    if (this.music.volume < 1 ) { this.music.volume += 0.1 }
    if (this.music.volume > 1) { this.music.volume = 1 }
  }

  decVolume() {
    if (this.music.volume > 0) { this.music.volume -= 0.1 }
    if (this.music.volume < 0) { this.music.volume = 0 }
  }

  createSections () {
    this.sectionName('options')
    if (this.music.mute) {
      this.button('Äänet päälle', this.musicOn, this)
    } else {
      this.button('Äänet pois', this.musicOff, this)
    }
    this.text('Äänen voimakkuus: ' + Math.round(this.music.volume*100) + '%')
    this.button('Volyymi +', this.incVolume, this)
    this.button('Volyymi -', this.decVolume, this)
    this.button('Lopeta', this.gameEvents.finishGame, this.gameEvents,)
  }
}
<|endoftext|>


<commit_before>var podMapping = {
  "ssl": "0",
  "na1": "3",
  "na2": "4",
  "na3": "5",
  "na4": "6",
  "na5": "7",
  "na6": "8",
  "na7": "A",
  "na8": "C",
  "na9": "E",
  "na10": "F",
  "na11": "G",
  "na12": "U",
  "na13": "a",
  "na14": "d",
  "na15": "i",
  "ap": "1",
  "ap1": "9",
  "emea": "2",
  "eu1": "D",
  "eu2": "b",
  "tapp0": "T",
  "cs1": "S",
  "cs2": "R",
  "cs3": "Q",
  "cs4": "P",
  "cs5": "O",
  "cs6": "N",
  "cs7": "M",
  "cs8": "L",
  "cs9": "K",
  "cs10": "J",
  "cs11": "Z",
  "cs12": "V",
  "cs13": "W",
  "cs14": "c",
  "cs15": "e",
  "cs16": "f",
  "cs17": "g",
  "prerelna1.pre": "t"
}

/**
 * Finds the salesforce viewstate string, if any, base64 decodes it, and return's it's length.
 * The length returned is the blob's lenght, NOT the base64 string - which is how SFDC calculates it
 * @return {integer|null}
 */
var calculateViewstateSize = function(){
    var restult;
    try{
        result = atob(document.getElementById('com.salesforce.visualforce.ViewState').value).length;
    }catch(ex){
        result = null;
    }
    return result;
}

/**
 * Get cookie value
 * @param key
 * @return {String|null}
 */
var getCookie = function(key) {
	var decode = function(value) {return decodeURIComponent(value.replace(/\+/g, ' '));};
	var cookies = document.cookie.split('; ');
	for (var i = 0, l = cookies.length; i < l; i++) {
		var parts = cookies[i].split('=');
		if (decode(parts.shift()) === key) {
			//success; found the key!
			return decode(parts.join('='));
		}
	}
	//failure; no such key
	return null;
}

/**
 * Takes any of the various forms of SFDC hostnames and spits out a "standard" format
 * @return {String}
 */

/**
 * Get URL parameters
 * @return {Array}
 */
var getUrlParam = function(param) {
	var hash, params = [];
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)    {
		hash = hashes[i].split('=');
		params.push(hash[0]);
		params[hash[0]] = hash[1];
	}
	return params[param] || null;
};

/**
 * Good ol Carlos - get record Id
 * @param url
 */
var getCurrentRecordId = function(url) {
	var href, iframehtml, id, theMatch, startParam;
	try{
		startParam = getUrlParam('timetracker_start');
	}catch(err){
		console.log(err);
	}

	var match;
	if (match = url.match(/\.com\/\w{15}|\.com\/\w{18}/)) {
		//success; captured id from salesforce.com/000xxxxxxxxxxxxXXX)
		return match[0].substr(5);
	} else if (match = url.match(/id\=\w{15}|id\=\w{18}/)) {
		//success; captured id from salesforce.com/id=000xxxxxxxxxxxxXXX
		return match[0].substr(3);
	} else {
		//failure; not on a page with an id
		return null;
	}
};

var context = {
	currentRecord : getCurrentRecordId(window.location.href),
	sessionId     : getCookie('sid'),
	orgId         : getCookie('sid').substring(0,15),
	userId        : null,
	sid_Client    : getCookie('sid_Client'),
	pod           : null,
	sfhost        : null
};

( function() {
    var instance = null;
    var hostname = window.location.host;
    //modified from http://stackoverflow.com/a/9722468/740787
    var parts = hostname.split("\.");
    if (parts.length == 3)
        instance = parts[0];
    else if (parts.length == 5)
        instance = parts[1];
    else if (parts.length == 4 && parts[1] === "my")
        instance = parts[0]+".my";

    if(instance === null)
        throw new Error("Unable to determine salesforce instance");
    context.pod = instance;
    context.userId = !!podMapping[instance] ? '005' + podMapping[instance] + getCookie('sid_Client').substring(0,11) : 'Unable to determine';

    var isVf = hostname.indexOf(".visual.force.com") > 0;
    if(parts[0].indexOf("--") > 0 && isVf){ //using my domain & this is sandbox or managed vf page
        var subparts = parts[0].split("--");
        context.sfhost = hostname.replace("--"+subparts[subparts.length-1],"").replace(".visual.force.com",".salesforce.com").replace(instance,"my");
    }else{
        context.sfhost = context.pod + ".salesforce.com";
    }

}());

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
	if(request.command == 'getContext')
	    sendResponse(context);
	else if(request.command == 'getViewstateSize')
	    sendResponse(calculateViewstateSize());
	else
	    throw 'Unknown command ' + request.command;
});<commit_msg>Revert "Fixed wrong 4th character in userIds"<commit_after>/**
 * Finds the salesforce viewstate string, if any, base64 decodes it, and return's it's length.
 * The length returned is the blob's lenght, NOT the base64 string - which is how SFDC calculates it
 * @return {integer|null}
 */
var calculateViewstateSize = function(){
    var restult;
    try{
        result = atob(document.getElementById('com.salesforce.visualforce.ViewState').value).length;
    }catch(ex){
        result = null;
    }
    return result;
}

/**
 * Get cookie value
 * @param key
 * @return {String|null}
 */
var getCookie = function(key) {
	var decode = function(value) {return decodeURIComponent(value.replace(/\+/g, ' '));};
	var cookies = document.cookie.split('; ');
	for (var i = 0, l = cookies.length; i < l; i++) {
		var parts = cookies[i].split('=');
		if (decode(parts.shift()) === key) {
			//success; found the key!
			return decode(parts.join('='));
		}
	}
	//failure; no such key
	return null;
}

/**
 * Takes any of the various forms of SFDC hostnames and spits out a "standard" format
 * @return {String}
 */

/**
 * Get URL parameters
 * @return {Array}
 */
var getUrlParam = function(param) {
	var hash, params = [];
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)    {
		hash = hashes[i].split('=');
		params.push(hash[0]);
		params[hash[0]] = hash[1];
	}
	return params[param] || null;
};

/**
 * Good ol Carlos - get record Id
 * @param url
 */
var getCurrentRecordId = function(url) {
	var href, iframehtml, id, theMatch, startParam;
	try{
		startParam = getUrlParam('timetracker_start');
	}catch(err){
		console.log(err);
	}

	var match;
	if (match = url.match(/\.com\/\w{15}|\.com\/\w{18}/)) {
		//success; captured id from salesforce.com/000xxxxxxxxxxxxXXX)
		return match[0].substr(5);
	} else if (match = url.match(/id\=\w{15}|id\=\w{18}/)) {
		//success; captured id from salesforce.com/id=000xxxxxxxxxxxxXXX
		return match[0].substr(3);
	} else {
		//failure; not on a page with an id
		return null;
	}
};

var context = {
	currentRecord : getCurrentRecordId(window.location.href),
	sessionId     : getCookie('sid'),
	orgId         : getCookie('sid').substring(0,15),
	userId        : '005E' + getCookie('sid_Client').substring(0,11),
	sid_Client    : getCookie('sid_Client'),
	pod           : null,
	sfhost        : null
};

( function() {
    var instance = null;
    var hostname = window.location.host;
    //modified from http://stackoverflow.com/a/9722468/740787
    var parts = hostname.split("\.");
    if (parts.length == 3)
        instance = parts[0];
    else if (parts.length == 5)
        instance = parts[1];
    else if (parts.length == 4 && parts[1] === "my")
        instance = parts[0]+".my";

    if(instance === null)
        throw new Error("Unable to determine salesforce instance");
    context.pod = instance;

    var isVf = hostname.indexOf(".visual.force.com") > 0;
    if(parts[0].indexOf("--") > 0 && isVf){ //using my domain & this is sandbox or managed vf page
        var subparts = parts[0].split("--");
        context.sfhost = hostname.replace("--"+subparts[subparts.length-1],"").replace(".visual.force.com",".salesforce.com").replace(instance,"my");
    }else{
        context.sfhost = context.pod + ".salesforce.com";
    }

}());

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
	if(request.command == 'getContext')
	    sendResponse(context);
	else if(request.command == 'getViewstateSize')
	    sendResponse(calculateViewstateSize());
	else
	    throw 'Unknown command ' + request.command;
});<|endoftext|>


<commit_before>
var moonlightSettings = {
    'map' : {
	'tilesets': [
	    { 'name': 'Macks-tilea2',
	      'path': 'gfx/Macks-tilea2.png'
	    },
	    { 'name': 'Macks-tilea3',
	      'path': 'gfx/Macks-tilea3.png'
	    }
	],
	'collisionRange': [385, 512],
	'path': 'gfx/junkmap.json'
    },
    'images': [
	{
	    'name': 'simplelight',
	    'path': 'gfx/lights/light-white-256px.png'
	}
    ],
    'spritesheets': [
	{
	    'name': 'player',
	    'path': 'gfx/sprites/sprite-player.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-1',
	    'path': 'gfx/sprites/sprite-townsfolk-male-1.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-2',
	    'path': 'gfx/sprites/sprite-townsfolk-male-2.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-3',
	    'path': 'gfx/sprites/sprite-townsfolk-male-3.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-4',
	    'path': 'gfx/sprites/sprite-townsfolk-male-4.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-1',
	    'path': 'gfx/sprites/sprite-townsfolk-female-1.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-2',
	    'path': 'gfx/sprites/sprite-townsfolk-female-2.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-3',
	    'path': 'gfx/sprites/sprite-townsfolk-female-3.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-4',
	    'path': 'gfx/sprites/sprite-townsfolk-female-4.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-guard-1',
	    'path': 'gfx/sprites/sprite-townsfolk-guard-1.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-guard-2',
	    'path': 'gfx/sprites/sprite-townsfolk-guard-2.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	}
    ],
    'animations': {
	'bipedwalkdown': {
	    'frames': [1, 2, 0],
	    'speed': 4,
	    'loop': true
	},
	'bipedwalkleft': {
	    'frames': [4, 5, 3],
	    'speed': 4,
	    'loop': true
	},
	'bipedwalkright': {
	    'frames': [7, 8, 6],
	    'speed': 4,
	    'loop': true
	},
	'bipedwalkup': {
	    'frames': [10, 11, 9],
	    'speed': 4,
	    'loop': true
	},
	'bipedrundown': {
	    'frames': [1, 2, 0],
	    'speed': 12,
	    'loop': true
	},
	'bipedrunleft': {
	    'frames': [4, 5, 3],
	    'speed': 12,
	    'loop': true
	},
	'bipedrunright': {
	    'frames': [7, 8, 6],
	    'speed': 12,
	    'loop': true
	},
	'bipedrunup': {
	    'frames': [10, 11, 9],
	    'speed': 12,
	    'loop': true
	}
    }
};

// Create torch objects
// Light constructor
var Light = function(game, x, y, radius, fade, color, flicker) {
    color = ( typeof color == undefined ? [255, 255, 255] : color );
    fade = ( typeof fade == undefined ? 0.25 : fade );
    radius = ( typeof radius == undefined ? 64 : radius );
    flicker = ( typeof flicker == undefined ? false : flicker );
    Phaser.Sprite.call(this, game, x, y, null);

    // Set the pivot point for this sprite to the center
    this.anchor.setTo(0.5, 0.5);
    this.color = color;
    this.radius = radius;
    this.fade = radius * fade
    this.rect = new Phaser.Rectangle(this.x, this.y, radius * 2, radius * 2)
    this.flicker = flicker;

};

// Lightes are a type of Phaser.Sprite
Light.prototype = Object.create(Phaser.Sprite.prototype);
Light.prototype.constructor = Light;

var GameState = function(game) {
}

GameState.prototype.addAnimation = function(obj, anim)
{
    a = moonlightSettings['animations'][anim]
    obj.animations.add(anim, a['frames'], a['speed'], a['loop'])
}

GameState.prototype.preload = function()
{
    for (var k in moonlightSettings['map']['tilesets']) {
	var ts = moonlightSettings['map']['tilesets'][k];
	this.load.image(ts['name'], ts['path']);
    }
    for (var k in moonlightSettings['images']) {
	var i = moonlightSettings['images'][k];
	this.load.image(i['name'], i['path']);
    }
    for (var k in moonlightSettings['spritesheets']) {
	var s = moonlightSettings['spritesheets'][k]
	game.load.spritesheet(s['name'], s['path'], s['width'], s['height'], s['frames'])
    }
    this.load.tilemap('map',
		      moonlightSettings['map']['path'],
		      null,
		      Phaser.Tilemap.TILED_JSON);
}

GameState.prototype.create = function()
{
    map = this.add.tilemap('map');
    for (var k in moonlightSettings['map']['tilesets']) {
	var ts = moonlightSettings['map']['tilesets'][k];
	map.addTilesetImage(ts['name']);
    }
    layer = map.createLayer('Tile Layer 1');
    layer.resizeWorld();
    map.setCollisionBetween(
	moonlightSettings['map']['collisionRange'][0],
	moonlightSettings['map']['collisionRange'][1]
    );

    player = this.add.sprite(10, 10, 'player');
    this.physics.arcade.enable(player);
    player.body.collideWorldBounds = true;

    this.addAnimation(player, 'bipedwalkleft');
    this.addAnimation(player, 'bipedwalkright');
    this.addAnimation(player, 'bipedwalkup');
    this.addAnimation(player, 'bipedwalkdown');
    this.addAnimation(player, 'bipedrunleft');
    this.addAnimation(player, 'bipedrunright');
    this.addAnimation(player, 'bipedrunup');
    this.addAnimation(player, 'bipedrundown');

    this.camera.follow(player, Phaser.Camera.FOLLOW_TOPDOWN);
    controls = game.input.keyboard.createCursorKeys();

    this.game.time.advancedTiming = true;
    this.fpsText = this.game.add.text(
        20, 20, '', { font: '16px Arial', fill: '#ffffff' }
    );
    this.fpsText.fixedToCamera = true;

    this.shadowTexture = game.add.bitmapData(game.world.width, game.world.height);

    // Create an object that will use the bitmap as a texture
    this.shadowSprite = game.add.image(0, 0, this.shadowTexture);

    // Set the blend mode to MULTIPLY. This will darken the colors of
    // everything below this sprite.
    this.shadowSprite.blendMode = Phaser.blendModes.MULTIPLY;

    // Create the lights
    this.staticLights = game.add.group();
    for (i = 0; i < 20 ; i++ ) {
	this.staticLights.add(
	    new Light(game,
		      game.rnd.integerInRange(0, game.width),
		      game.rnd.integerInRange(0, game.height),
		      game.rnd.integerInRange(0, 128),
		      game.rnd.realInRange(0.0, 1.0),
		      [
			  game.rnd.integerInRange(0, 255),
			  game.rnd.integerInRange(0, 255),
			  game.rnd.integerInRange(0, 255)
		      ],
		      flicker = [true, false][game.rnd.integerInRange(0, 1)]
		 )
	);
    }
    //this.movingLight = new Light(game, game.width/2, game.height/2);
    //this.lights.add(this.movingLight);
}

GameState.prototype.updateShadowTexture = function() {
    // This function updates the shadow texture (this.shadowTexture).
    // First, it fills the entire texture with a dark shadow color.
    // Then it draws a white circle centered on the pointer position.
    // Because the texture is drawn to the screen using the MULTIPLY
    // blend mode, the dark areas of the texture make all of the colors
    // underneath it darker, while the white area is unaffected.

    // Draw shadow
    this.shadowTexture.context.fillStyle = 'rgb(50, 50, 50)';
    this.shadowTexture.context.fillRect(0, 0, game.world.width, game.world.height);

    // Iterate through each of the lights and draw the glow
    this.staticLights.forEach(function(light) {
	var r1 = new Phaser.Rectangle(this.game.camera.x,
				      this.game.camera.y,
				      this.game.camera.width,
				      this.game.camera.height);
	if ( ! light.rect.intersects(r1) ) {
	    return;
	}
        // Randomly change the radius each frame
	if ( light.flicker ) {
            var radius = light.radius + game.rnd.integerInRange(1,10);
	} else {
	    var radius = light.radius;
	}

        // Draw circle of light with a soft edge
        var gradient =
            this.shadowTexture.context.createRadialGradient(
                light.x + 16, light.y + 16, light.fade,
                light.x + 16, light.y + 16, radius);
        gradient.addColorStop(0, 'rgba(' + light.color[0] + ',' + light.color[1] + ',' + light.color[2] +', 1.0)');
        gradient.addColorStop(1, 'rgba(' + light.color[0] + ',' + light.color[1] + ',' + light.color[2] +', 0.0)');

        this.shadowTexture.context.beginPath();
        this.shadowTexture.context.fillStyle = gradient;
        this.shadowTexture.context.arc(light.x + 16, light.y + 16, radius, 0, Math.PI*2);
        this.shadowTexture.context.fill();
    }, this);

    // This just tells the engine it should update the texture cache
    this.shadowTexture.dirty = true;
};

GameState.prototype.setSpriteMovement = function(spr, running, dir)
{
    var x = 0;
    var y = 0;

    if ( running ) {
	x = 200;
	y = 200;
	spr.animations.play("bipedrun" + dir);
    } else {
	x = 75;
	y = 75;
	spr.animations.play("bipedwalk" + dir);
    }

    if ( dir == "left" ) {
	spr.body.velocity.x = -x;
	spr.body.velocity.y = 0;
    } else if ( dir == "right" ) {
	spr.body.velocity.x = x;
	spr.body.velocity.y = 0;
    } else if ( dir == "up" ) {
	spr.body.velocity.x = 0;
	spr.body.velocity.y = -y;
    } else if ( dir == "down" ) {
	spr.body.velocity.x = 0;
	spr.body.velocity.y = y;
    }
}

GameState.prototype.check_input = function()
{

    player.body.velocity.x = 0;
    player.body.velocity.y = 0;
    velocityMod = 0;

    runningSpeed = {true: 150, false: 75}

    if ( controls.up.isDown) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'up');
    } else if ( controls.down.isDown ) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'down');
    } else if ( controls.left.isDown ) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'left');
    } else if ( controls.right.isDown ) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'right');
    } else {
	player.animations.stop(null, true);
    }
}

GameState.prototype.update = function()
{
    if (game.time.fps !== 0) {
        this.fpsText.setText(game.time.fps + ' FPS');
    }

    this.check_input();
    this.physics.arcade.collide(player, layer);
    //this.movingLight.x = player.x;
    //this.movingLight.y = player.y;
    this.updateShadowTexture();
}

var game = new Phaser.Game(640, 480, Phaser.AUTO, '');
game.state.add('game', GameState, true);
<commit_msg>Torch becomes Light, flicker becomes optional<commit_after>
var moonlightSettings = {
    'map' : {
	'tilesets': [
	    { 'name': 'Macks-tilea2',
	      'path': 'gfx/Macks-tilea2.png'
	    },
	    { 'name': 'Macks-tilea3',
	      'path': 'gfx/Macks-tilea3.png'
	    }
	],
	'collisionRange': [385, 512],
	'path': 'gfx/junkmap.json'
    },
    'images': [
	{
	    'name': 'simplelight',
	    'path': 'gfx/lights/light-white-256px.png'
	}
    ],
    'spritesheets': [
	{
	    'name': 'player',
	    'path': 'gfx/sprites/sprite-player.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-1',
	    'path': 'gfx/sprites/sprite-townsfolk-male-1.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-2',
	    'path': 'gfx/sprites/sprite-townsfolk-male-2.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-3',
	    'path': 'gfx/sprites/sprite-townsfolk-male-3.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-male-4',
	    'path': 'gfx/sprites/sprite-townsfolk-male-4.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-1',
	    'path': 'gfx/sprites/sprite-townsfolk-female-1.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-2',
	    'path': 'gfx/sprites/sprite-townsfolk-female-2.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-3',
	    'path': 'gfx/sprites/sprite-townsfolk-female-3.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-female-4',
	    'path': 'gfx/sprites/sprite-townsfolk-female-4.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-guard-1',
	    'path': 'gfx/sprites/sprite-townsfolk-guard-1.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	},
	{
	    'name': 'townsfolk-guard-2',
	    'path': 'gfx/sprites/sprite-townsfolk-guard-2.png',
	    'width': 32,
	    'height': 32,
	    'frames': 12
	}
    ],
    'animations': {
	'bipedwalkdown': {
	    'frames': [1, 2, 0],
	    'speed': 4,
	    'loop': true
	},
	'bipedwalkleft': {
	    'frames': [4, 5, 3],
	    'speed': 4,
	    'loop': true
	},
	'bipedwalkright': {
	    'frames': [7, 8, 6],
	    'speed': 4,
	    'loop': true
	},
	'bipedwalkup': {
	    'frames': [10, 11, 9],
	    'speed': 4,
	    'loop': true
	},
	'bipedrundown': {
	    'frames': [1, 2, 0],
	    'speed': 12,
	    'loop': true
	},
	'bipedrunleft': {
	    'frames': [4, 5, 3],
	    'speed': 12,
	    'loop': true
	},
	'bipedrunright': {
	    'frames': [7, 8, 6],
	    'speed': 12,
	    'loop': true
	},
	'bipedrunup': {
	    'frames': [10, 11, 9],
	    'speed': 12,
	    'loop': true
	}
    }
};

// Create torch objects
// Light constructor
var Light = function(game, x, y, radius, fade, color, flicker) {
    color = ( typeof color == undefined ? [255, 255, 255] : color );
    fade = ( typeof fade == undefined ? 0.25 : fade );
    radius = ( typeof radius == undefined ? 64 : radius );
    flicker = ( typeof flicker == undefined ? false : flicker );
    Phaser.Sprite.call(this, game, x, y, null);

    // Set the pivot point for this sprite to the center
    this.anchor.setTo(0.5, 0.5);
    this.color = color;
    this.radius = radius;
    this.fade = radius * fade
    this.rect = new Phaser.Rectangle(this.x, this.y, radius * 2, radius * 2)
    this.flicker = flicker;

};

// Lightes are a type of Phaser.Sprite
Light.prototype = Object.create(Phaser.Sprite.prototype);
Light.prototype.constructor = Light;

var GameState = function(game) {
}

GameState.prototype.addAnimation = function(obj, anim)
{
    a = moonlightSettings['animations'][anim]
    obj.animations.add(anim, a['frames'], a['speed'], a['loop'])
}

GameState.prototype.preload = function()
{
    for (var k in moonlightSettings['map']['tilesets']) {
	var ts = moonlightSettings['map']['tilesets'][k];
	this.load.image(ts['name'], ts['path']);
    }
    for (var k in moonlightSettings['images']) {
	var i = moonlightSettings['images'][k];
	this.load.image(i['name'], i['path']);
    }
    for (var k in moonlightSettings['spritesheets']) {
	var s = moonlightSettings['spritesheets'][k]
	game.load.spritesheet(s['name'], s['path'], s['width'], s['height'], s['frames'])
    }
    this.load.tilemap('map',
		      moonlightSettings['map']['path'],
		      null,
		      Phaser.Tilemap.TILED_JSON);
}

GameState.prototype.create = function()
{
    map = this.add.tilemap('map');
    for (var k in moonlightSettings['map']['tilesets']) {
	var ts = moonlightSettings['map']['tilesets'][k];
	map.addTilesetImage(ts['name']);
    }
    layer = map.createLayer('Tile Layer 1');
    layer.resizeWorld();
    map.setCollisionBetween(
	moonlightSettings['map']['collisionRange'][0],
	moonlightSettings['map']['collisionRange'][1]
    );

    player = this.add.sprite(10, 10, 'player');
    this.physics.arcade.enable(player);
    player.body.collideWorldBounds = true;

    this.addAnimation(player, 'bipedwalkleft');
    this.addAnimation(player, 'bipedwalkright');
    this.addAnimation(player, 'bipedwalkup');
    this.addAnimation(player, 'bipedwalkdown');
    this.addAnimation(player, 'bipedrunleft');
    this.addAnimation(player, 'bipedrunright');
    this.addAnimation(player, 'bipedrunup');
    this.addAnimation(player, 'bipedrundown');

    this.camera.follow(player, Phaser.Camera.FOLLOW_TOPDOWN);
    controls = game.input.keyboard.createCursorKeys();

    this.game.time.advancedTiming = true;
    this.fpsText = this.game.add.text(
        20, 20, '', { font: '16px Arial', fill: '#ffffff' }
    );
    this.fpsText.fixedToCamera = true;

    this.shadowTexture = game.add.bitmapData(game.world.width, game.world.height);
    this.shadowTextureColor = 'rgb(10, 10, 10)';

    // Create an object that will use the bitmap as a texture
    this.shadowSprite = game.add.image(0, 0, this.shadowTexture);

    // Set the blend mode to MULTIPLY. This will darken the colors of
    // everything below this sprite.
    this.shadowSprite.blendMode = Phaser.blendModes.MULTIPLY;

    // Create the lights
    this.staticLights = game.add.group();
    for (i = 0; i < 20 ; i++ ) {
	this.staticLights.add(
	    new Light(game,
		      game.rnd.integerInRange(0, game.width),
		      game.rnd.integerInRange(0, game.height),
		      game.rnd.integerInRange(0, 128),
		      game.rnd.realInRange(0.0, 1.0),
		      [
			  game.rnd.integerInRange(0, 255),
			  game.rnd.integerInRange(0, 255),
			  game.rnd.integerInRange(0, 255)
		      ],
		      flicker = [true, false][game.rnd.integerInRange(0, 1)]
		 )
	);
    }
    //this.movingLight = new Light(game, game.width/2, game.height/2);
    //this.lights.add(this.movingLight);
}

GameState.prototype.updateShadowTexture = function() {
    // This function updates the shadow texture (this.shadowTexture).
    // First, it fills the entire texture with a dark shadow color.
    // Then it draws a white circle centered on the pointer position.
    // Because the texture is drawn to the screen using the MULTIPLY
    // blend mode, the dark areas of the texture make all of the colors
    // underneath it darker, while the white area is unaffected.

    // Draw shadow
    this.shadowTexture.context.fillStyle = this.shadowTextureColor;
    this.shadowTexture.context.fillRect(0, 0, game.world.width, game.world.height);

    // Iterate through each of the lights and draw the glow
    this.staticLights.forEach(function(light) {
	// Don't draw lights that aren't on screen
	var r1 = new Phaser.Rectangle(this.game.camera.x,
				      this.game.camera.y,
				      this.game.camera.width,
				      this.game.camera.height);
	if ( ! light.rect.intersects(r1) ) {
	    return;
	}

	if ( light.flicker ) {
            // Randomly change the radius each frame
            var radius = light.radius + game.rnd.integerInRange(1,10);
	} else {
	    var radius = light.radius;
	}

        // Draw circle of light with a soft edge
        var gradient =
            this.shadowTexture.context.createRadialGradient(
                light.x + 16, light.y + 16, light.fade,
                light.x + 16, light.y + 16, radius);
        gradient.addColorStop(0, 'rgba(' + light.color[0] + ',' + light.color[1] + ',' + light.color[2] +', 1.0)');
        gradient.addColorStop(1, 'rgba(' + light.color[0] + ',' + light.color[1] + ',' + light.color[2] +', 0.0)');

        this.shadowTexture.context.beginPath();
        this.shadowTexture.context.fillStyle = gradient;
        this.shadowTexture.context.arc(light.x + 16, light.y + 16, radius, 0, Math.PI*2);
        this.shadowTexture.context.fill();
    }, this);

    // This just tells the engine it should update the texture cache
    this.shadowTexture.dirty = true;
};

GameState.prototype.setSpriteMovement = function(spr, running, dir)
{
    var x = 0;
    var y = 0;

    if ( running ) {
	x = 200;
	y = 200;
	spr.animations.play("bipedrun" + dir);
    } else {
	x = 75;
	y = 75;
	spr.animations.play("bipedwalk" + dir);
    }

    if ( dir == "left" ) {
	spr.body.velocity.x = -x;
	spr.body.velocity.y = 0;
    } else if ( dir == "right" ) {
	spr.body.velocity.x = x;
	spr.body.velocity.y = 0;
    } else if ( dir == "up" ) {
	spr.body.velocity.x = 0;
	spr.body.velocity.y = -y;
    } else if ( dir == "down" ) {
	spr.body.velocity.x = 0;
	spr.body.velocity.y = y;
    }
}

GameState.prototype.check_input = function()
{

    player.body.velocity.x = 0;
    player.body.velocity.y = 0;
    velocityMod = 0;

    runningSpeed = {true: 150, false: 75}

    if ( controls.up.isDown) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'up');
    } else if ( controls.down.isDown ) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'down');
    } else if ( controls.left.isDown ) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'left');
    } else if ( controls.right.isDown ) {
	this.setSpriteMovement(player, controls.up.shiftKey, 'right');
    } else {
	player.animations.stop(null, true);
    }
}

GameState.prototype.update = function()
{
    if (game.time.fps !== 0) {
        this.fpsText.setText(game.time.fps + ' FPS');
    }

    this.check_input();
    this.physics.arcade.collide(player, layer);
    //this.movingLight.x = player.x;
    //this.movingLight.y = player.y;
    this.updateShadowTexture();
}

var game = new Phaser.Game(640, 480, Phaser.AUTO, '');
game.state.add('game', GameState, true);
<|endoftext|>