<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

/* eslint no-shadow: ['warn', {allow: ['file']}] */

import Dropzone from 'dropzone';
import 'dropzone/dist/dropzone.css';

(function(global) {
    $(document).ready(function() {
        Dropzone.autoDiscover = false;
    });

    global.setupDropzone = function(element) {
        var $dz = $(element);
        var $form = $dz.closest('form');
        var $flashArea = $form.find('.flashed-messages');
        var options = {
            clickable: element + ' .dropzone-inner',
            previewsContainer: element + ' .dropzone-previews',
            autoProcessQueue: false,

            init: function() {
                var $button = $form.find('input[type="submit"], .js-dropzone-upload');
                var self = this;
                var files = $dz.data('value');

                function addFile(file) {
                    var existingFile = {
                        name: file.filename,
                        id: file.id,
                        size: file.size,
                        accepted: true
                    };

                    self.emit('addedfile', existingFile);
                    $dz.find('.dz-progress').hide();
                    self.files.push(existingFile);

                    /* Disable opening the upload dialog when clicking on the file's preview element */
                    $dz.find('.dz-preview').on('click', function(e) {
                        e.stopPropagation();
                    });

                    // Check if the existing file is an image and add the image preview.
                    if (file.content_type.match(/image\/.*/) && file.url) {
                        $dz.find('.dz-image > img').attr('src', file.url);
                        $dz.find('.dz-image > img').attr('width', '120px');
                        $dz.find('.dz-preview').removeClass('dz-file-preview').addClass('dz-image-preview');
                    }
                }

                if (files) {
                    if (options.uploadMultiple) {
                        files.forEach(addFile);
                    } else {
                        addFile(files);
                    }
                }

                // We'll first remove the default 'submit' handler
                $form.off('submit').on('submit', function(e) {
                    var evt = $.Event('ajaxForm:validateBeforeSubmit');
                    $(this).trigger(evt);
                    if (!evt.isDefaultPrevented()) {
                        $button.prop('disabled', true);
                        $.each(self.getRejectedFiles(), function(index, file) {
                            self.removeFile(file);
                        });
                        if (self.getQueuedFiles().length) {
                            e.preventDefault();
                            e.stopPropagation();
                            $dz.find('.dz-progress').show();
                            self.processQueue();
                        }
                    }
                });

                self.on('addedfile', function(file) {
                    if (!options.uploadMultiple && self.files.length > 1) {
                        self.removeFile(self.files[0]);
                    }

                    // force change in form, so that we can process
                    // the 'change' event
                    $button.prop('disabled', false);
                    $form.find('.change-trigger').val('added-file');
                    $form.trigger('change');

                    $dz.find('.dz-message').hide();
                    $dz.find('.dz-progress').hide();
                    $(file.previewElement).on('click', function(e) {
                        e.stopPropagation();
                    });
                });

                self.on('removedfile', function(file) {
                    $button.prop('disabled', false);
                    if (self.files.length === 0) {
                        // force change in form, so that we can process the 'change' event
                        $form.find('.change-trigger').val('no-file');
                        $form.trigger('change');
                        $dz.find('.dz-message').show();
                    }

                    if (options.editable) {
                        var $field = $form.find('.deleted-files');
                        var deletedFiles = JSON.parse($field.val());
                        deletedFiles.push(file.id);
                        $field.val(JSON.stringify(deletedFiles));
                    }
                });

                self.on(options.uploadMultiple ? 'sendingmultiple' : 'sending', function() {
                    $form.trigger('ajaxForm:beforeSubmit');
                });

                self.on('success', function(e, response) {
                    if (options.handleFlashes) {
                        handleFlashes(response, true, $flashArea);
                    }

                    $dz.data('value', response.content);
                    $form.find('.change-trigger').val($dz.data('value') ? 'uploaded-file' : 'no-file');
                    $form.trigger('indico:fieldsSaved', response);
                    $form.trigger('ajaxForm:success', [response]);
                });

                self.on('error', function(e, msg, xhr) {
                    if (xhr) {
                        var evt = $.Event('ajaxForm:error');
                        $form.trigger(evt, [xhr]);
                        if (!evt.isDefaultPrevented()) {
                            handleAjaxError(xhr);
                        }
                    }
                });
            }
        };

        _.extend(options, $dz.data('options'));
        var param = options.paramName;
        options.paramName = function() {
            return param;
        };

        // include the csrf token in case the dropzone is submitting data to a
        // seperate endpoint than the form's action
        if (options.url) {
            options.params = {
                csrf_token: $form.find('#csrf_token').val()
            };
            $dz.dropzone(options);
        } else {
            $form.dropzone(options);
        }

        $form.data('dropzoneField', $dz[0]);
    };
})(window);
<commit_msg>Make Dropzone object available globally<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

/* eslint no-shadow: ['warn', {allow: ['file']}] */

import Dropzone from 'dropzone';
import 'dropzone/dist/dropzone.css';

(function(global) {
    global.Dropzone = Dropzone;

    $(document).ready(function() {
        Dropzone.autoDiscover = false;
    });

    global.setupDropzone = function(element) {
        var $dz = $(element);
        var $form = $dz.closest('form');
        var $flashArea = $form.find('.flashed-messages');
        var options = {
            clickable: element + ' .dropzone-inner',
            previewsContainer: element + ' .dropzone-previews',
            autoProcessQueue: false,

            init: function() {
                var $button = $form.find('input[type="submit"], .js-dropzone-upload');
                var self = this;
                var files = $dz.data('value');

                function addFile(file) {
                    var existingFile = {
                        name: file.filename,
                        id: file.id,
                        size: file.size,
                        accepted: true
                    };

                    self.emit('addedfile', existingFile);
                    $dz.find('.dz-progress').hide();
                    self.files.push(existingFile);

                    /* Disable opening the upload dialog when clicking on the file's preview element */
                    $dz.find('.dz-preview').on('click', function(e) {
                        e.stopPropagation();
                    });

                    // Check if the existing file is an image and add the image preview.
                    if (file.content_type.match(/image\/.*/) && file.url) {
                        $dz.find('.dz-image > img').attr('src', file.url);
                        $dz.find('.dz-image > img').attr('width', '120px');
                        $dz.find('.dz-preview').removeClass('dz-file-preview').addClass('dz-image-preview');
                    }
                }

                if (files) {
                    if (options.uploadMultiple) {
                        files.forEach(addFile);
                    } else {
                        addFile(files);
                    }
                }

                // We'll first remove the default 'submit' handler
                $form.off('submit').on('submit', function(e) {
                    var evt = $.Event('ajaxForm:validateBeforeSubmit');
                    $(this).trigger(evt);
                    if (!evt.isDefaultPrevented()) {
                        $button.prop('disabled', true);
                        $.each(self.getRejectedFiles(), function(index, file) {
                            self.removeFile(file);
                        });
                        if (self.getQueuedFiles().length) {
                            e.preventDefault();
                            e.stopPropagation();
                            $dz.find('.dz-progress').show();
                            self.processQueue();
                        }
                    }
                });

                self.on('addedfile', function(file) {
                    if (!options.uploadMultiple && self.files.length > 1) {
                        self.removeFile(self.files[0]);
                    }

                    // force change in form, so that we can process
                    // the 'change' event
                    $button.prop('disabled', false);
                    $form.find('.change-trigger').val('added-file');
                    $form.trigger('change');

                    $dz.find('.dz-message').hide();
                    $dz.find('.dz-progress').hide();
                    $(file.previewElement).on('click', function(e) {
                        e.stopPropagation();
                    });
                });

                self.on('removedfile', function(file) {
                    $button.prop('disabled', false);
                    if (self.files.length === 0) {
                        // force change in form, so that we can process the 'change' event
                        $form.find('.change-trigger').val('no-file');
                        $form.trigger('change');
                        $dz.find('.dz-message').show();
                    }

                    if (options.editable) {
                        var $field = $form.find('.deleted-files');
                        var deletedFiles = JSON.parse($field.val());
                        deletedFiles.push(file.id);
                        $field.val(JSON.stringify(deletedFiles));
                    }
                });

                self.on(options.uploadMultiple ? 'sendingmultiple' : 'sending', function() {
                    $form.trigger('ajaxForm:beforeSubmit');
                });

                self.on('success', function(e, response) {
                    if (options.handleFlashes) {
                        handleFlashes(response, true, $flashArea);
                    }

                    $dz.data('value', response.content);
                    $form.find('.change-trigger').val($dz.data('value') ? 'uploaded-file' : 'no-file');
                    $form.trigger('indico:fieldsSaved', response);
                    $form.trigger('ajaxForm:success', [response]);
                });

                self.on('error', function(e, msg, xhr) {
                    if (xhr) {
                        var evt = $.Event('ajaxForm:error');
                        $form.trigger(evt, [xhr]);
                        if (!evt.isDefaultPrevented()) {
                            handleAjaxError(xhr);
                        }
                    }
                });
            }
        };

        _.extend(options, $dz.data('options'));
        var param = options.paramName;
        options.paramName = function() {
            return param;
        };

        // include the csrf token in case the dropzone is submitting data to a
        // seperate endpoint than the form's action
        if (options.url) {
            options.params = {
                csrf_token: $form.find('#csrf_token').val()
            };
            $dz.dropzone(options);
        } else {
            $form.dropzone(options);
        }

        $form.data('dropzoneField', $dz[0]);
    };
})(window);
<|endoftext|>


<commit_before>/* ========================================================================
 * Section
 * ======================================================================== */

var orders = [];

document.addEventListener('DOMContentLoaded', function() {

  // get orders from page

  chrome.tabs.executeScript(null, {
    code: "\
      var orders = [];\
      if (document.location.hash.indexOf('#history') == -1) {\
        var my_name = document.querySelector('#h-profilename').textContent;\
        var name_tags = document.querySelectorAll('h1');\
        var order_tags = document.querySelectorAll('div.details');\
        for (var i = 0; i < name_tags.length; i++) {\
          var tds = order_tags[i].querySelectorAll('footer td');\
          orders.push({\
            name: name_tags[i].textContent.replace('Selecțiile mele', my_name).trim(),\
            price: tds[tds.length - 1].textContent.trim(),\
          });\
        }\
      } else {\
        var order_tags = document.querySelectorAll('.history-diners .container-marginTBMedium');\
        for (var i = 0; i < order_tags.length; i++) {\
          var tds = order_tags[i].querySelectorAll('footer td');\
          orders.push({\
            name: order_tags[i].querySelector('h4').textContent.trim(),\
            price: tds[tds.length - 1].textContent.trim(),\
          });\
        }\
      }\
      JSON.stringify(orders);\
    "
  }, function(orders) {
    orders = JSON.parse(orders);
    orders.sort(function(a, b) {
      var x = a.name.toLowerCase();
      var y = b.name.toLowerCase();
      return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });

    // render the checklist

    var html = '';
    for (var i = 0; i < orders.length; i++) {
      html = html + '
';
      html = html + '' + orders[i].name + '	';
      html = html + '' + orders[i].price + '	';
      html = html + '<input id="check' + i + '" type="checkbox" data-name="' + orders[i].name + '"' + (orders[i].payed ? ' checked ' : '') + '>	';
      html = html + '
';
    }
    document.querySelector('tbody').innerHTML = html;
    var checks = document.querySelectorAll('td input');
    for (var i = 0; i < checks.length; i++) {
      checks[i].addEventListener('click', function(event) {
        var name = this.getAttribute('data-name');
        for (var j = 0; j < orders.length; j++) {
          if (orders[j].name == name) {
            orders[j].payed = this.checked;
            chrome.tabs.executeScript(null, {
              code: "sessionStorage.setItem('" + name + "', " + this.checked + ")"
            });
          }
        }
      });
    }

    // get checkbox statuses from parent page

    for (var i = 0; i < orders.length; i++) {
      chrome.tabs.executeScript(null, {
        code: i.toString() + " + ':' + sessionStorage.getItem('" + orders[i].name + "')"
      }, function(data) {
        data = data[0].split(':');
        var index = parseInt(data[0]);
        var value = (data[1] == 'true' ? true : false);
        orders[index].payed = value;
        document.querySelector('input[data-name="' + orders[index].name + '"]').checked = value;
      });
    }
  });
});

/* ========================================================================
 * Section
 * ======================================================================== */
<commit_msg>Forgot how to English<commit_after>/* ========================================================================
 * Section
 * ======================================================================== */

var orders = [];

document.addEventListener('DOMContentLoaded', function() {

  // get orders from page

  chrome.tabs.executeScript(null, {
    code: "\
      var orders = [];\
      if (document.location.hash.indexOf('#history') == -1) {\
        var my_name = document.querySelector('#h-profilename').textContent;\
        var name_tags = document.querySelectorAll('h1');\
        var order_tags = document.querySelectorAll('div.details');\
        for (var i = 0; i < name_tags.length; i++) {\
          var tds = order_tags[i].querySelectorAll('footer td');\
          orders.push({\
            name: name_tags[i].textContent.replace('Selecțiile mele', my_name).trim(),\
            price: tds[tds.length - 1].textContent.trim(),\
          });\
        }\
      } else {\
        var order_tags = document.querySelectorAll('.history-diners .container-marginTBMedium');\
        for (var i = 0; i < order_tags.length; i++) {\
          var tds = order_tags[i].querySelectorAll('footer td');\
          orders.push({\
            name: order_tags[i].querySelector('h4').textContent.trim(),\
            price: tds[tds.length - 1].textContent.trim(),\
          });\
        }\
      }\
      JSON.stringify(orders);\
    "
  }, function(orders) {
    orders = JSON.parse(orders);
    orders.sort(function(a, b) {
      var x = a.name.toLowerCase();
      var y = b.name.toLowerCase();
      return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });

    // render the checklist

    var html = '';
    for (var i = 0; i < orders.length; i++) {
      html = html + '
';
      html = html + '' + orders[i].name + '	';
      html = html + '' + orders[i].price + '	';
      html = html + '<input id="check' + i + '" type="checkbox" data-name="' + orders[i].name + '"' + (orders[i].paid ? ' checked ' : '') + '>	';
      html = html + '
';
    }
    document.querySelector('tbody').innerHTML = html;
    var checks = document.querySelectorAll('td input');
    for (var i = 0; i < checks.length; i++) {
      checks[i].addEventListener('click', function(event) {
        var name = this.getAttribute('data-name');
        for (var j = 0; j < orders.length; j++) {
          if (orders[j].name == name) {
            orders[j].paid = this.checked;
            chrome.tabs.executeScript(null, {
              code: "sessionStorage.setItem('" + name + "', " + this.checked + ")"
            });
          }
        }
      });
    }

    // get checkbox statuses from parent page

    for (var i = 0; i < orders.length; i++) {
      chrome.tabs.executeScript(null, {
        code: i.toString() + " + ':' + sessionStorage.getItem('" + orders[i].name + "')"
      }, function(data) {
        data = data[0].split(':');
        var index = parseInt(data[0]);
        var value = (data[1] == 'true' ? true : false);
        orders[index].paid = value;
        document.querySelector('input[data-name="' + orders[index].name + '"]').checked = value;
      });
    }
  });
});

/* ========================================================================
 * Section
 * ======================================================================== */
<|endoftext|>


<commit_before>var assert = require('assert');
var _ = require('@sailshq/lodash');

describe('Association Interface', function() {

  describe('n:m association :: .destroy()', function() {

    /////////////////////////////////////////////////////
    // TEST SETUP
    ////////////////////////////////////////////////////

    var driverRecord;

    before(function(done) {
      Associations.Driver.create({ name: 'manymany destroy'}, function(err, driver) {
        if(err) return done(err);

        driverRecord = driver;

        var taxis = [];
        for(var i=0; i<2; i++) {
          driverRecord.taxis.add({ medallion: i });
        }

        driverRecord.save(function(err) {
          if(err) return done(err);
          done();
        });
      });
    });

    /////////////////////////////////////////////////////
    // TEST METHODS
    ////////////////////////////////////////////////////

    it.skip('should remove join table records when a parent is destroyed', function(done) {

      var parentId = driverRecord.id;

      Associations.Driver.destroy({ name: 'manymany destroy' })
      .exec(function(err, status) {
        assert.ifError(err);

        Associations.Driver_taxis__taxi_drivers.find({ driver_taxis: parentId })
        .exec(function(err, records) {
          assert.ifError(err);
          assert.strictEqual(records.length, 0);
          done();
        });
      });
    });

  });

  describe('when criteria returns no results', function () {

    /////////////////////////////////////////////////////
    // TEST SETUP
    ////////////////////////////////////////////////////

    var driverRecord;

    before(function(done) {
      Associations.Driver.create({ name: 'manymany destroy'}, function(err, driver) {
        if(err) return done(err);

        driverRecord = driver;

        var taxis = [];
        for(var i=0; i<2; i++) {
          driverRecord.taxis.add({ medallion: i });
        }

        driverRecord.save(function(err) {
          if(err) return done(err);
          done();
        });
      });
    });

    /////////////////////////////////////////////////////
    // TEST METHODS
    ////////////////////////////////////////////////////

    it('should not destroy any join table records', function (done) {
      Associations.Driver.destroy({ name: 'manymany destroy_foo' }, function (err, status) {
        assert.ifError(err);

        // Find records in the join table
        Associations.Driver_taxis__taxi_drivers.find({ driver_taxis: driverRecord.id }).exec(function(err, records) {
          if(err) return done(err);
          if(!records.length) {
            return done(new Error('Removed all the join table records!'));
          }

          return done();
        });
      });
    });

  });

  describe('destroying an entire collection', function () {

    it('should not result in an error', function (done) {
      Associations.Driver.destroy(function (err, status) {
        assert.ifError(err);
        done();
      });
    });
  });

  describe('destroying an entire collection, now empty', function () {

    it('should not result in an error', function (done) {
      Associations.Driver.destroy(function (err, status) {
        assert.ifError(err);
        done();
      });
    });
  });

});
<commit_msg>remove destroy test<commit_after><|endoftext|>


<commit_before>let motivos = [
	'No começo era legal, mas agora eu quero matar todo mundo'
	, 'Uma capivara me disse pra fazer isso'
	, 'Papai quer que eu faça medicina'
	, 'Acabou o café'
	, 'Acabou o leite do café'
	, 'Acabou o açucar do café'
	, 'Nunca posso nada nessa p****!'
	, 'Demissão não se pede se ganha!'
	, 'A empresa usa Sybase'
	, 'O comercial vendeu uma feature que não existe no sistema'
	, 'Agendaram a homologação do sistema para às 18h de sexta'
	, 'Meu trabalho esta  matando a minha criatividade'
	, 'Patch de correção para um problema que foi criado por um patch anterior'
	, 'Deixaram pra contratar a consultoria quando começou a dar merda'
	, 'O planejamento do projeto se resume a fazer tudo no tempo'
	, 'Não entendi a change, mas os totais voltaram a bater'
];

document.getElementById('motivo').firstChild.innerText = motivos[Math.trunc(Math.random() * motivos.length)];
<commit_msg>Adicionado novos motivos (#9)<commit_after>let motivos = [
	'No começo era legal, mas agora eu quero matar todo mundo'
	, 'Uma capivara me disse pra fazer isso'
	, 'Papai quer que eu faça medicina'
	, 'Acabou o café'
	, 'Acabou o leite do café'
	, 'Acabou o açucar do café'
	, 'Nunca posso nada nessa p****!'
	, 'Demissão não se pede se ganha!'
	, 'A empresa usa Sybase'
	, 'O comercial vendeu uma feature que não existe no sistema'
	, 'Agendaram a homologação do sistema para às 18h de sexta'
	, 'Meu trabalho esta  matando a minha criatividade'
	, 'Patch de correção para um problema que foi criado por um patch anterior'
	, 'Deixaram pra contratar a consultoria quando começou a dar merda'
	, 'O planejamento do projeto se resume a fazer tudo no tempo'
	, 'Não entendi a change, mas os totais voltaram a bater'
	, 'A empresa está contratando programador PHP'
	, 'A empresa usa SVN'
];

document.getElementById('motivo').firstChild.innerText = motivos[Math.trunc(Math.random() * motivos.length)];
<|endoftext|>


<commit_before>
var ReactWeather = React.createClass({
  getInitialState: function() {
    return {
      citiesArr: [],
      userLocation: 'London'
    };
  },

  componentDidMount: function() {
    this._getCitysFromStorage();

    var self = this;
    self._getCityWeather('London', function(result) {
      if ( self.isMounted() ) {
        self.setState({
          temp: result.main.temp,
          icon: result.weather[0].icon,
          pressure: result.main.pressure,
          humidity: result.main.humidity
        });
      }
    });
  },

  componentWillUnmount: function() {
    this._setCitysToStorage();
  },

  _getCitysFromStorage: function() {
    //localStorage.removeItem('citiesArr');
    if(typeof localStorage['citiesArr'] === 'undefined') {
      localStorage['citiesArr'] = '[]';
    }

    this.setState({
      citiesArr: JSON.parse(localStorage['citiesArr'])
    });
  },

  _setCitysToStorage: function() {
    localStorage['citiesArr'] = JSON.stringify(this.state.citiesArr);
  },

  _getCityWeather: function(city, cb) {
    var appid = '2de143494c0b295cca9337e1e96b00e0';
    var url = 'http://api.openweathermap.org/data/2.5/weather';

    $.get(url, {q: city, appid: appid}, cb);
  },

  _addCity: function(city) {
    this.setState(function(state) {
      state.citiesArr = state.citysArr.push(city);
    });
  },

  inputHanler: function(event) {
    var str = document.getElementById("addCity").value;
    console.log('inputHandler activate: ' + str);
  },

  render: function () {
    var state = this.state;
    var iconLink = 'http://openweathermap.org/img/w/'+state.icon+'.png'
    console.log(state);
    return (

          Влажность: {state.humidity}

          Давление: {state.pressure}

          Температура: {state.temp}

          <input type='text' id='addCity' />
          <input type='submit' onClick={this.inputHanler} />

    );
  }
});

ReactDOM.render(
  <ReactWeather />,
  document.getElementById('ReactWeather')
);
<commit_msg>worked save in local storage<commit_after>
var ReactWeather = React.createClass({
  getInitialState: function() {
    return {
      citiesArr: [],
      userLocation: 'London'
    };
  },

  componentDidMount: function() {
    this._getCitysFromStorage();

    var self = this;
    self._getCityWeather('London', function(result) {
      if ( self.isMounted() ) {
        self.setState({
          temp: result.main.temp,
          icon: result.weather[0].icon,
          pressure: result.main.pressure,
          humidity: result.main.humidity
        });
      }
    });
  },

  componentDidUpdate: function() {
    this._setCitysToStorage();
  },

  _getCitysFromStorage: function() {
    //localStorage.removeItem('citiesArr');
    console.log(localStorage['citiesArr']);
    if(typeof localStorage['citiesArr'] === 'undefined') {
      localStorage['citiesArr'] = '[]';
    }

    this.setState({
      citiesArr: JSON.parse(localStorage['citiesArr'])
    });
  },

  _setCitysToStorage: function() {
    localStorage['citiesArr'] = JSON.stringify(this.state.citiesArr);
  },

  _getCityWeather: function(city, cb) {
    var appid = '2de143494c0b295cca9337e1e96b00e0';
    var url = 'http://api.openweathermap.org/data/2.5/weather';

    $.get(url, {q: city, appid: appid}, cb);
  },

  _addCity: function(city) {
    this.setState(function(state) {
      var temp = state.citiesArr;
      temp.push(city);
      state.citiesArr = temp;
    });
  },

  inputHanler: function(event) {
    var str = document.getElementById("addCity").value;
    console.log('inputHandler activate: ' + str);
    this._addCity(str);
  },

  render: function () {
    var state = this.state;
    var iconLink = 'http://openweathermap.org/img/w/'+state.icon+'.png'
    console.log(state);
    return (

          Влажность: {state.humidity}

          Давление: {state.pressure}

          Температура: {state.temp}

          <input type='text' id='addCity' />
          <input type='submit' onClick={this.inputHanler} />

    );
  }
});

ReactDOM.render(
  <ReactWeather />,
  document.getElementById('ReactWeather')
);
<|endoftext|>


<commit_before>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >= 8 && myDate.getHours() <=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailer=message.text;
          return bot.setProp('emailer', emailer)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${emailer} op de hoogte.`))
              .then(  function() {
                                    Smooch.updateUser({
                                            givenName: 'Doctor',
                                            surname: 'Who'
                                    });
                            }
                  )
            .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},

hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say(`Hoe heet je eigelijk? 😋`),
          receive: (bot, message) => {
              const Name = message.text;
              return bot.setProp('Name', Name)
                  .then(() => bot.say(`Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.`))
                  .then(() => 'processing')
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => 'pri'
// },

finish: {
receive: () => 'finish'
}
});
<commit_msg>few<commit_after>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >= 8 && myDate.getHours() <=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailer=message.text;
          return bot.setProp('emailer', emailer)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${emailer} op de hoogte.`))
              .then(  ( function() {
                                    Smooch.updateUser({
                                            givenName: 'Doctor',
                                            surname: 'Who'
                                    });
                            })
                          )
            .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},

hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say(`Hoe heet je eigelijk? 😋`),
          receive: (bot, message) => {
              const Name = message.text;
              return bot.setProp('Name', Name)
                  .then(() => bot.say(`Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.`))
                  .then(() => 'processing')
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => 'pri'
// },

finish: {
receive: () => 'finish'
}
});
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;
const smoochBot = require('smooch-bot');
var storage = require("node-persist");
var getQuotesFromStorage = require('./helper.js');
const Bot = smoochBot.Bot;
const MemoryStore = smoochBot.MemoryStore;
const MemoryLock = smoochBot.MemoryLock;

storage.initSync();

class HerokuBot1 extends Bot {
    constructor(options) {
        super(options);
    }

    say(text) {
        return new Promise((resolve) => {
            console.log(text);
            resolve();
        });
    }

    getQ() {
        getQuotesFromStorage(function(quote){
            console.log(quote);
            return 'demo';
        });
    }
}

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'getQuotes');
        }
    },

    getQuotes : {
      prompt: (bot) => getQuotesFromStorage(function(quote) {
          console.log(quote);
          bot.say(quote);
      }),
      receive: (bot) => {
          return bot.say('Have a good day')
            .then(() => 'finish');
      }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my crear didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});

const userId = 'testUserId';
const store = new MemoryStore();
const lock = new MemoryLock();
const bot = new HerokuBot1({
    store,
    lock,
    userId
});
<commit_msg>script.js updated<commit_after>'use strict';

const Script = require('smooch-bot').Script;
const smoochBot = require('smooch-bot');
var storage = require("node-persist");
var getQuotesFromStorage = require('./helper.js');
const MemoryStore = smoochBot.MemoryStore;
const MemoryLock = smoochBot.MemoryLock;

storage.initSync();

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'getQuotes');
        }
    },

    getQuotes : {
      prompt: (bot) => getQuotesFromStorage(function(quote) {
          console.log(quote);
          bot.say(quote);
      }),
      receive: () => 'Have a good day'
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my crear didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>/*    Copyright 2019-2021 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

const Platform = require('../Platform.js');
const f = require('../../net2/Firewalla.js')
const exec = require('child-process-promise').exec;
const fs = require('fs').promises; // available after Node 10
const log = require('../../net2/logger.js')(__filename);
const ipset = require('../../net2/Ipset.js');
const { execSync } = require('child_process');

class GoldPlatform extends Platform {

  getName() {
    return "gold";
  }

  getLicenseTypes() {
    return ["b1"];
  }

  getAllNicNames() {
    // there are for NICs on gold
    return ["eth0", "eth1", "eth2", "eth3"];
  }

  getDHCPServiceName() {
    return "firerouter_dhcp";
  }

  getDHKeySize() {
    if (this.isUbuntu20()) {
      return 2048;
    } else {
      return 1024;
    }
  }

  getDNSServiceName() {
    return "firerouter_dns";
  }

  getBoardSerial() {
    // use mac address as unique serial number
    return this.getSignatureMac();
  }

  getB4Binary() {
    return `${f.getFirewallaHome()}/bin/real.x86_64/bitbridge7`;
  }

  getB6Binary() {
    return `${f.getFirewallaHome()}/bin/real.x86_64/bitbridge6`;
  }

  getGCMemoryForMain() {
    return 200;
  }

  getLedPaths() {
    return [
      // "/sys/devices/platform/leds/leds/nanopi:green:status",
//      "/sys/devices/platform/leds/leds/nanopi:red:pwr"
    ];
  }

  getLSBCodeName() {
    return execSync("lsb_release -cs", {encoding: 'utf8'}).trim();
  }

  isUbuntu20() {
    return this.getLSBCodeName() === 'focal';
  }

  async ledReadyForPairing() {
    try {
      for (const path of this.getLedPaths()) {
        const trigger = `${path}/trigger`;
        const brightness = `${path}/brightness`;
        await exec(`sudo bash -c 'echo none > ${trigger}'`);
        await exec(`sudo bash -c 'echo 255 > ${brightness}'`);
      }
    } catch(err) {
      log.error("Error set LED as ready for pairing", err)
    }
  }

  async switchQoS(state, qdisc) {
    if (state == false) {
      await exec(`sudo ipset add -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4}`).catch((err) => {
        log.error(`Failed to add ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4} to ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
      await exec(`sudo ipset add -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6}`).catch((err) => {
        log.error(`Failed to add ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6} to ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
    } else {
      await exec(`sudo ipset del -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4}`).catch((err) => {
        log.error(`Failed to remove ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4} from ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
      await exec(`sudo ipset del -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6}`).catch((err) => {
        log.error(`Failed to remove ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6} from ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
    }
  }

  getSubnetCapacity() {
    return 18;
  }

  hasMultipleCPUs() {
    return true
  }

  async getCpuTemperature() {
    try {
      const path = '/sys/class/hwmon/hwmon1/'
      const tempList = []
      const dir = await fs.opendir(path)
      for await (const dirent of dir) {
        if (dirent.name.match(/temp(\d+)_input/)) {
          const input = await fs.readFile(path + dirent.name, 'utf8')
          tempList.push(Number(input) / 1000)
        }
      }
      return tempList
    } catch(err) {
      log.error("Failed to get cpu temperature, use 0 as default, err:", err);
      return 0;
    }
  }

  getPolicyCapacity() {
    return 3000;
  }

  getDHCPCapacity() {
    return false
  }

  isFireRouterManaged() {
    return true;
  }

  isWireguardSupported() {
    return true;
  }

  getCronTabFile() {
    return `${f.getFirewallaHome()}/etc/crontab.gold`;
  }
  getAllowCustomizedProfiles(){
    return 10;
  }
  getRatelimitConfig(){
    return {
      "appMax": 240,
      "webMax": 480,
      "duration": 60
    }
  }

  isBonjourBroadcastEnabled() {
    return false;
  }

  isOverlayNetworkAvailable() {
    return false;
  }

  isIFBSupported() {
    return true;
  }

  isDockerSupported() {
    return true;
  }

  getRetentionTimeMultiplier() {
    return 1;
  }

  getRetentionCountMultiplier() {
    return 1;
  }

  getCompresseCountMultiplier(){
    return 1;
  }

  getCompresseMemMultiplier(){
    return 1;
  }

  isAccountingSupported() {
    return true;
  }

  getStatsSpecs() {
    return [{
      granularities: '1hour',
      hits: 72,
      stat: '3d'
    }]
  }

  async installTLSModule() {
    const installed = await this.isTLSModuleInstalled();
    if (installed) return;
    let TLSmodulePathPrefix = null;
    if (this.isUbuntu20()) {
      TLSmodulePathPrefix = __dirname+"/files/TLS/u20";
    } else {
      TLSmodulePathPrefix = __dirname+"/files/TLS/u18";
    }
    await exec(`sudo insmod ${TLSmodulePathPrefix}/xt_tls.ko max_host_sets=1024 hostset_uid=${process.getuid()} hostset_gid=${process.getgid()}`);
    await exec(`sudo install -D -v -m 644 ${TLSmodulePathPrefix}/libxt_tls.so /usr/lib/x86_64-linux-gnu/xtables`);
  }

  async isTLSModuleInstalled() {
    if (this.tlsInstalled) return true;
    const cmdResult = await exec(`lsmod| grep xt_tls| awk '{print $1}'`);
    const results = cmdResult.stdout.toString().trim().split('\n');
    for(const result of results) {
      if (result == 'xt_tls') {
        this.tlsInstalled = true;
        break;
      }
    }
    return this.tlsInstalled;
  }

  isTLSBlockSupport() {
    return true;
  }

  getDnsmasqBinaryPath() {
    return `${__dirname}/files/dnsmasq`;
  }

  getDnsproxySOPath() {
    return `${__dirname}/files/libdnsproxy.so`
  }

  getIftopPath() {
    return `${__dirname}/files/iftop`
  }

  getSpeedtestCliBinPath() {
    return `${f.getRuntimeInfoFolder()}/assets/speedtest`
  }
}

module.exports = GoldPlatform;
<commit_msg>bug fix<commit_after>/*    Copyright 2019-2021 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

const Platform = require('../Platform.js');
const f = require('../../net2/Firewalla.js')
const exec = require('child-process-promise').exec;
const fs = require('fs').promises; // available after Node 10
const log = require('../../net2/logger.js')(__filename);
const ipset = require('../../net2/Ipset.js');
const { execSync } = require('child_process');

class GoldPlatform extends Platform {

  getName() {
    return "gold";
  }

  getLicenseTypes() {
    return ["b1", "b2"];
  }

  getAllNicNames() {
    // there are for NICs on gold
    return ["eth0", "eth1", "eth2", "eth3"];
  }

  getDHCPServiceName() {
    return "firerouter_dhcp";
  }

  getDHKeySize() {
    if (this.isUbuntu20()) {
      return 2048;
    } else {
      return 1024;
    }
  }

  getDNSServiceName() {
    return "firerouter_dns";
  }

  getBoardSerial() {
    // use mac address as unique serial number
    return this.getSignatureMac();
  }

  getB4Binary() {
    return `${f.getFirewallaHome()}/bin/real.x86_64/bitbridge7`;
  }

  getB6Binary() {
    return `${f.getFirewallaHome()}/bin/real.x86_64/bitbridge6`;
  }

  getGCMemoryForMain() {
    return 200;
  }

  getLedPaths() {
    return [
      // "/sys/devices/platform/leds/leds/nanopi:green:status",
//      "/sys/devices/platform/leds/leds/nanopi:red:pwr"
    ];
  }

  getLSBCodeName() {
    return execSync("lsb_release -cs", {encoding: 'utf8'}).trim();
  }

  isUbuntu20() {
    return this.getLSBCodeName() === 'focal';
  }

  async ledReadyForPairing() {
    try {
      for (const path of this.getLedPaths()) {
        const trigger = `${path}/trigger`;
        const brightness = `${path}/brightness`;
        await exec(`sudo bash -c 'echo none > ${trigger}'`);
        await exec(`sudo bash -c 'echo 255 > ${brightness}'`);
      }
    } catch(err) {
      log.error("Error set LED as ready for pairing", err)
    }
  }

  async switchQoS(state, qdisc) {
    if (state == false) {
      await exec(`sudo ipset add -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4}`).catch((err) => {
        log.error(`Failed to add ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4} to ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
      await exec(`sudo ipset add -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6}`).catch((err) => {
        log.error(`Failed to add ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6} to ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
    } else {
      await exec(`sudo ipset del -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4}`).catch((err) => {
        log.error(`Failed to remove ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET4} from ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
      await exec(`sudo ipset del -! ${ipset.CONSTANTS.IPSET_QOS_OFF} ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6}`).catch((err) => {
        log.error(`Failed to remove ${ipset.CONSTANTS.IPSET_MATCH_ALL_SET6} from ${ipset.CONSTANTS.IPSET_QOS_OFF}`, err.message);
      });
    }
  }

  getSubnetCapacity() {
    return 18;
  }

  hasMultipleCPUs() {
    return true
  }

  async getCpuTemperature() {
    try {
      const path = '/sys/class/hwmon/hwmon1/'
      const tempList = []
      const dir = await fs.opendir(path)
      for await (const dirent of dir) {
        if (dirent.name.match(/temp(\d+)_input/)) {
          const input = await fs.readFile(path + dirent.name, 'utf8')
          tempList.push(Number(input) / 1000)
        }
      }
      return tempList
    } catch(err) {
      log.error("Failed to get cpu temperature, use 0 as default, err:", err);
      return 0;
    }
  }

  getPolicyCapacity() {
    return 3000;
  }

  getDHCPCapacity() {
    return false
  }

  isFireRouterManaged() {
    return true;
  }

  isWireguardSupported() {
    return true;
  }

  getCronTabFile() {
    return `${f.getFirewallaHome()}/etc/crontab.gold`;
  }
  getAllowCustomizedProfiles(){
    return 10;
  }
  getRatelimitConfig(){
    return {
      "appMax": 240,
      "webMax": 480,
      "duration": 60
    }
  }

  isBonjourBroadcastEnabled() {
    return false;
  }

  isOverlayNetworkAvailable() {
    return false;
  }

  isIFBSupported() {
    return true;
  }

  isDockerSupported() {
    return true;
  }

  getRetentionTimeMultiplier() {
    return 1;
  }

  getRetentionCountMultiplier() {
    return 1;
  }

  getCompresseCountMultiplier(){
    return 1;
  }

  getCompresseMemMultiplier(){
    return 1;
  }

  isAccountingSupported() {
    return true;
  }

  getStatsSpecs() {
    return [{
      granularities: '1hour',
      hits: 72,
      stat: '3d'
    }]
  }

  async installTLSModule() {
    const installed = await this.isTLSModuleInstalled();
    if (installed) return;
    let TLSmodulePathPrefix = null;
    if (this.isUbuntu20()) {
      TLSmodulePathPrefix = __dirname+"/files/TLS/u20";
    } else {
      TLSmodulePathPrefix = __dirname+"/files/TLS/u18";
    }
    await exec(`sudo insmod ${TLSmodulePathPrefix}/xt_tls.ko max_host_sets=1024 hostset_uid=${process.getuid()} hostset_gid=${process.getgid()}`);
    await exec(`sudo install -D -v -m 644 ${TLSmodulePathPrefix}/libxt_tls.so /usr/lib/x86_64-linux-gnu/xtables`);
  }

  async isTLSModuleInstalled() {
    if (this.tlsInstalled) return true;
    const cmdResult = await exec(`lsmod| grep xt_tls| awk '{print $1}'`);
    const results = cmdResult.stdout.toString().trim().split('\n');
    for(const result of results) {
      if (result == 'xt_tls') {
        this.tlsInstalled = true;
        break;
      }
    }
    return this.tlsInstalled;
  }

  isTLSBlockSupport() {
    return true;
  }

  getDnsmasqBinaryPath() {
    return `${__dirname}/files/dnsmasq`;
  }

  getDnsproxySOPath() {
    return `${__dirname}/files/libdnsproxy.so`
  }

  getIftopPath() {
    return `${__dirname}/files/iftop`
  }

  getSpeedtestCliBinPath() {
    return `${f.getRuntimeInfoFolder()}/assets/speedtest`
  }
}

module.exports = GoldPlatform;
<|endoftext|>


<commit_before>$(function() {

  var isMacOS = navigator.appVersion.indexOf("Mac") > 0;

  var linkSelector =

     // t.co is used for shortened links and twitter images
    'a[href^="http://t.co"], a[href^="https://t.co"],' +

    // settings link from menu dropdown
    'a[data-nav="settings"],' +

    // edit profile link (there are more than 1)
    'a[href="/settings/profile"],' +

    // help link from menu dropdown
    'a[data-nav="help_center"]';

  var onClickLink = function(url) {
    chrome.extension.sendRequest({
      action: 'openLink',
      url: url
    });
  };

  var onBeforeUnload = function() {
    chrome.extension.sendRequest({
      action: 'saveDimensions',
      dimensions: {

        // it appears that innerWidth/Height is accurate for Mac OS,
        // while outerWidth/Height is accurate for Windows
        width: isMacOS ? window.innerWidth : window.outerWidth,
        height: isMacOS ? window.innerHeight : window.outerHeight,

        top: window.screenTop,
        left: window.screenLeft
      }
    });
  };

  $('body').on('click', linkSelector, function(e) {

    // if large window, just user normal link behavior

    if(document.width > 865) {
      return;
    }

    e.preventDefault();
    var href = $(this).attr('href');
    if(href.substring(0,2) == '//') {
      href = window.location.protocol + href;
    }
    if(href.substring(0,4) != 'http') {
      href = "https://twitter.com/" + href;
    }
    onClickLink(href);
  });

  $(window).on('beforeunload', onBeforeUnload);

  // disable jquery animations
  document.location = 'javascript:$.fx.off=true;';

  // key reference: http://www.k68.org/wp-content/uploads/2010/11/Key_Codes.htm
  var keyHandlers = {
    // o
    '111': function() {
      var $currentTweet = $('.hovered-stream-item, .js-had-hovered-stream-item');
      if($currentTweet.length > 0) {
        var $tweetText = $('.js-tweet-text', $currentTweet);
        var $links = $(linkSelector, $tweetText);
        if($links.length > 0) {
          $($links[0]).click();
        }
      }
    }
  };

  // handle shortcut keys
  $(document).on('keypress', function(event) {
    if ($(event.target).is('input, textarea, .rich-editor')) {
      return;
    }
    var handler = keyHandlers[event.charCode.toString()];
    if(typeof handler == 'function') {
      handler();
    }
  });
});
<commit_msg>fixed window size remember on Windows<commit_after>$(function() {

  var linkSelector =

     // t.co is used for shortened links and twitter images
    'a[href^="http://t.co"], a[href^="https://t.co"],' +

    // settings link from menu dropdown
    'a[data-nav="settings"],' +

    // edit profile link (there are more than 1)
    'a[href="/settings/profile"],' +

    // help link from menu dropdown
    'a[data-nav="help_center"]';

  var onClickLink = function(url) {
    chrome.extension.sendRequest({
      action: 'openLink',
      url: url
    });
  };

  var onBeforeUnload = function() {
    chrome.extension.sendRequest({
      action: 'saveDimensions',
      dimensions: {

        width: window.innerWidth,
        height: window.innerHeight,

        top: window.screenTop,
        left: window.screenLeft
      }
    });
  };

  $('body').on('click', linkSelector, function(e) {

    // if large window, just user normal link behavior

    if(document.width > 865) {
      return;
    }

    e.preventDefault();
    var href = $(this).attr('href');
    if(href.substring(0,2) == '//') {
      href = window.location.protocol + href;
    }
    if(href.substring(0,4) != 'http') {
      href = "https://twitter.com/" + href;
    }
    onClickLink(href);
  });

  $(window).on('beforeunload', onBeforeUnload);

  // disable jquery animations
  document.location = 'javascript:$.fx.off=true;';

  // key reference: http://www.k68.org/wp-content/uploads/2010/11/Key_Codes.htm
  var keyHandlers = {
    // o
    '111': function() {
      var $currentTweet = $('.hovered-stream-item, .js-had-hovered-stream-item');
      if($currentTweet.length > 0) {
        var $tweetText = $('.js-tweet-text', $currentTweet);
        var $links = $(linkSelector, $tweetText);
        if($links.length > 0) {
          $($links[0]).click();
        }
      }
    }
  };

  // handle shortcut keys
  $(document).on('keypress', function(event) {
    if ($(event.target).is('input, textarea, .rich-editor')) {
      return;
    }
    var handler = keyHandlers[event.charCode.toString()];
    if(typeof handler == 'function') {
      handler();
    }
  });
});
<|endoftext|>


<commit_before>/**
 * The game's global configuration.
 */
var Smc = {
    // The Phaser event handlers. Keys are event names, and values are arrays of functions that take no arguments.
    phaserEventHandlers: {
        preload: [],
        create: [],
        update: []
    }
};

/**
 * Builds a Phaser event handler for a specific event.
 *
 * @param {string} eventName
 *   The name of the event to create the handler for. Must exist as a key in Smc.eventHandlers.
 *
 * @returns {Function}
 *   The event handler, which takes no arguments.
 */
function buildPhaserEventHandler(eventName) {
    // Phaser callbacks are functions that take no arguments. We create them dynamically using the event name that was
    // passed on to this builder function.
    return function() {
        Smc.phaserEventHandlers[eventName].forEach(function (handler) {
            handler();
        });
    }
}

var game = new Phaser.Game(640,480, Phaser.AUTO, 'world', {
    preload: buildPhaserEventHandler("preload"),
    create: buildPhaserEventHandler("create"),
    update: buildPhaserEventHandler("update")
});

var cursors;

var mexicanX = 200;
var mexicanY= 100;
var boxX = 200;
var boxY = 250;
var liftX = 400;
var liftY = 250;
var lift ;
var student;
var studentWeaponMount;
var mexican;

var armX = 46;
var armY= 93;
var pumpX = 62;
var pumpY= 168;
var weightX = 0;
var weightY= 345;

var x = game.width/2;
var y = game.height/2;
var dirX = 10;
var dirY = 10;
var emitter;
var weapon;

Smc.phaserEventHandlers.preload.push(function() {
    game.load.image('arm', 'assets/arm.png');
    game.load.image('pump', 'assets/pump.png');
    game.load.image('weight', 'assets/weight.png');

    game.load.image('fire1', 'assets/fire1.png');
    game.load.image('fire2', 'assets/fire2.png');
    game.load.image('fire3', 'assets/fire3.png');
    game.load.image('smoke', 'assets/smoke-puff.png');

    game.load.image('pixel', 'assets/trans-pixel.png');

    game.load.image('bullet', 'assets/bullet.png');
    game.load.image('box', 'assets/box.png');
    game.load.image('lift', 'assets/lift.png');
    game.load.image('background', 'assets/header.jpg');
    game.load.atlasJSONHash('student', 'assets/student.png','assets/student.json');
    game.load.atlasJSONHash('mexican', 'assets/mexican.png', 'assets/mexican.json');

    game.load.image('pixel', 'assets/trans-pixel.png');
    game.load.script('HudManager', 'plugins/HUDManager.js');
});

Smc.phaserEventHandlers.create.push(function() {
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.stage.backgroundColor = '#333';
    game.add.tileSprite(-400,-400, 2000, 1600, 'background');
    emitter = game.add.emitter(game.world.centerX, game.world.centerY, 400);

    emitter.makeParticles( [ 'fire1', 'fire2', 'fire3', 'smoke' ] );

    emitter.gravity = 800;
    emitter.setAlpha(1, 0, 3000);

    student = game.add.sprite( 600,480, 'student');
    studentWeaponMount = game.add.sprite( 600,480, 'pixel');

    game.physics.enable(studentWeaponMount, Phaser.Physics.ARCADE);

    studentWeaponMount.body.enable          = true;
    studentWeaponMount.body.allowRotation   = true;

    student.animations.add('left', ['left1', 'left2','left3', 'left4','left5', 'left6','left7', 'left8','left9']);
    student.animations.add('right', ['right1', 'right2','right3', 'right4','right5', 'right6','right7', 'right8', 'right9']);
    student.animations.add('up', ['up1', 'up2','up3', 'up4','up5', 'up6','up7', 'up8','up9']);
    student.animations.add('down', ['down1', 'down2']);

    mexican = game.add.sprite( mexicanX, mexicanY, 'mexican');
    box = game.add.sprite( boxX, boxY, 'box');
    lift = game.add.sprite( liftX, liftY, 'lift');

    pump = game.add.sprite( pumpX, pumpY, 'pump');
    arm = game.add.sprite( armX, armY, 'arm');
    weight = game.add.sprite( weightX, weightY, 'weight');

    mexican.animations.add('stop');
    mexican.animations.play('stop', 5, true);

    mexican.id                  = 1;
    mexican.maxHealth           = 100;
    mexican.health              = 100;
    mexican.anchor.setTo(0.5, 0.5);
    game.physics.enable(mexican, Phaser.Physics.ARCADE);
    mexican.hud                 = Phaser.Plugin.HUDManager.create(mexican.game, mexican, 'enemyhud');
    mexican.healthHUD           =mexican.hud.addBar(0, -20, 32, 2, mexican.maxHealth, 'health', mexican, Phaser.Plugin.HUDManager.HEALTHBAR, false);
    mexican.healthHUD.bar.anchor.setTo(0.5, 0.5);
    mexican.addChild(mexican.healthHUD.bar);
    mexican.body.immovable      = true;

    game.physics.arcade.enable(mexican);
    game.physics.arcade.enable(box);
    game.physics.arcade.enable(lift);
    mexican.body.gravity.set(0, 180);
    mexican.body.collideWorldBounds = true;
    lift.body.collideWorldBounds = true;
    box.body.collideWorldBounds = true;
    student.anchor.setTo(0.5, 0.5);
    game.physics.arcade.enable(student);
    student.body.velocity.setTo(200, 200);
    // makes image collideable
    student.body.collideWorldBounds = true;
    // student.bounce.set(0.8);
    student.body.gravity.set(0, 180);
    //student.inputEnabled = true;

    game.physics.arcade.enable(box);

    game.physics.arcade.enable(lift);

    cursors = game.input.keyboard.createCursorKeys();

    //  Creates 30 bullets, using the 'bullet' graphic
    weapon = game.add.weapon(30, 'bullet');

    //  The bullet will be automatically killed when it leaves the world bounds
    weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;

    //  The speed at which the bullet is fired
    weapon.bulletSpeed = 600;

    //  Speed-up the rate of fire, allowing them to shoot 1 bullet every 60ms
    weapon.fireRate = 100;

    game.physics.arcade.enable(weapon);
    //  Tell the Weapon to track the 'student' Sprite
    //  With no offsets from the position
    //  But the 'true' argument tells the weapon to track sprite rotation
    weapon.trackSprite(studentWeaponMount, 0, 0, true);
});

Smc.phaserEventHandlers.update.push(function() {
    game.physics.arcade.collide(mexican, box, yahoo);
    game.physics.arcade.collide(mexican, weapon.bullets, bomb, null, this);

    game.physics.arcade.collide(student, box, yahoo);
    game.physics.arcade.collide(student, lift, yahoo);

    if (x > game.width - student.width || x < 0) {
        dirX = -dirX;
    }
    if (y > game.height - student.height || y < 0) {
        dirY = -dirY;
    }

    if (cursors.up.isDown) {
        student.y = student.y - 10;
        particleBurst();
        //  emitter.start(false, 3000, 5);
        student.animations.play('up', 30, false);

        console.log(student.y);
    }
    else {
        student.animations.play('stop', 30, false);
    }

    if (cursors.left.isDown) {
        if (cursors.up.isDown) {
            student.x = student.x - 10;
        } else {
            student.x = student.x - 5;
        }
        student.animations.play('left', 15, false);

        studentWeaponMount.angle = 180;

    }
    else if (cursors.right.isDown) {
        if (cursors.up.isDown) {
            student.x = student.x + 10;
        } else {
            student.x = student.x + 5;
        }
        student.animations.play('right', 15, false);
        studentWeaponMount.x = x;
        studentWeaponMount.angle = 0;

    } else {
        student.animations.play('stop', 15, false);
    }

    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
        weapon.fire();
    }

    studentWeaponMount.y =   student.y;
    studentWeaponMount.x =   student.x;
});

function bomb(whatsthis, bullet){
    console.log(bullet);

    mexican.health = mexican.health -10;

    if  (mexican.health<=60){

        mexican.kill();
    }
    bullet.kill();
}

function particleBurst() {
    var px = student.body.velocity.x;
    var py = student.body.velocity.y;

    px *= -1;
    py *= -1;

    emitter.minParticleSpeed.set(px, py);
    emitter.maxParticleSpeed.set(px, py);

    emitter.emitX = student.x;
    emitter.emitY = student.y;

    emitter.setScale(0.1,0, 0.1,0, 3000);

    emitter.start(true, 100, null, 5);

}

function yahoo(){

    console.log('yahoo');

}
<commit_msg>Make the Mexican die at 0% health instead of 60%.<commit_after>/**
 * The game's global configuration.
 */
var Smc = {
    // The Phaser event handlers. Keys are event names, and values are arrays of functions that take no arguments.
    phaserEventHandlers: {
        preload: [],
        create: [],
        update: []
    }
};

/**
 * Builds a Phaser event handler for a specific event.
 *
 * @param {string} eventName
 *   The name of the event to create the handler for. Must exist as a key in Smc.eventHandlers.
 *
 * @returns {Function}
 *   The event handler, which takes no arguments.
 */
function buildPhaserEventHandler(eventName) {
    // Phaser callbacks are functions that take no arguments. We create them dynamically using the event name that was
    // passed on to this builder function.
    return function() {
        Smc.phaserEventHandlers[eventName].forEach(function (handler) {
            handler();
        });
    }
}

var game = new Phaser.Game(640,480, Phaser.AUTO, 'world', {
    preload: buildPhaserEventHandler("preload"),
    create: buildPhaserEventHandler("create"),
    update: buildPhaserEventHandler("update")
});

var cursors;

var mexicanX = 200;
var mexicanY= 100;
var boxX = 200;
var boxY = 250;
var liftX = 400;
var liftY = 250;
var lift ;
var student;
var studentWeaponMount;
var mexican;

var armX = 46;
var armY= 93;
var pumpX = 62;
var pumpY= 168;
var weightX = 0;
var weightY= 345;

var x = game.width/2;
var y = game.height/2;
var dirX = 10;
var dirY = 10;
var emitter;
var weapon;

Smc.phaserEventHandlers.preload.push(function() {
    game.load.image('arm', 'assets/arm.png');
    game.load.image('pump', 'assets/pump.png');
    game.load.image('weight', 'assets/weight.png');

    game.load.image('fire1', 'assets/fire1.png');
    game.load.image('fire2', 'assets/fire2.png');
    game.load.image('fire3', 'assets/fire3.png');
    game.load.image('smoke', 'assets/smoke-puff.png');

    game.load.image('pixel', 'assets/trans-pixel.png');

    game.load.image('bullet', 'assets/bullet.png');
    game.load.image('box', 'assets/box.png');
    game.load.image('lift', 'assets/lift.png');
    game.load.image('background', 'assets/header.jpg');
    game.load.atlasJSONHash('student', 'assets/student.png','assets/student.json');
    game.load.atlasJSONHash('mexican', 'assets/mexican.png', 'assets/mexican.json');

    game.load.image('pixel', 'assets/trans-pixel.png');
    game.load.script('HudManager', 'plugins/HUDManager.js');
});

Smc.phaserEventHandlers.create.push(function() {
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.stage.backgroundColor = '#333';
    game.add.tileSprite(-400,-400, 2000, 1600, 'background');
    emitter = game.add.emitter(game.world.centerX, game.world.centerY, 400);

    emitter.makeParticles( [ 'fire1', 'fire2', 'fire3', 'smoke' ] );

    emitter.gravity = 800;
    emitter.setAlpha(1, 0, 3000);

    student = game.add.sprite( 600,480, 'student');
    studentWeaponMount = game.add.sprite( 600,480, 'pixel');

    game.physics.enable(studentWeaponMount, Phaser.Physics.ARCADE);

    studentWeaponMount.body.enable          = true;
    studentWeaponMount.body.allowRotation   = true;

    student.animations.add('left', ['left1', 'left2','left3', 'left4','left5', 'left6','left7', 'left8','left9']);
    student.animations.add('right', ['right1', 'right2','right3', 'right4','right5', 'right6','right7', 'right8', 'right9']);
    student.animations.add('up', ['up1', 'up2','up3', 'up4','up5', 'up6','up7', 'up8','up9']);
    student.animations.add('down', ['down1', 'down2']);

    mexican = game.add.sprite( mexicanX, mexicanY, 'mexican');
    box = game.add.sprite( boxX, boxY, 'box');
    lift = game.add.sprite( liftX, liftY, 'lift');

    pump = game.add.sprite( pumpX, pumpY, 'pump');
    arm = game.add.sprite( armX, armY, 'arm');
    weight = game.add.sprite( weightX, weightY, 'weight');

    mexican.animations.add('stop');
    mexican.animations.play('stop', 5, true);

    mexican.id                  = 1;
    mexican.maxHealth           = 100;
    mexican.health              = 100;
    mexican.anchor.setTo(0.5, 0.5);
    game.physics.enable(mexican, Phaser.Physics.ARCADE);
    mexican.hud                 = Phaser.Plugin.HUDManager.create(mexican.game, mexican, 'enemyhud');
    mexican.healthHUD           =mexican.hud.addBar(0, -20, 32, 2, mexican.maxHealth, 'health', mexican, Phaser.Plugin.HUDManager.HEALTHBAR, false);
    mexican.healthHUD.bar.anchor.setTo(0.5, 0.5);
    mexican.addChild(mexican.healthHUD.bar);
    mexican.body.immovable      = true;

    game.physics.arcade.enable(mexican);
    game.physics.arcade.enable(box);
    game.physics.arcade.enable(lift);
    mexican.body.gravity.set(0, 180);
    mexican.body.collideWorldBounds = true;
    lift.body.collideWorldBounds = true;
    box.body.collideWorldBounds = true;
    student.anchor.setTo(0.5, 0.5);
    game.physics.arcade.enable(student);
    student.body.velocity.setTo(200, 200);
    // makes image collideable
    student.body.collideWorldBounds = true;
    // student.bounce.set(0.8);
    student.body.gravity.set(0, 180);
    //student.inputEnabled = true;

    game.physics.arcade.enable(box);

    game.physics.arcade.enable(lift);

    cursors = game.input.keyboard.createCursorKeys();

    //  Creates 30 bullets, using the 'bullet' graphic
    weapon = game.add.weapon(30, 'bullet');

    //  The bullet will be automatically killed when it leaves the world bounds
    weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;

    //  The speed at which the bullet is fired
    weapon.bulletSpeed = 600;

    //  Speed-up the rate of fire, allowing them to shoot 1 bullet every 60ms
    weapon.fireRate = 100;

    game.physics.arcade.enable(weapon);
    //  Tell the Weapon to track the 'student' Sprite
    //  With no offsets from the position
    //  But the 'true' argument tells the weapon to track sprite rotation
    weapon.trackSprite(studentWeaponMount, 0, 0, true);
});

Smc.phaserEventHandlers.update.push(function() {
    game.physics.arcade.collide(mexican, box, yahoo);
    game.physics.arcade.collide(mexican, weapon.bullets, bomb, null, this);

    game.physics.arcade.collide(student, box, yahoo);
    game.physics.arcade.collide(student, lift, yahoo);

    if (x > game.width - student.width || x < 0) {
        dirX = -dirX;
    }
    if (y > game.height - student.height || y < 0) {
        dirY = -dirY;
    }

    if (cursors.up.isDown) {
        student.y = student.y - 10;
        particleBurst();
        //  emitter.start(false, 3000, 5);
        student.animations.play('up', 30, false);

        console.log(student.y);
    }
    else {
        student.animations.play('stop', 30, false);
    }

    if (cursors.left.isDown) {
        if (cursors.up.isDown) {
            student.x = student.x - 10;
        } else {
            student.x = student.x - 5;
        }
        student.animations.play('left', 15, false);

        studentWeaponMount.angle = 180;

    }
    else if (cursors.right.isDown) {
        if (cursors.up.isDown) {
            student.x = student.x + 10;
        } else {
            student.x = student.x + 5;
        }
        student.animations.play('right', 15, false);
        studentWeaponMount.x = x;
        studentWeaponMount.angle = 0;

    } else {
        student.animations.play('stop', 15, false);
    }

    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
        weapon.fire();
    }

    studentWeaponMount.y =   student.y;
    studentWeaponMount.x =   student.x;
});

function bomb(mexican, bullet){
    mexican.health = mexican.health -10;

    if  (mexican.health<=0){

        mexican.kill();
    }
    bullet.kill();
}

function particleBurst() {
    var px = student.body.velocity.x;
    var py = student.body.velocity.y;

    px *= -1;
    py *= -1;

    emitter.minParticleSpeed.set(px, py);
    emitter.maxParticleSpeed.set(px, py);

    emitter.emitX = student.x;
    emitter.emitY = student.y;

    emitter.setScale(0.1,0, 0.1,0, 3000);

    emitter.start(true, 100, null, 5);

}

function yahoo(){

    console.log('yahoo');

}
<|endoftext|>


<commit_before>// Get data
endpoint = 'https://clement-dejardin.github.io/data.json'
const data = []
fetch(endpoint)
    .then(blob => blob.json())
    .then(stuff => data.push(...stuff))

// Search between 2 city
function findMatches(city1, city2, data) {
    return data.filter(place => {
        const regex1 = new RegExp(city1, 'gi')
        const regex2 = new RegExp(city2, 'gi')
        return (place.Departure.match(regex1) || place.Arrival.match(regex1)) &&
            (place.Departure.match(regex2) || place.Arrival.match(regex2))
    })
}

// Dispay the result
function displayMatches() {
    const matchArray = findMatches(searchInputCity1.value, searchInputCity2.value, data)
    // Sort matchArray by price
    const html = matchArray.map(place => {
        return `

        ${place.Departure} ➜ ${place.Arrival} ⏱ ${place.Flight_time}

                    Airline : ${place.Airline}

                    Helicopter : ${place.Helicopter}

                    Single Pilot :

                    ${place.Single_pilot} ${place.Currency}

                    Double Pilot :

                    ${place.Double_pilot} ${place.Currency}

`
    }).join('')
    document.querySelector('.content').innerHTML = html
}

// Run matches when typing in input
const searchInputCity1 = document.querySelector('.city1')
const searchInputCity2 = document.querySelector('.city2')

searchInputCity1.addEventListener('change', displayMatches)
searchInputCity2.addEventListener('change', displayMatches)
searchInputCity1.addEventListener('keyup', displayMatches)
searchInputCity2.addEventListener('keyup', displayMatches)<commit_msg>sortBy<commit_after>// Get data
endpoint = 'https://clement-dejardin.github.io/data.json'
const data = []
fetch(endpoint)
    .then(blob => blob.json())
    .then(stuff => data.push(...stuff))

// Sorting function
var sortBy = function (property) {
    return function (x, y) {
        return ((x[property] === y[property]) ? 0 : ((x[property] > y[property]) ? 1 : -1));
    };
};

// Search between 2 city
function findMatches(city1, city2, data) {
    return data.filter(place => {
        const regex1 = new RegExp(city1, 'gi')
        const regex2 = new RegExp(city2, 'gi')
        return (place.Departure.match(regex1) || place.Arrival.match(regex1)) &&
            (place.Departure.match(regex2) || place.Arrival.match(regex2))
    })
}

// Dispay the result
function displayMatches() {
    const matchArray = findMatches(searchInputCity1.value, searchInputCity2.value, data)
    // Sort matchArray by price
    matchArray.sort(sortBy('Single_pilot'))
    const html = matchArray.map(place => {
        return `

        ${place.Departure} ➜ ${place.Arrival} ⏱ ${place.Flight_time}

                    Airline : ${place.Airline}

                    Helicopter : ${place.Helicopter}

                    Single Pilot :

                    ${place.Single_pilot} ${place.Currency}

                    Double Pilot :

                    ${place.Double_pilot} ${place.Currency}

`
    }).join('')
    document.querySelector('.content').innerHTML = html
}

// Run matches when typing in input
const searchInputCity1 = document.querySelector('.city1')
const searchInputCity2 = document.querySelector('.city2')

searchInputCity1.addEventListener('change', displayMatches)
searchInputCity2.addEventListener('change', displayMatches)
searchInputCity1.addEventListener('keyup', displayMatches)
searchInputCity2.addEventListener('keyup', displayMatches)<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;
const smoochBot = require('smooch-bot');
var storage = require("node-persist");
var getQuotesFromStorage = require('./helper.js');
const Bot = smoochBot.Bot;
const MemoryStore = smoochBot.MemoryStore;
const MemoryLock = smoochBot.MemoryLock;

storage.initSync();

class HerokuBot1 extends Bot {
    constructor(options) {
        super(options);
    }

    say(text) {
        return new Promise((resolve) => {
            console.log(text);
            resolve();
        });
    }

    getQ() {
        getQuotesFromStorage(function(quote){
            console.log(quote);
            return 'demo';
        });
    }
}

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'getQuotes1');
        }
    },

    getQuotes1 : {
      prompt: (bot) => bot.say(bot.getQ()),
      receive: (bot) => {
          return bot.say('Have a good day')
            .then(() => 'finish');
      }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my crear didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});

const userId = 'testUserId';
const store = new MemoryStore();
const lock = new MemoryLock();
const bot = new HerokuBot1({
    store,
    lock,
    userId
});
<commit_msg>script.js updated<commit_after>'use strict';

const Script = require('smooch-bot').Script;
const smoochBot = require('smooch-bot');
var storage = require("node-persist");
var getQuotesFromStorage = require('./helper.js');
const Bot = smoochBot.Bot;
const MemoryStore = smoochBot.MemoryStore;
const MemoryLock = smoochBot.MemoryLock;

storage.initSync();

class HerokuBot1 extends Bot {
    constructor(options) {
        super(options);
    }

    say(text) {
        return new Promise((resolve) => {
            console.log(text);
            resolve();
        });
    }

    getQ() {
        getQuotesFromStorage(function(quote){
            console.log(quote);
            return 'demo';
        });
    }
}

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'getQuotes');
        }
    },

    getQuotes : {
      prompt: (bot) => getQuotesFromStorage(function(quote) {
          console.log(quote);
          bot.say(quote);
      }),
      receive: (bot) => {
          return bot.say('Have a good day')
            .then(() => 'finish');
      }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my crear didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});

const userId = 'testUserId';
const store = new MemoryStore();
const lock = new MemoryLock();
const bot = new HerokuBot1({
    store,
    lock,
    userId
});
<|endoftext|>