<commit_before>'use strict';
/*
 Oressource
 Copyright (C) 2014-2017  Martin Vert and Oressource devellopers

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 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/>.
 */
//
// Inspired from https://github.com/declandewet/common-tags/ lib
function stripIndent(html) {
// remove the shortest leading indentation from each line
  const indent = Math.min(...html[0].match(/^[ \t]*(?=\S)/gm).map(el => el.length));
  return html[0].replace(new RegExp('^[ \\t]{' + indent + '}', 'gm'), '');
}

function number_write(x) {
  const text_box = document.getElementById("number");
  text_box.value = text_box.value + x;
}

function number_clear() {
  const input = document.getElementById("number");
  input.value = "";
  input.setCustomValidity("");
}

/*
 * Classe pour la gestion du pave numerique.
 * Le design actuel est minimaliste a terme cela serait pratique d'en faire un
 * widget a la Morris.js.
 */
class NumPad {
  /*
   * Cree un Numpad cote JS on lui passe l'element input HTML associee au numpad.
   * ainsi que la liste des conteneurs disponnibles.
   * ```js
   * const numpad = new NumPad(document.getElementById('number'));
   * ```
   */
  constructor(root, conteneurs = []) {

    const div = document.createElement('div');
    div.setAttribute('class', 'panel panel-info');
    div.innerHTML = stripIndent`

      <input type="text" class="form-control" placeholder="Masse" id="number" name="num">

        <button class="numkey btn btn-default btn-lg" onclick="number_write('1');" data-value="1">1</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('2');" data-value="2">2</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('3');" data-value="3">3</button>

        <button class="numkey btn btn-default btn-lg" onclick="number_write('4');" data-value="4">4</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('5');" data-value="5">5</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('6');" data-value="6">6</button>

        <button class="numkey btn btn-default btn-lg" onclick="number_write('7');" data-value="7">7</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('8');" data-value="8">8</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('9');" data-value="9">9</button>

        <button class="numkey btn btn-default btn-lg" onclick="number_clear();" data-value="C">C</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('0');" data-value="0">0</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('.');" data-value=".">,</button>

`;
    const numpad = document.createDocumentFragment();
    numpad.appendChild(div);
    if (conteneurs.length > 0) {

      const fragment = document.createDocumentFragment();
      const div = document.createElement('div');
      div.setAttribute('class', 'input-group-btn');
      div.innerHTML = `
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

        </button>

`;
      fragment.appendChild(div);
      const ul = fragment.querySelector('#conteneurs');
      conteneurs.forEach((c) => {
        const li = document.createElement('li');
        const a = document.createElement('a');
        a.innerText = `${c.nom}: -${c.masse} kg`;
        a.addEventListener('click', () => {
          this.substract_manutention(c.masse);
        }, false);
        li.appendChild(a);
        ul.appendChild(li);
      });
      numpad.querySelector('#saisie').appendChild(fragment);
    }
    root.appendChild(numpad);
    this.input = document.getElementById('number');
  }

  substract_manutention(masse_conteneur) {
    const new_value = this.value - masse_conteneur;
    if (new_value > 0.0) {
      this.value = (this.value - masse_conteneur).toFixed(2);
    } else {
      this.error("La masse de l'objet pesee est inferieur au poids du conteneur!");
    }
  }

  /*
   * Permet de recuperer la valeur contenue dans l'input du pave numerique.
   */
  get value() {
    return parseFloat(this.input.value);
  }

  set value(value) {
    this.input.value = value;
  }

  /*
   * Remet a zero le numpad.
   */
  reset_numpad() {
    this.input.value = '';
    this.input.setCustomValidity('');
  }

  /*
   * Permet de definir la validite du champ input du numpad.
   */
  error(msg) {
    this.input.setCustomValidity(msg);
  }
}
<commit_msg>Removed code who remove indentation at runtime on template string<commit_after>'use strict';
/*
 Oressource
 Copyright (C) 2014-2017  Martin Vert and Oressource devellopers

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 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/>.
 */

function number_write(x) {
  const text_box = document.getElementById("number");
  text_box.value = text_box.value + x;
}

function number_clear() {
  const input = document.getElementById("number");
  input.value = "";
  input.setCustomValidity("");
}

/*
 * Classe pour la gestion du pave numerique.
 * Le design actuel est minimaliste a terme cela serait pratique d'en faire un
 * widget a la Morris.js.
 */
class NumPad {
  /*
   * Cree un Numpad cote JS on lui passe l'element input HTML associee au numpad.
   * ainsi que la liste des conteneurs disponnibles.
   * ```js
   * const numpad = new NumPad(document.getElementById('number'));
   * ```
   */
  constructor(root, conteneurs = []) {

    const div = document.createElement('div');
    div.setAttribute('class', 'panel panel-info');
    div.innerHTML = `

      <input type="text" class="form-control" placeholder="Masse" id="number" name="num">

        <button class="numkey btn btn-default btn-lg" onclick="number_write('1');" data-value="1">1</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('2');" data-value="2">2</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('3');" data-value="3">3</button>

        <button class="numkey btn btn-default btn-lg" onclick="number_write('4');" data-value="4">4</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('5');" data-value="5">5</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('6');" data-value="6">6</button>

        <button class="numkey btn btn-default btn-lg" onclick="number_write('7');" data-value="7">7</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('8');" data-value="8">8</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('9');" data-value="9">9</button>

        <button class="numkey btn btn-default btn-lg" onclick="number_clear();" data-value="C">C</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('0');" data-value="0">0</button>
        <button class="numkey btn btn-default btn-lg" onclick="number_write('.');" data-value=".">,</button>

`;
    const numpad = document.createDocumentFragment();
    numpad.appendChild(div);
    if (conteneurs.length > 0) {

      const fragment = document.createDocumentFragment();
      const div = document.createElement('div');
      div.setAttribute('class', 'input-group-btn');
      div.innerHTML = `
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

        </button>

`;
      fragment.appendChild(div);
      const ul = fragment.querySelector('#conteneurs');
      conteneurs.forEach((c) => {
        const li = document.createElement('li');
        const a = document.createElement('a');
        a.innerText = `${c.nom}: -${c.masse} kg`;
        a.addEventListener('click', () => {
          this.substract_manutention(c.masse);
        }, false);
        li.appendChild(a);
        ul.appendChild(li);
      });
      numpad.querySelector('#saisie').appendChild(fragment);
    }
    root.appendChild(numpad);
    this.input = document.getElementById('number');
  }

  substract_manutention(masse_conteneur) {
    const new_value = this.value - masse_conteneur;
    if (new_value > 0.0) {
      this.value = (this.value - masse_conteneur).toFixed(2);
    } else {
      this.error("La masse de l'objet pesee est inferieur au poids du conteneur!");
    }
  }

  /*
   * Permet de recuperer la valeur contenue dans l'input du pave numerique.
   */
  get value() {
    return parseFloat(this.input.value);
  }

  set value(value) {
    this.input.value = value;
  }

  /*
   * Remet a zero le numpad.
   */
  reset_numpad() {
    this.input.value = '';
    this.input.setCustomValidity('');
  }

  /*
   * Permet de definir la validite du champ input du numpad.
   */
  error(msg) {
    this.input.setCustomValidity(msg);
  }
}
<|endoftext|>


<commit_before>$(function () {
    configureLibs();
    setupApp();
});

function configureLibs() {
    nunjucks.configure("", {web: {useCache: true}});
    $.fn.editable.defaults.mode = 'inline';
    $.fn.editable.defaults.showbuttons = false;
    $.fn.editable.defaults.showbuttons = false;
    $.fn.editable.defaults.onblur = 'submit';
    Backbone.Marionette.Renderer.render = function (template, data) {
        if (_.isFunction(template)) {
            return template(data);
        }
        return nunjucks.render(template, data);
    };
}

var App = {};

function createEmptyDiet() {
    var diet = new Diet();
    var dayCollection = new DayCollection();
    diet.set('days', dayCollection);

    var mealListModel = new MealList();
    var firstMeal = new Meal();
    firstMeal.set('name', "Meal 1");
    mealListModel.add(firstMeal);

    dayCollection.add(new Day({name: "Monday", meals: mealListModel, active: true}));
    dayCollection.add(new Day({name: "Tuesday", meals: new MealList()}));
    dayCollection.add(new Day({name: "Wednesday", meals: new MealList()}));
    dayCollection.add(new Day({name: "Thursday", meals: new MealList()}));
    dayCollection.add(new Day({name: "Friday", meals: new MealList()}));

    diet.set('caloricIntake', new CaloricIntakeModel());

    return diet;
}

var setupApp = function () {
    var dietId = url('?id');

    App.daysPanelView = undefined;

    if (dietId != null) {
        Search.Load(dietId, function (diet) {
            App.diet = diet;
            App.daysPanelView = prepareView(diet.get('days'))
        });
    } else {
        App.diet = createEmptyDiet();
        App.daysPanelView = prepareView(App.diet.get('days'))
    }

    var caloricIntakeView = new CaloricIntakeView();

    function prepareView(daysCollection) {
        var daysPanelView = new DaysPanelView({model: daysCollection});
        daysPanelView.render();

        return daysPanelView;
    }

    function saveDiet() {
        Search.Save(App.diet, function onSuccess(data) {
            var dietUrl = window.location.href.split('?')[0] + '?id=' + data['_id'];
            window.location = dietUrl;
        });
    }

    $('#save_diet').click(saveDiet);

};
<commit_msg>Added initial meal for each day<commit_after>$(function () {
    configureLibs();
    setupApp();
});

function configureLibs() {
    nunjucks.configure("", {web: {useCache: true}});
    $.fn.editable.defaults.mode = 'inline';
    $.fn.editable.defaults.showbuttons = false;
    $.fn.editable.defaults.showbuttons = false;
    $.fn.editable.defaults.onblur = 'submit';
    Backbone.Marionette.Renderer.render = function (template, data) {
        if (_.isFunction(template)) {
            return template(data);
        }
        return nunjucks.render(template, data);
    };
}

var App = {};

function createNewDay(name, active) {
    var mealListModel = new MealList();
    var firstMeal = new Meal({name: 'Meal 1'});
    mealListModel.add(firstMeal);
    return new Day({name: name, meals: mealListModel, active: active})
}

function createEmptyDiet() {
    var dayCollection = new DayCollection();
    dayCollection.add(createNewDay("Monday", true));
    dayCollection.add(createNewDay("Tuesday", false));
    dayCollection.add(createNewDay("Wednesday", false));
    dayCollection.add(createNewDay("Thursday", false));
    dayCollection.add(createNewDay("Friday", false));

    return new Diet({days: dayCollection, caloricIntake: new CaloricIntakeModel()});
}

var setupApp = function () {
    var dietId = url('?id');

    App.daysPanelView = undefined;

    if (dietId != null) {
        Search.Load(dietId, function (diet) {
            App.diet = diet;
            App.daysPanelView = prepareView(diet.get('days'))
        });
    } else {
        App.diet = createEmptyDiet();
        App.daysPanelView = prepareView(App.diet.get('days'))
    }

    var caloricIntakeView = new CaloricIntakeView();

    function prepareView(daysCollection) {
        var daysPanelView = new DaysPanelView({model: daysCollection});
        daysPanelView.render();

        return daysPanelView;
    }

    function saveDiet() {
        Search.Save(App.diet, function onSuccess(data) {
            var dietUrl = window.location.href.split('?')[0] + '?id=' + data['_id'];
            window.location = dietUrl;
        });
    }

    $('#save_diet').click(saveDiet);

};
<|endoftext|>


<commit_before>/*
 * MIT License (MIT) - Copyright (c) 2014 Johann Troendle
 *
 * This file is part of <grunt-dock>.
 */
var fs = require('fs'),
    path = require('path'),
    tar = require('tar-stream'),
    tarfs = require('tar-fs'),
    concat = require('concat-stream'),
    zlib = require('zlib'),
    async = require('async'),
    utils = require('./utils');

/**
 * Build images.
 * Each image is a content associated with its tag name.
 * The content can be a regular file or whatever for Docker.
 * In case of a plain file, it will be tar + gz before sent
 * to Docker.
 *
 * @param  {Object}   grunt   The Grunt Object
 * @param  {Object}   docker  The Dockerode connection
 * @param  {Object}   options The Grunt options
 * @param  {Function} done    The done function to call when finished
 * @param  {String}   tag     The image tag to work with or null
 */
var buildCommands = function(grunt, docker, options, done, tag) {

  // Build image with tag and its data/options.
  // Call callback when done or error.
  var build = function(data, options, callback) {
    grunt.log.subhead('Building image [' + options.t + ']');

    docker.buildImage(data, options, function(err, stream) {

      if (err) {
        return callback(err);
      }

      stream.setEncoding('utf8');

      stream.on('data', function(data) {
        var jsonData = JSON.parse(data);
        jsonData.stream && grunt.log.write(jsonData.stream);
        jsonData.error && grunt.fail.warn(jsonData.error);
      });

      stream.on('error', callback);
      stream.on('end', function() {
        grunt.log.oklns('Build successfuly done.');
        callback();
      });
    });
  };

  var processDirectory = function(dirpath, buildOpts, callback) {
    grunt.log.debug('Packing directory [' + dirpath + ']');
    var pathentry = path.resolve(dirpath),
        dockerignore = pathentry + '/' +'.dockerignore',
        ignores = [];

    if (fs.statSync(dockerignore)) {
      grunt.log.debug('Detected a .dockerignore file, will perform ignoring tests');
      ignores = fs.readFileSync(dockerignore).toString().split("\n");
      ignores.push('.dockerignore');
    }

    tarfs.pack(pathentry, {
      ignore: function(name) {
        var relativeName = name.replace(pathentry + '/', ''),
            ignore = utils.shouldIgnore(ignores, relativeName);

        if (ignore) {
          grunt.log.debug('Ignoring file [' + relativeName +']');
        }

        return ignore;
      }
    }).pipe(zlib.createGzip())
      .pipe(concat(function (data) {
        build(data, buildOpts, callback);
      }));
  };

  var processFile = function(filepath, buildOpts, callback) {
    var content;
    try {
      content = fs.readFileSync(filepath);
    } catch(e) {
      return done(e);
    }
    var isTar = utils.isTarFile(filepath);
    switch(isTar) {
    case true:
      // The file is already a tar, build with it.
      build(content, buildOpts, callback);
      break;

    case false:
      // Compress the file before sending to docker
      var pack = tar.pack();
      pack.entry({ name:'Dockerfile' }, content);
      pack.finalize();

      pack.pipe(zlib.createGzip())
        .pipe(concat(function(data) {
          build(data, buildOpts, callback);
        }));

      break;
    }
  };

  // Process an image.
  // Determine if dockerfile option is directory or file.
  var process = function(tag, image, callback) {

    if (!image.dockerfile) { return callback(new Error('Dockerfile is null.')) };

    // Create the options object for the build
    var imageOptions = image.options || {};
    var buildOpts = utils.merge({t: tag}, imageOptions.build || {});

    var stats = fs.statSync(path.resolve(image.dockerfile));

    // Option 1: source is directory, pack it
    if (stats.isDirectory()) {
      processDirectory(image.dockerfile, buildOpts, callback);
    }
    else if (stats.isFile()) {
      processFile(image.dockerfile, buildOpts, callback);
    }
    else {
      return callback(new Error('Unsupported format.'));
    }
  };

  var i = 0;

  var tags = Object.keys(options.images);
  if (tag && tag !== 'default') {
    tags = [tag];
  }

  async.doWhilst(
    function (callback) {
      i ++;
      var tag = tags[i-1];
      var image = options.images[tag];

      process(tag, image, callback);
    },
    function () { return i < tags.length; },
    function (e) {
      done(e);
    }
  ); // do while images
};

module.exports = buildCommands;
<commit_msg>- Adding the check for the .dockerignore exists<commit_after>/*
 * MIT License (MIT) - Copyright (c) 2014 Johann Troendle
 *
 * This file is part of <grunt-dock>.
 */
var fs = require('fs'),
    path = require('path'),
    tar = require('tar-stream'),
    tarfs = require('tar-fs'),
    concat = require('concat-stream'),
    zlib = require('zlib'),
    async = require('async'),
    utils = require('./utils');

/**
 * Build images.
 * Each image is a content associated with its tag name.
 * The content can be a regular file or whatever for Docker.
 * In case of a plain file, it will be tar + gz before sent
 * to Docker.
 *
 * @param  {Object}   grunt   The Grunt Object
 * @param  {Object}   docker  The Dockerode connection
 * @param  {Object}   options The Grunt options
 * @param  {Function} done    The done function to call when finished
 * @param  {String}   tag     The image tag to work with or null
 */
var buildCommands = function(grunt, docker, options, done, tag) {

  // Build image with tag and its data/options.
  // Call callback when done or error.
  var build = function(data, options, callback) {
    grunt.log.subhead('Building image [' + options.t + ']');

    docker.buildImage(data, options, function(err, stream) {

      if (err) {
        return callback(err);
      }

      stream.setEncoding('utf8');

      stream.on('data', function(data) {
        var jsonData = JSON.parse(data);
        jsonData.stream && grunt.log.write(jsonData.stream);
        jsonData.error && grunt.fail.warn(jsonData.error);
      });

      stream.on('error', callback);
      stream.on('end', function() {
        grunt.log.oklns('Build successfuly done.');
        callback();
      });
    });
  };

  var processDirectory = function(dirpath, buildOpts, callback) {
    grunt.log.debug('Packing directory [' + dirpath + ']');
    var pathentry = path.resolve(dirpath),
        dockerignore = pathentry + '/' +'.dockerignore',
        ignores = [];

    if (fs.existsSync(dockerignore) && fs.statSync(dockerignore)) {
      grunt.log.debug('Detected a .dockerignore file, will perform ignoring tests');
      ignores = fs.readFileSync(dockerignore).toString().split("\n");
      ignores.push('.dockerignore');
    }

    tarfs.pack(pathentry, {
      ignore: function(name) {
        var relativeName = name.replace(pathentry + '/', ''),
            ignore = utils.shouldIgnore(ignores, relativeName);

        if (ignore) {
          grunt.log.debug('Ignoring file [' + relativeName +']');
        }

        return ignore;
      }
    }).pipe(zlib.createGzip())
      .pipe(concat(function (data) {
        build(data, buildOpts, callback);
      }));
  };

  var processFile = function(filepath, buildOpts, callback) {
    var content;
    try {
      content = fs.readFileSync(filepath);
    } catch(e) {
      return done(e);
    }
    var isTar = utils.isTarFile(filepath);
    switch(isTar) {
    case true:
      // The file is already a tar, build with it.
      build(content, buildOpts, callback);
      break;

    case false:
      // Compress the file before sending to docker
      var pack = tar.pack();
      pack.entry({ name:'Dockerfile' }, content);
      pack.finalize();

      pack.pipe(zlib.createGzip())
        .pipe(concat(function(data) {
          build(data, buildOpts, callback);
        }));

      break;
    }
  };

  // Process an image.
  // Determine if dockerfile option is directory or file.
  var process = function(tag, image, callback) {

    if (!image.dockerfile) { return callback(new Error('Dockerfile is null.')) };

    // Create the options object for the build
    var imageOptions = image.options || {};
    var buildOpts = utils.merge({t: tag}, imageOptions.build || {});

    var stats = fs.statSync(path.resolve(image.dockerfile));

    // Option 1: source is directory, pack it
    if (stats.isDirectory()) {
      processDirectory(image.dockerfile, buildOpts, callback);
    }
    else if (stats.isFile()) {
      processFile(image.dockerfile, buildOpts, callback);
    }
    else {
      return callback(new Error('Unsupported format.'));
    }
  };

  var i = 0;

  var tags = Object.keys(options.images);
  if (tag && tag !== 'default') {
    tags = [tag];
  }

  async.doWhilst(
    function (callback) {
      i ++;
      var tag = tags[i-1];
      var image = options.images[tag];

      process(tag, image, callback);
    },
    function () { return i < tags.length; },
    function (e) {
      done(e);
    }
  ); // do while images
};

module.exports = buildCommands;
<|endoftext|>


<commit_before>$(document).ready(init);
//Inicialitzar associacions Events-formulari
function init(){
	associaEvents();
}

//Connector Events
function associaEvents(){
	// MENU VERTICAL//
	$("a.noticies").click(llistatNoticies);
	$("a.multimedia").click(llistatMultimedies);
	$("a.usuaris").click(llistatUsuaris);

	//Inserir elements, eliminar o modificar elements//
	$('#enviarNot').click(inserirModificarNoticia);
	$('#borrarNot').click(netejaNoticia);

}

//FUNCIONS PER RECUPERAR DADES DE LA BASE DE DADES//
////////////////////////////////////////////////////

//Petic AJAX (llistat total de noticies de la BD)
function llistatNoticies(dades){
	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data: 'quin=noticies',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		//Trucada a funci (per no programar-la aqu i respectar el model)
		success: function(data) {presentaNoticies(data);}
	});
}

//Petic AJAX (llistat total de multimedies de la BD)
function llistatMultimedies(dades){
	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data: 'quin=multimedies',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		//Trucada a funci (per no programar-la aqu i respectar el model)
		success: function(data) {presentaMultimedies(data);}
	});
}

//Petic AJAX (llistat total de usuaris de la BD)
function llistatUsuaris(dades){
	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data : 'quin=usuaris',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		//Trucada a funci (per no programar-la aqu i respectar el model)
		success: function(data) {presentaUsuaris(data);}
	});
}

//FUNCIONS PER INSERIR DADES A LA BASE DE DADES//
/////////////////////////////////////////////////
function inserirModificarNoticia(){ //segons sigui el header del div, inserim o modifiquem
	var titol = document.getElementById('titolNot').value;

	var cont = document.getElementById('contingutNot').value;

	var tipus;

	if(document.getElementById('op1').checked){
		tipus = 'Vot';
	}

	if(document.getElementById('op2').checked){
		tipus = 'Enq';
	}

	if(document.getElementById('op3').checked){
		tipus = 'Ref';
	}

	var url = "test";
	var resum = "test";

	var quin = $('.inserirNoticia').find('.header').text();

	if(quin == "Inserir notcia"){
		$.ajax
		({	url: 'php/inserir.php',
			type: 'POST',
			data: 'quin=noticies&tipus='+tipus+'&titol='+titol+'&contingut='+cont+'&url='+url+'&resum='+resum ,
			cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
			success: function(data){alert("Dades inserides correctament")}

		});
	}

	if(quin == "Editar notcia"){
		var id = document.getElementById("idNot").innerHTML;
		$.ajax
		({	url: 'php/inserir.php',
			type: 'POST',
			data: 'quin=noticiesUpdate&id='+id+'&tipus='+tipus+'&titol='+titol+'&contingut='+cont+'&url='+url+'&resum='+resum ,
			cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
			success: function(data){alert("Dades actualitzades correctament")}

		});
	}

	netejaNoticia();
}

function netejaNoticia(){
	//netejem els camps
	document.getElementById('titolNot').value = "";

	document.getElementById('op1').checked = false;
	document.getElementById('op2').checked = false;
	document.getElementById('op3').checked = false;

	document.getElementById('contingutNot').value = "";
}

//FUNCIONS PER ELIMINAR DADES DE LA BASE DE DADES//
///////////////////////////////////////////////////

function eliminaNoticia(valor) {
	$.ajax
	({	url: 'php/elimina.php',
		dataType: 'json',
		type: 'GET',
		data: 'id='+valor+'&quin=noticia',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
	});
}

function eliminaMultimedia(valor) {
	$.ajax
	({	url: 'php/elimina.php',
		dataType: 'json',
		type: 'GET',
		data : 'id='+valor+'&quin=multimedia',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
	});
}

function eliminaUsuari(valor) {
	$.ajax
	({	url: 'php/elimina.php',
		dataType: 'json',
		type: 'GET',
		data: 'id='+valor+'&quin=usuari',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false
	});
}

// FUNCIONS PER MODIFICAR DADES DE LA BASE DE DADES//
/////////////////////////////////////////////////////
function recuperarNoticia(valor){ // primer recuperem la noticia que volem modificar
 	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data: 'quin=noticia&id='+valor,
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		success: function(data){presentaNoticia(data);}
	});
}

function presentaNoticia(data){
	// Primer mostrem la pagina d'inserir modificada amb els camps de la noticia
	$('.menuadmin a').removeClass('aqui');
    $('div.inserirNoticia').addClass('aqui');
    $('div.inserirNoticia').show();
    $('div.noticies, div.multimedia, div.resum,div.usuaris, div.inserirMulti, div.inserirUsuari').hide();

    $('.inserirNoticia .header').html("Editar notcia"); // s'ha de tornar al estat original al sortir !

    var id = data[1].id;
    var titol = data[1].titol;
    var tipus = data[1].tipus;
    var url = data[1].url;
    var cont = data[1].contingut;
    var resum = data[1].resum;

    $('#titolNot').val(titol);

    if(tipus == "Vot"){
		document.getElementById('op1').checked = true;
	}

	if(tipus == "Enq"){
		document.getElementById('op2').checked = true;
	}

	if(tipus == "Ref"){
		document.getElementById('op3').checked = true;
	}

	$('#contingutNot').val(cont);
	$('#resum').val(resum);

	// aquest p sera per guardar el id de la noticia, per actualitzar quan l'usuari clicki al boto enviar
	var element = document.createElement("p");
	var texte = document.createTextNode(id);
	element.appendChild(texte);
	element.style.display = "none";
	element.id = "idNot"

	document.getElementById("containerInsNot").appendChild(element);
}
//FUNCIONS PER PRESENTAR DADES DE LA BASE DE DADES//
////////////////////////////////////////////////////
function presentaNoticies(data){
	$("#containerNoticies").html("");
	$("#containerNoticies").append(
		$.each(data, function(index){
			var id = data[index].id;
			var titol = data[index].titol;

			var txt = '';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +''+titol+'';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +' ';
			txt = txt +' ';
			txt = txt +'
';
			txt = txt +'
';

			$("#containerNoticies").append(txt);

		})
		);
}

function presentaMultimedies(data){
	$("#containerMultimedia").html("");
	$("#containerMultimedia").append(
		$.each(data, function(index){
			var id = data[index].id;
			var titol = data[index].titol;

			var txt = '';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +''+titol+'';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +' ';
			txt = txt +' ';
			txt = txt +'
';
			txt = txt +'
';

			$("#containerMultimedia").append(txt);

		})
		);
}

function presentaUsuaris(data){
	$("#containerUsuaris").html("");
	$("#containerUsuaris").append(
		$.each(data, function(index){
			var id = data[index].id;
			var nom = data[index].nom;

			var txt = '';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +''+nom+'';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +' ';
			txt = txt +' ';
			txt = txt +'
';
			txt = txt +'
';

			$("#containerUsuaris").append(txt);

		})
		);
}

<commit_msg>Te posat la capçalera de les funcions que faltarien i algun comentari per alla XD si algo me dicee ^^ @rocduran<commit_after>$(document).ready(init);
//Inicialitzar associacions Events-formulari
function init(){
	associaEvents();
}

//Connector Events
function associaEvents(){
	// MENU VERTICAL//
	$("a.noticies").click(llistatNoticies);
	$("a.multimedia").click(llistatMultimedies);
	$("a.usuaris").click(llistatUsuaris);

	//Inserir elements, eliminar o modificar elements//
	$('#enviarNot').click(inserirModificarNoticia);
	$('#borrarNot').click(netejaNoticia);

	//AQUI FALTARIEN ELS DE enviarMultimedia i enviarUsuari (nse si es diuen aixi, al html surt XD)

}

//FUNCIONS PER RECUPERAR DADES DE LA BASE DE DADES//
////////////////////////////////////////////////////

//Petic AJAX (llistat total de noticies de la BD)
function llistatNoticies(dades){
	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data: 'quin=noticies',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		//Trucada a funci (per no programar-la aqu i respectar el model)
		success: function(data) {presentaNoticies(data);}
	});
}

//Petic AJAX (llistat total de multimedies de la BD)
function llistatMultimedies(dades){
	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data: 'quin=multimedies',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		//Trucada a funci (per no programar-la aqu i respectar el model)
		success: function(data) {presentaMultimedies(data);}
	});
}

//Petic AJAX (llistat total de usuaris de la BD)
function llistatUsuaris(dades){
	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data : 'quin=usuaris',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		//Trucada a funci (per no programar-la aqu i respectar el model)
		success: function(data) {presentaUsuaris(data);}
	});
}

//FUNCIONS PER INSERIR DADES A LA BASE DE DADES//
/////////////////////////////////////////////////
function inserirModificarNoticia(){ //segons sigui el header del div, inserim o modifiquem
	var titol = document.getElementById('titolNot').value;

	var cont = document.getElementById('contingutNot').value;

	var tipus;

	if(document.getElementById('op1').checked){
		tipus = 'Vot';
	}

	if(document.getElementById('op2').checked){
		tipus = 'Enq';
	}

	if(document.getElementById('op3').checked){
		tipus = 'Ref';
	}

	var url = "test";
	var resum = "test";

	var quin = $('.inserirNoticia').find('.header').text();

	if(quin == "Inserir notcia"){
		$.ajax
		({	url: 'php/inserir.php',
			type: 'POST',
			data: 'quin=noticies&tipus='+tipus+'&titol='+titol+'&contingut='+cont+'&url='+url+'&resum='+resum ,
			cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
			success: function(data){alert("Dades inserides correctament")}

		});
	}

	if(quin == "Editar notcia"){
		var id = document.getElementById("idNot").innerHTML;
		$.ajax
		({	url: 'php/inserir.php',
			type: 'POST',
			data: 'quin=noticiesUpdate&id='+id+'&tipus='+tipus+'&titol='+titol+'&contingut='+cont+'&url='+url+'&resum='+resum ,
			cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
			success: function(data){alert("Dades actualitzades correctament")}

		});
	}

	netejaNoticia();
}

function netejaNoticia(){
	//netejem els camps
	document.getElementById('titolNot').value = "";

	document.getElementById('op1').checked = false;
	document.getElementById('op2').checked = false;
	document.getElementById('op3').checked = false;

	document.getElementById('contingutNot').value = "";
}

function inserirModificarMultimedies(){ //segons sigui el header del div, inserim o modifiquem
	// com el de noticies
}

function netejaMultimedia(){

}

function inserirModificarUsuaris(){ //segons sigui el header del div, inserim o modifiquem
	//mas de lo mismo xd
}

function netejaUsuari(){

}

//FUNCIONS PER ELIMINAR DADES DE LA BASE DE DADES//
///////////////////////////////////////////////////

function eliminaNoticia(valor) {
	$.ajax
	({	url: 'php/elimina.php',
		dataType: 'json',
		type: 'GET',
		data: 'id='+valor+'&quin=noticia',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
	});
}

function eliminaMultimedia(valor) {
	$.ajax
	({	url: 'php/elimina.php',
		dataType: 'json',
		type: 'GET',
		data : 'id='+valor+'&quin=multimedia',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
	});
}

function eliminaUsuari(valor) {
	$.ajax
	({	url: 'php/elimina.php',
		dataType: 'json',
		type: 'GET',
		data: 'id='+valor+'&quin=usuari',
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false
	});
}

// FUNCIONS PER MODIFICAR DADES DE LA BASE DE DADES//
/////////////////////////////////////////////////////
function recuperarNoticia(valor){ // primer recuperem la noticia que volem modificar
 	$.ajax
	({	url: 'php/llistats.php',
		dataType: 'json',
		type: 'GET',
		data: 'quin=noticia&id='+valor,
		cache: false, //IE per a defecte emmagatzema en cach (evitar-ho-->false)
		success: function(data){presentaNoticia(data);}
	});
}

function presentaNoticia(data){
	// Primer mostrem la pagina d'inserir modificada amb els camps de la noticia
	$('.menuadmin a').removeClass('aqui');
    $('div.inserirNoticia').addClass('aqui');
    $('div.inserirNoticia').show();
    $('div.noticies, div.multimedia, div.resum,div.usuaris, div.inserirMulti, div.inserirUsuari').hide();

    $('.inserirNoticia .header').html("Editar notcia"); // s'ha de tornar al estat original al sortir !

    var id = data[1].id;
    var titol = data[1].titol;
    var tipus = data[1].tipus;
    var url = data[1].url;
    var cont = data[1].contingut;
    var resum = data[1].resum;

    $('#titolNot').val(titol);

    if(tipus == "Vot"){
		document.getElementById('op1').checked = true;
	}

	if(tipus == "Enq"){
		document.getElementById('op2').checked = true;
	}

	if(tipus == "Ref"){
		document.getElementById('op3').checked = true;
	}

	$('#contingutNot').val(cont);
	$('#resum').val(resum);

	// aquest p sera per guardar el id de la noticia, per actualitzar quan l'usuari clicki al boto enviar
	var element = document.createElement("p");
	var texte = document.createTextNode(id);
	element.appendChild(texte);
	element.style.display = "none";
	element.id = "idNot";

	document.getElementById("containerInsNot").appendChild(element);
}

function recuperarMultimedia(dades){
	//aqui aniria la peticio ajax + crida a la seguuent
}

function presentaMultimedia(data){
	//aqui lo de recuperar dades del element i presentarles, canviar el header i el div oculto pel id
}

function recuperarUsuari(dades){
	//mas de lo mismo XD
}

function presentaUsuari(data){
	//mas de lo mismo xD
}

function
//FUNCIONS PER PRESENTAR DADES DE LA BASE DE DADES//
////////////////////////////////////////////////////
function presentaNoticies(data){
	$("#containerNoticies").html("");
	$("#containerNoticies").append(
		$.each(data, function(index){
			var id = data[index].id;
			var titol = data[index].titol;

			var txt = '';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +''+titol+'';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +' ';
			txt = txt +' ';
			txt = txt +'
';
			txt = txt +'
';

			$("#containerNoticies").append(txt);

		})
		);
}

function presentaMultimedies(data){
	$("#containerMultimedia").html("");
	$("#containerMultimedia").append(
		$.each(data, function(index){
			var id = data[index].id;
			var titol = data[index].titol;

			var txt = '';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +''+titol+'';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +' ';
			txt = txt +' ';
			txt = txt +'
';
			txt = txt +'
';

			$("#containerMultimedia").append(txt);

		})
		);
}

function presentaUsuaris(data){
	$("#containerUsuaris").html("");
	$("#containerUsuaris").append(
		$.each(data, function(index){
			var id = data[index].id;
			var nom = data[index].nom;

			var txt = '';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +''+nom+'';
			txt = txt +'
';
			txt = txt +'
';
			txt = txt +' ';
			txt = txt +' ';
			txt = txt +'
';
			txt = txt +'
';

			$("#containerUsuaris").append(txt);

		})
		);
}

<|endoftext|>


<commit_before>'use strict';

var del = require('del');
var fs = require('fs');
var gulp = require('gulp');
var concat = require('gulp-concat');
var concatCss = require('gulp-concat-css');
var connect = require('gulp-connect');
var data = require('gulp-data');
var gulpif = require('gulp-if');
var minifyCss = require('gulp-minify-css');
var nunjucksRender = require('gulp-nunjucks-render');
var renameRegex = require('gulp-regex-rename');
var showHelp = require('gulp-showhelp');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var ini = require('ini');
var proxy = require('proxy-middleware');
var runSequence = require('run-sequence');

var config = {
  dev: true,
  srcJS: ['src/main/webapp/js/lib/angular.js',
    'src/main/webapp/js/lib/*.js',
    'src/main/webapp/js/app.js',
    'src/main/webapp/js/app/**/*module.js',
    'src/main/webapp/js/app/**/*.js'
  ],
  destJS: 'prd/js/',
  outJS: 'game.js',
  watchJS: 'src/main/webapp/js/app/**/*.js',
  srcGameCss: ['src/main/webapp/css/*.css'],
  outGameCSS: 'game.css',
  srcSiteCSS: ['!src/main/webapp/css/createGame.css', '!src/main/webapp/css/gamePage.css', 'src/main/webapp/css/*.css'],
  outSiteCSS: 'site.css',
  destCSS: 'prd/css/',
  watchCSS: 'src/main/webapp/css/*.css',
  srcHtml: ['!src/main/webapp/WEB-INF/_*.html', 'src/main/webapp/WEB-INF/*.html'],
  destHtml: 'prd',
  watchHtml: 'src/main/webapp/WEB-INF/*.html',
  scrPartials: 'src/main/webapp/js/app/**/*.html',
  destPartials: 'prd/partials',
  srcImg: 'src/main/webapp/img/**/*',
  destImg: 'prd/img',
  templates: {}
};

// We cannot use the default tags since they conflict with angular's
nunjucksRender.nunjucks.configure({
  tags: {
    variableStart: '${',
    variableEnd: '}'
  },
  watch: false
});

gulp.task('default', ['help']);

gulp.task('help', function () {
  showHelp.show(showHelp.taskNames().sort());
});

gulp.task('clean', function (cb) {
  del('prd', cb);
}).help = 'clean production files.';

gulp.task('cleanall', ['clean'], function (cb) {
  del('node_modules', cb);
}).help = 'launch clean and remove all node_modules.';

gulp.task('dev', function (cb) {
  runSequence(
      'load-dev-conf',
      ['build-js', 'build-css', 'build-html', 'build-partials', 'build-images'],
      cb);
}).help = 'build all files for development.';

gulp.task('load-dev-conf', function () {
  config.templates = ini.parse(fs.readFileSync('./config-dev.ini', 'utf-8'));
});

gulp.task('build-js', function () {
  return gulp.src(config.srcJS)
      .pipe(gulpif(config.dev, sourcemaps.init()))
      .pipe(concat(config.outJS))
      .pipe(uglify())
      .pipe(gulpif(config.dev, sourcemaps.write()))
      .pipe(gulp.dest(config.destJS));
});

gulp.task('build-css', ['build-game-css', 'build-site-css']);

gulp.task('build-game-css', function () {
  return gulp.src(config.srcGameCss)
      .pipe(gulpif(config.dev, sourcemaps.init()))
      .pipe(concatCss(config.outGameCSS))
      .pipe(minifyCss())
      .pipe(gulpif(config.dev, sourcemaps.write()))
      .pipe(gulp.dest(config.destCSS));
});

gulp.task('build-site-css', function () {
  return gulp.src(config.srcSiteCSS)
      .pipe(gulpif(config.dev, sourcemaps.init()))
      .pipe(concatCss(config.outSiteCSS))
      .pipe(minifyCss())
      .pipe(gulpif(config.dev, sourcemaps.write()))
      .pipe(gulp.dest(config.destCSS));
});

gulp.task('build-html', function () {
  return gulp.src(config.srcHtml)
      .pipe(data(function () {
        var nunjucksConfig = config.templates;
        return nunjucksConfig;
      }))
      .pipe(nunjucksRender())
      .pipe(renameRegex(/(.*).html/, '$1/index.html'))
      .pipe(renameRegex(/index\/index.html/, 'index.html'))
      .pipe(gulp.dest(config.destHtml));
});

gulp.task('build-partials', function () {
  return gulp.src(config.scrPartials)
      .pipe(renameRegex(/\/partials/, ''))
      .pipe(gulp.dest(config.destPartials));
});

gulp.task('build-images', function () {
  return gulp.src(config.srcImg)
      .pipe(gulp.dest(config.destImg));
});

gulp.task('watch', ['dev', 'serve'], function () {
  watch(config.watchJS, function () {
    gulp.start('build-js');
  });
  watch(config.watchCSS, function () {
    gulp.start('build-css');
  });
  watch(config.watchHtml, function () {
    gulp.start('build-html');
  });
}).help = 'watch files for modification and rebuild them.';

gulp.task('serve', function () {
  connect.server({
    root: 'prd',
    port: 8282,
    middleware: function () {
      return [(function () {
          var url = require('url');
          var options = url.parse('http://localhost:8080/api');
          options.route = '/api';
          return proxy(options);
        })()];
    }
  });
}).help = 'start a small server to ease devolopment of the frontend';

gulp.task('prod', function (cb) {
  runSequence(
      'clean',
      'load-prod-conf',
      ['build-js', 'build-css', 'build-html', 'build-images', 'build-partials'],
      cb);
}).help = 'build all files for production.';

gulp.task('load-prod-conf', function (cb) {
  config.dev = false;
  config.templates = ini.parse(fs.readFileSync('./config-prod.ini', 'utf-8'));

  cb();
});<commit_msg>chore: improve gulpfile<commit_after>'use strict';

var del = require('del');
var fs = require('fs');
var gulp = require('gulp');
var concat = require('gulp-concat');
var concatCss = require('gulp-concat-css');
var connect = require('gulp-connect');
var data = require('gulp-data');
var gulpif = require('gulp-if');
var minifyCss = require('gulp-minify-css');
var nunjucksRender = require('gulp-nunjucks-render');
var renameRegex = require('gulp-regex-rename');
var showHelp = require('gulp-showhelp');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var ini = require('ini');
var proxy = require('proxy-middleware');
var runSequence = require('run-sequence');

var config = {
  dev: true,
  srcJS: ['src/main/webapp/js/lib/angular.js',
    'src/main/webapp/js/lib/*.js',
    'src/main/webapp/js/app.js',
    'src/main/webapp/js/app/**/*module.js',
    'src/main/webapp/js/app/**/*.js'
  ],
  destJS: 'prd/js/',
  outJS: 'game.js',
  srcGameCss: ['src/main/webapp/css/*.css'],
  outGameCSS: 'game.css',
  srcSiteCSS: ['!src/main/webapp/css/createGame.css', '!src/main/webapp/css/gamePage.css', 'src/main/webapp/css/*.css'],
  outSiteCSS: 'site.css',
  destCSS: 'prd/css/',
  srcHtml: ['!src/main/webapp/WEB-INF/_*.html', 'src/main/webapp/WEB-INF/*.html'],
  destHtml: 'prd',
  srcPartials: 'src/main/webapp/js/app/**/*.html',
  destPartials: 'prd/partials',
  srcImg: 'src/main/webapp/img/**/*',
  destImg: 'prd/img',
  templates: {}
};

// We cannot use the default tags since they conflict with angular's
nunjucksRender.nunjucks.configure({
  tags: {
    variableStart: '${',
    variableEnd: '}'
  },
  watch: false
});

gulp.task('default', ['help']);

gulp.task('help', function () {
  showHelp.show(showHelp.taskNames().sort());
});

gulp.task('clean', function (cb) {
  del('prd', cb);
}).help = 'clean production files.';

gulp.task('cleanall', ['clean'], function (cb) {
  del('node_modules', cb);
}).help = 'launch clean and remove all node_modules.';

gulp.task('dev', function (cb) {
  runSequence(
      'load-dev-conf',
      ['build-js', 'build-css', 'build-html', 'build-partials', 'build-images'],
      cb);
}).help = 'build all files for development.';

gulp.task('load-dev-conf', function () {
  config.templates = ini.parse(fs.readFileSync('./config-dev.ini', 'utf-8'));
});

gulp.task('build-js', function () {
  return gulp.src(config.srcJS)
      .pipe(gulpif(config.dev, sourcemaps.init()))
      .pipe(concat(config.outJS))
      .pipe(uglify())
      .pipe(gulpif(config.dev, sourcemaps.write()))
      .pipe(gulp.dest(config.destJS));
});

gulp.task('build-css', ['build-game-css', 'build-site-css']);

gulp.task('build-game-css', function () {
  return gulp.src(config.srcGameCss)
      .pipe(gulpif(config.dev, sourcemaps.init()))
      .pipe(concatCss(config.outGameCSS))
      .pipe(minifyCss())
      .pipe(gulpif(config.dev, sourcemaps.write()))
      .pipe(gulp.dest(config.destCSS));
});

gulp.task('build-site-css', function () {
  return gulp.src(config.srcSiteCSS)
      .pipe(gulpif(config.dev, sourcemaps.init()))
      .pipe(concatCss(config.outSiteCSS))
      .pipe(minifyCss())
      .pipe(gulpif(config.dev, sourcemaps.write()))
      .pipe(gulp.dest(config.destCSS));
});

gulp.task('build-html', function () {
  return gulp.src(config.srcHtml)
      .pipe(data(function () {
        var nunjucksConfig = config.templates;
        return nunjucksConfig;
      }))
      .pipe(nunjucksRender())
      .pipe(renameRegex(/(.*).html/, '$1/index.html'))
      .pipe(renameRegex(/index\/index.html/, 'index.html'))
      .pipe(gulp.dest(config.destHtml));
});

gulp.task('build-partials', function () {
  return gulp.src(config.srcPartials)
      .pipe(renameRegex(/\/partials/, ''))
      .pipe(gulp.dest(config.destPartials));
});

gulp.task('build-images', function () {
  return gulp.src(config.srcImg)
      .pipe(gulp.dest(config.destImg));
});

gulp.task('watch', ['dev', 'serve'], function () {
  watch(config.srcJS, function () {
    gulp.start('build-js');
  });
  watch(config.srcGameCss, function () {
    gulp.start('build-css');
  });
  watch(config.srcHtml, function () {
    gulp.start('build-html');
  });
  watch(config.srcPartials, function () {
    gulp.start('build-partials');
  });
  watch(config.srcImg, function () {
    gulp.start('build-images')
  });
}).help = 'watch files for modification and rebuild them.';

gulp.task('serve', function () {
  connect.server({
    root: 'prd',
    port: 8282,
    middleware: function () {
      return [(function () {
          var url = require('url');
          var options = url.parse('http://localhost:8080/api');
          options.route = '/api';
          return proxy(options);
        })()];
    }
  });
}).help = 'start a small server to ease devolopment of the frontend';

gulp.task('prod', function (cb) {
  runSequence(
      'clean',
      'load-prod-conf',
      ['build-js', 'build-css', 'build-html', 'build-images', 'build-partials'],
      cb);
}).help = 'build all files for production.';

gulp.task('load-prod-conf', function (cb) {
  config.dev = false;
  config.templates = ini.parse(fs.readFileSync('./config-prod.ini', 'utf-8'));

  cb();
});<|endoftext|>


<commit_before>// Copyright 2017-2020, University of Colorado Boulder

/**
 * Unit tests for phetcommon. Please run once in phet brand and once in brand=phet-io to cover all functionality.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

import qunitStart from '../../chipper/js/sim-tests/qunitStart.js';
import './model/FractionTests.js';
import './util/StringUtilsTests.js';

// Since our tests are loaded asynchronously, we must direct QUnit to begin the tests
qunitStart();<commit_msg>update copyright dates from daily grunt work<commit_after>// Copyright 2017-2022, University of Colorado Boulder

/**
 * Unit tests for phetcommon. Please run once in phet brand and once in brand=phet-io to cover all functionality.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

import qunitStart from '../../chipper/js/sim-tests/qunitStart.js';
import './model/FractionTests.js';
import './util/StringUtilsTests.js';

// Since our tests are loaded asynchronously, we must direct QUnit to begin the tests
qunitStart();<|endoftext|>


<commit_before>//
// File:    parity.js
// Author:  Abe Fehr
// Version: 0.2
//
// Contains the main game logic for parity
//

$(document).ready(function() {

  //all the page objects
  var resetLink   = $('#reset');
  var levelLink   = $('#level');
  var overlay     = $('#overlay');
  var button      = $('#overlay > #holder > button');
  var board       = $('#board');
  var cells = [];
  for(var i = 0; i < 4; ++i) {
    cells.push([]);
    for(var j = 0; j < 4; ++j) {
      cells[i].push($('td[data-x="' + i + '"][data-y="' + j + '"]'));
    }
  }

  //the bookmark in the story of the game
  var bookmark = 0;

  var options = {
    fade: 300 //the time in ms for the fade
  }

  //where we'll store the current level
  var level;

  //where we'll store the instructions and the levels
  var story;

  $(document).keydown(function(e){
    if(story[bookmark].type == 'level') {
      if(e.keyCode == 37) {
        left();
        return false;
      }
      if(e.keyCode == 38) {
        up();
        return false;
      }
      if(e.keyCode == 39) {
        right();
        return false;
      }
      if(e.keyCode == 40) {
        down();
        return false;
      }
    }
    else if(story[bookmark].type == 'overlay') {
      if(e.keyCode == 32) {
        button.trigger('click');
      }
    }
  });

  //selects the cell to the left of the current cell
  function left() {
    if(level.selected.x > 0) {
      select(--level.selected.x, level.selected.y);
      update();
    }
  }

  //selects the cell above the current cell
  function up() {
    if(level.selected.y > 0) {
      select(level.selected.x, --level.selected.y);
      update();
    }
  }

  //selects the cell to the right of the current cell
  function right() {
    if(level.selected.x < 2) {
      select(++level.selected.x, level.selected.y);
      update();
    }
  }

  //selects the cell under the current cell
  function down() {
    if(level.selected.y < 2) {
      select(level.selected.x, ++level.selected.y);
      update();
    }
  }

  //selects a cell and increases its value
  function select(x, y) {
    //increase the number in the selected cell
    cell(level.selected.x, level.selected.y, cell(level.selected.x, level.selected.y)+1);
  }

  // goes through the model(the story), draws the board accordingly,
  // and checks if it's a win scenario
  function update() {
    if(story[bookmark].type == 'level') {
      //go through the board and clear it of all the "selected" classes
      $('td.selected').removeClass('selected');

      cells[level.selected.x][level.selected.y].addClass('selected');

      //check if it's a win
      if(isWin()) {
        advanceStory();
      }
    }
  }

  // gets the current page of the story where the bookmark is, parses
  // it, and puts it in the grid
  function loadCurrentPage() {
    if(story[bookmark].type == 'level') {
      if(story[bookmark].contents == 'generated') {
        //generate a level
        data = generate(story[bookmark]);
        loadLevel(data);
      }
      else {
        loadLevel(story[bookmark]);
      }
    }
    else if(story[bookmark].type == 'overlay') {
      //get the current slide that the overlay is on
      if(!story[bookmark].current)
        story[bookmark].current = 0;
      var index = story[bookmark].current;
      var slide = story[bookmark].contents[index];

      showOverlay(slide);
    }
  }

  //validation function to be used later
  function valid(direction, x, y) {
    switch(direction) {
      case 0:
        return false;
      case 1: //north
        if(y == 0) {
          return false;
        }
        return true;
      case 2: //east
        if(x == 2) {
          return false;
        }
        return true;
      case 3: //south
        if(y == 2) {
          return false;
        }
        return true;
      case 4: //west
        if(x == 0) {
          return false;
        }
        return true;
    }
  }

  //generates a level
  function generate(level) {
    //create a new object
    //create an array for the level data
    var content = [];

    //push the initial value into the array that number of times
    for(var i=0;i<9;++i) {
      content.push(level.schema.end);
    }

    //generate a random number of steps in the bounds
    var moveRange = level.schema.maxNumMoves - level.schema.minNumMoves;
    var numMoves = level.schema.minNumMoves + Math.random()*(moveRange);

    //generate a random starting location
    var x = Math.floor(Math.random()*3);
    var y = Math.floor(Math.random()*3);

    //loop through all the moves
    for(var i=0;i<numMoves;++i) {
      //for each time, move the coordinates by one in a random direction...
      var direction = 0; //initialize it to 0(non-real direction)
      while(!valid(direction, x, y)) {
        //generate a number between 1 and 4 inclusive
        direction = Math.floor(1 + Math.random()*4);
      }
      //at this point, the direction is valid so we're just moving it one
      switch(direction) {
        case 1: //north
          --content[y*3+x];
          --y;
          break;
        case 2: //east
          --content[y*3+x];
          ++x;
          break;
        case 3: //south
          --content[y*3+x];
          ++y;
          break;
        case 4: //west
          --content[y*3+x];
          --x;
          break;
      }
    }

    return {
      type: level.type,
      number: level.number,
      contents: content,
      initialSelected: { x: x, y: y }
    };
  }

  //loads a level
  function loadLevel(data) {
    //set the level data
    level = data;

    //parse its contents
    for(var i = 0; i < level.contents.length; ++i) {
      cell(i % 3,Math.floor(i / 3), level.contents[i]);
    }

    //set the currently selected cell
    level.selected = {
      x: data.initialSelected.x,
      y: data.initialSelected.y
    };

    //put the level number in the corner
    levelLink.html('level ' + level.number + '/' + numLevels());

    //fade in the level
    board.fadeIn(options['fade']);

    //update the screen
    update();

    //save it in a cookie
    saveProgress();

    //add the anchor to the url
    document.location.hash = "#" + level.number;
  }

  //resets the board back to the level's beginning
  function reset() {
    loadLevel(level);
  }

  //checks to see if there's a win condition or not
  //returns: boolean
  function isWin() {
    var value = cell(0,0);
    for(var i = 0; i < 3; ++i) {
      for(var j = 0; j < 3; ++j) {
        if(cell(i,j) != value)
          return false
      }
    }
    return true;
  }

  //gets or sets a cells
  //input: -the x/y location of a cell
  //       -the value to put into the cell(optional)
  //returns: -the contents of the cell(if no value is given)
  //         -nothing, if a value is given
  function cell(x, y, value) {
    //either gets the contents of x, y or sets them
    if(arguments.length==3) {
      cells[x][y].html(value);
    }
    else {
      //return the value
      return parseInt(cells[x][y].html());
    }
  }

  //starts the game by initializing the level text and displaying
  //the first level
  function start() {
    //put the level number in the corner
    levelLink.html('level 0/' + numLevels());

    /*
     * at this point, the level must be loaded.
     *
     * it can either be loaded from the anchor in the url
     * or the last level from the cookie...so which do we
     * choose? first we'll check to see if there's an anchor,
     * and we'll actually save THAT level in the cookie.
     *
     * if there is no anchor, just load whatever is in the
     * cookie.
     */
    levelNo = window.location.hash.substring(1);

    if(levelNo) {
      setLevel(levelNo);
    }
    else {
      loadProgress();
    }

    //actually load the level
    loadCurrentPage();

    //update the stuff
    update();
  }

  //fades out the board
  //input: -the callback to call when the fade is completed
  function fadeOut(callback) {
    //only fade out that visible component
    if(board.is(':visible'))
      board.fadeOut(options['fade'], callback);

    if(overlay.is(':visible'))
      overlay.fadeOut(options['fade'], callback);
  }

  //tries to advance the story
  function advanceStory() {
    //tries to advance the current slide first if it's an overlay
    if(story[bookmark].type == 'overlay') {
      if(++story[bookmark].current < story[bookmark].contents.length) {
          fadeOut(loadCurrentPage);
          return;
      }
    }

    if(++bookmark < story.length) {
      fadeOut(loadCurrentPage);
    }
  }

  //gets the number of levels in the story
  function numLevels() {
    //go through the stuff in the story
    var sum = 0;
    for(var i=0; i < story.length; ++i) {
      if(story[i].type == 'level') {
        ++sum;
      }
    }
    return sum;
  }

  function showOverlay(slide) {
    //put the text from the thingy into the overlay
    var title   = slide.title;
    var content = slide.content;
    var action  = slide.button;

    $('#overlay > h1').html(title);
    $('#overlay > #content').html(content);
    if(action) {
      button.show();
      button.html(action);
    }
    else
      button.hide();

    overlay.fadeIn(options['fade']);
  }

  //brings up the level selector
  function levelSelect() {
    //create the level select object
    var levelselect = {
      title:   'Level Select',
      content: ''
    };
    //go through all of the levels in the story
    levelselect.content += '
'
    var j = 0; //for counting the columns
    for(var i = 0; i < story.length; ++i) {
      if(story[i].type == 'level') {
        var num = story[i].number;
        if(j % 3 == 0) {
          levelselect.content += '
';
        }
        levelselect.content += '
' + num + '
	';
        if(j+1 % 3 == 0) {
          levelselect.content += '
';
        }
        ++j;
      }
    }
    levelselect.content += '
'

    //show that as an overlay
    showOverlay(levelselect);
  }

  //sets the current level to whatever
  function setLevel(n) {
    //now we just need to make sure it exists
    var bookmarkNo = getBookmarkOfLevel(n)

    if(bookmarkNo != -1) {
      bookmark = bookmarkNo;

      //hide the overlay
      overlay.hide();
    }
  }

  //gets the bookmark number for a level number
  //input:   -the level number
  //returns: -the bookmark number
  function getBookmarkOfLevel(n) {
    for(var i = 0; i < story.length; ++i) {
      if(story[i].number == n) {
        return i;
      }
    }
    return -1;
  }

  //event assignments
  button.click(advanceStory);
  resetLink.click(reset);
  levelLink.click(function() {
    fadeOut(levelSelect);
  });

  //start the game off by getting the story
  $.getJSON('story.json', function(data) {
    story = data;
    start();
  });
});
<commit_msg>added a quick comment<commit_after>//
// File:    parity.js
// Author:  Abe Fehr
// Version: 0.2
//
// Contains the main game logic for parity
//

//the main entry point for the game
$(document).ready(function() {

  //all the page objects
  var resetLink   = $('#reset');
  var levelLink   = $('#level');
  var overlay     = $('#overlay');
  var button      = $('#overlay > #holder > button');
  var board       = $('#board');
  var cells = [];
  for(var i = 0; i < 4; ++i) {
    cells.push([]);
    for(var j = 0; j < 4; ++j) {
      cells[i].push($('td[data-x="' + i + '"][data-y="' + j + '"]'));
    }
  }

  //the bookmark in the story of the game
  var bookmark = 0;

  var options = {
    fade: 300 //the time in ms for the fade
  }

  //where we'll store the current level
  var level;

  //where we'll store the instructions and the levels
  var story;

  $(document).keydown(function(e){
    if(story[bookmark].type == 'level') {
      if(e.keyCode == 37) {
        left();
        return false;
      }
      if(e.keyCode == 38) {
        up();
        return false;
      }
      if(e.keyCode == 39) {
        right();
        return false;
      }
      if(e.keyCode == 40) {
        down();
        return false;
      }
    }
    else if(story[bookmark].type == 'overlay') {
      if(e.keyCode == 32) {
        button.trigger('click');
      }
    }
  });

  //selects the cell to the left of the current cell
  function left() {
    if(level.selected.x > 0) {
      select(--level.selected.x, level.selected.y);
      update();
    }
  }

  //selects the cell above the current cell
  function up() {
    if(level.selected.y > 0) {
      select(level.selected.x, --level.selected.y);
      update();
    }
  }

  //selects the cell to the right of the current cell
  function right() {
    if(level.selected.x < 2) {
      select(++level.selected.x, level.selected.y);
      update();
    }
  }

  //selects the cell under the current cell
  function down() {
    if(level.selected.y < 2) {
      select(level.selected.x, ++level.selected.y);
      update();
    }
  }

  //selects a cell and increases its value
  function select(x, y) {
    //increase the number in the selected cell
    cell(level.selected.x, level.selected.y, cell(level.selected.x, level.selected.y)+1);
  }

  // goes through the model(the story), draws the board accordingly,
  // and checks if it's a win scenario
  function update() {
    if(story[bookmark].type == 'level') {
      //go through the board and clear it of all the "selected" classes
      $('td.selected').removeClass('selected');

      cells[level.selected.x][level.selected.y].addClass('selected');

      //check if it's a win
      if(isWin()) {
        advanceStory();
      }
    }
  }

  // gets the current page of the story where the bookmark is, parses
  // it, and puts it in the grid
  function loadCurrentPage() {
    if(story[bookmark].type == 'level') {
      if(story[bookmark].contents == 'generated') {
        //generate a level
        data = generate(story[bookmark]);
        loadLevel(data);
      }
      else {
        loadLevel(story[bookmark]);
      }
    }
    else if(story[bookmark].type == 'overlay') {
      //get the current slide that the overlay is on
      if(!story[bookmark].current)
        story[bookmark].current = 0;
      var index = story[bookmark].current;
      var slide = story[bookmark].contents[index];

      showOverlay(slide);
    }
  }

  //validation function to be used later
  function valid(direction, x, y) {
    switch(direction) {
      case 0:
        return false;
      case 1: //north
        if(y == 0) {
          return false;
        }
        return true;
      case 2: //east
        if(x == 2) {
          return false;
        }
        return true;
      case 3: //south
        if(y == 2) {
          return false;
        }
        return true;
      case 4: //west
        if(x == 0) {
          return false;
        }
        return true;
    }
  }

  //generates a level
  function generate(level) {
    //create a new object
    //create an array for the level data
    var content = [];

    //push the initial value into the array that number of times
    for(var i=0;i<9;++i) {
      content.push(level.schema.end);
    }

    //generate a random number of steps in the bounds
    var moveRange = level.schema.maxNumMoves - level.schema.minNumMoves;
    var numMoves = level.schema.minNumMoves + Math.random()*(moveRange);

    //generate a random starting location
    var x = Math.floor(Math.random()*3);
    var y = Math.floor(Math.random()*3);

    //loop through all the moves
    for(var i=0;i<numMoves;++i) {
      //for each time, move the coordinates by one in a random direction...
      var direction = 0; //initialize it to 0(non-real direction)
      while(!valid(direction, x, y)) {
        //generate a number between 1 and 4 inclusive
        direction = Math.floor(1 + Math.random()*4);
      }
      //at this point, the direction is valid so we're just moving it one
      switch(direction) {
        case 1: //north
          --content[y*3+x];
          --y;
          break;
        case 2: //east
          --content[y*3+x];
          ++x;
          break;
        case 3: //south
          --content[y*3+x];
          ++y;
          break;
        case 4: //west
          --content[y*3+x];
          --x;
          break;
      }
    }

    return {
      type: level.type,
      number: level.number,
      contents: content,
      initialSelected: { x: x, y: y }
    };
  }

  //loads a level
  function loadLevel(data) {
    //set the level data
    level = data;

    //parse its contents
    for(var i = 0; i < level.contents.length; ++i) {
      cell(i % 3,Math.floor(i / 3), level.contents[i]);
    }

    //set the currently selected cell
    level.selected = {
      x: data.initialSelected.x,
      y: data.initialSelected.y
    };

    //put the level number in the corner
    levelLink.html('level ' + level.number + '/' + numLevels());

    //fade in the level
    board.fadeIn(options['fade']);

    //update the screen
    update();

    //save it in a cookie
    saveProgress();

    //add the anchor to the url
    document.location.hash = "#" + level.number;
  }

  //resets the board back to the level's beginning
  function reset() {
    loadLevel(level);
  }

  //checks to see if there's a win condition or not
  //returns: boolean
  function isWin() {
    var value = cell(0,0);
    for(var i = 0; i < 3; ++i) {
      for(var j = 0; j < 3; ++j) {
        if(cell(i,j) != value)
          return false
      }
    }
    return true;
  }

  //gets or sets a cells
  //input: -the x/y location of a cell
  //       -the value to put into the cell(optional)
  //returns: -the contents of the cell(if no value is given)
  //         -nothing, if a value is given
  function cell(x, y, value) {
    //either gets the contents of x, y or sets them
    if(arguments.length==3) {
      cells[x][y].html(value);
    }
    else {
      //return the value
      return parseInt(cells[x][y].html());
    }
  }

  //starts the game by initializing the level text and displaying
  //the first level
  function start() {
    //put the level number in the corner
    levelLink.html('level 0/' + numLevels());

    /*
     * at this point, the level must be loaded.
     *
     * it can either be loaded from the anchor in the url
     * or the last level from the cookie...so which do we
     * choose? first we'll check to see if there's an anchor,
     * and we'll actually save THAT level in the cookie.
     *
     * if there is no anchor, just load whatever is in the
     * cookie.
     */
    levelNo = window.location.hash.substring(1);

    if(levelNo) {
      setLevel(levelNo);
    }
    else {
      loadProgress();
    }

    //actually load the level
    loadCurrentPage();

    //update the stuff
    update();
  }

  //fades out the board
  //input: -the callback to call when the fade is completed
  function fadeOut(callback) {
    //only fade out that visible component
    if(board.is(':visible'))
      board.fadeOut(options['fade'], callback);

    if(overlay.is(':visible'))
      overlay.fadeOut(options['fade'], callback);
  }

  //tries to advance the story
  function advanceStory() {
    //tries to advance the current slide first if it's an overlay
    if(story[bookmark].type == 'overlay') {
      if(++story[bookmark].current < story[bookmark].contents.length) {
          fadeOut(loadCurrentPage);
          return;
      }
    }

    if(++bookmark < story.length) {
      fadeOut(loadCurrentPage);
    }
  }

  //gets the number of levels in the story
  function numLevels() {
    //go through the stuff in the story
    var sum = 0;
    for(var i=0; i < story.length; ++i) {
      if(story[i].type == 'level') {
        ++sum;
      }
    }
    return sum;
  }

  function showOverlay(slide) {
    //put the text from the thingy into the overlay
    var title   = slide.title;
    var content = slide.content;
    var action  = slide.button;

    $('#overlay > h1').html(title);
    $('#overlay > #content').html(content);
    if(action) {
      button.show();
      button.html(action);
    }
    else
      button.hide();

    overlay.fadeIn(options['fade']);
  }

  //brings up the level selector
  function levelSelect() {
    //create the level select object
    var levelselect = {
      title:   'Level Select',
      content: ''
    };
    //go through all of the levels in the story
    levelselect.content += '
'
    var j = 0; //for counting the columns
    for(var i = 0; i < story.length; ++i) {
      if(story[i].type == 'level') {
        var num = story[i].number;
        if(j % 3 == 0) {
          levelselect.content += '
';
        }
        levelselect.content += '
' + num + '
	';
        if(j+1 % 3 == 0) {
          levelselect.content += '
';
        }
        ++j;
      }
    }
    levelselect.content += '
'

    //show that as an overlay
    showOverlay(levelselect);
  }

  //sets the current level to whatever
  function setLevel(n) {
    //now we just need to make sure it exists
    var bookmarkNo = getBookmarkOfLevel(n)

    if(bookmarkNo != -1) {
      bookmark = bookmarkNo;

      //hide the overlay
      overlay.hide();
    }
  }

  //gets the bookmark number for a level number
  //input:   -the level number
  //returns: -the bookmark number
  function getBookmarkOfLevel(n) {
    for(var i = 0; i < story.length; ++i) {
      if(story[i].number == n) {
        return i;
      }
    }
    return -1;
  }

  //event assignments
  button.click(advanceStory);
  resetLink.click(reset);
  levelLink.click(function() {
    fadeOut(levelSelect);
  });

  //start the game off by getting the story
  $.getJSON('story.json', function(data) {
    story = data;
    start();
  });
});
<|endoftext|>


<commit_before>/*
 * L.Marker is used to display clickable/draggable icons on the map.
 */

L.Marker = L.Class.extend({

	includes: L.Mixin.Events,

	options: {
		icon: new L.Icon.Default(),
		title: '',
		clickable: true,
		draggable: false,
		zIndexOffset: 0,
		opacity: 1,
		riseOnHover: false,
		riseOffset: 250
	},

	initialize: function (latlng, options) {
		L.setOptions(this, options);
		this._latlng = L.latLng(latlng);
	},

	onAdd: function (map) {
		this._map = map;

		map.on('viewreset', this.update, this);

		this._initIcon();
		this.update();

		if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
			map.on('zoomanim', this._animateZoom, this);
		}
	},

	addTo: function (map) {
		map.addLayer(this);
		return this;
	},

	onRemove: function (map) {
		if (this.dragging) {
			this.dragging.disable();
		}

		this._removeIcon();
		this._removeShadow();

		this.fire('remove');

		map.off({
			'viewreset': this.update,
			'zoomanim': this._animateZoom
		}, this);

		this._map = null;
	},

	getLatLng: function () {
		return this._latlng;
	},

	setLatLng: function (latlng) {
		this._latlng = L.latLng(latlng);

		this.update();

		return this.fire('move', { latlng: this._latlng });
	},

	setZIndexOffset: function (offset) {
		this.options.zIndexOffset = offset;
		this.update();

		return this;
	},

	setIcon: function (icon) {

		this.options.icon = icon;

		if (this._map) {
			this._initIcon();
			this.update();
		}

		return this;
	},

	update: function () {
		if (this._icon) {
			var pos = this._map.latLngToLayerPoint(this._latlng).round();
			this._setPos(pos);
		}

		return this;
	},

	_initIcon: function () {
		var options = this.options,
		    map = this._map,
		    animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
		    classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';

		var icon = options.icon.createIcon(this._icon),
			addIcon = false;

		// if we're not reusing the icon, remove the old one and init new one
		if (icon !== this._icon) {
			if (this._icon) {
				this._removeIcon();
			}
			addIcon = true;

			if (options.title) {
				icon.title = options.title;
			}
		}

		L.DomUtil.addClass(icon, classToAdd);

		this._icon = icon;

		this._initInteraction();

		if (options.riseOnHover) {
			L.DomEvent
				.on(icon, 'mouseover', this._bringToFront, this)
				.on(icon, 'mouseout', this._resetZIndex, this);
		}

		var newShadow = options.icon.createShadow(this._shadow),
			addShadow = false;

		if (newShadow !== this._shadow) {
			this._removeShadow();
			addShadow = true;

			if (newShadow) {
				L.DomUtil.addClass(newShadow, classToAdd);
			}
		}
		this._shadow = newShadow;

		if (options.opacity < 1) {
			this._updateOpacity();
		}

		var panes = this._map._panes;

		if (addIcon) {
			panes.markerPane.appendChild(this._icon);
		}

		if (newShadow && addShadow) {
			panes.shadowPane.appendChild(this._shadow);
		}
	},

	_removeIcon: function () {
		if (this.options.riseOnHover) {
			L.DomEvent
			    .off(this._icon, 'mouseover', this._bringToFront)
			    .off(this._icon, 'mouseout', this._resetZIndex);
		}

		this._map._panes.markerPane.removeChild(this._icon);

		this._icon = null;
	},

	_removeShadow: function () {
		if (this._shadow) {
			this._map._panes.shadowPane.removeChild(this._shadow);
		}
		this._shadow = null;
	},

	_setPos: function (pos) {
		L.DomUtil.setPosition(this._icon, pos);

		if (this._shadow) {
			L.DomUtil.setPosition(this._shadow, pos);
		}

		this._zIndex = pos.y + this.options.zIndexOffset;

		this._resetZIndex();
	},

	_updateZIndex: function (offset) {
		this._icon.style.zIndex = this._zIndex + offset;
	},

	_animateZoom: function (opt) {
		var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);

		this._setPos(pos);
	},

	_initInteraction: function () {

		if (!this.options.clickable) { return; }

		// TODO refactor into something shared with Map/Path/etc. to DRY it up

		var icon = this._icon,
		    events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];

		L.DomUtil.addClass(icon, 'leaflet-clickable');
		L.DomEvent.on(icon, 'click', this._onMouseClick, this);

		for (var i = 0; i < events.length; i++) {
			L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
		}

		if (L.Handler.MarkerDrag) {
			this.dragging = new L.Handler.MarkerDrag(this);

			if (this.options.draggable) {
				this.dragging.enable();
			}
		}
	},

	_onMouseClick: function (e) {
		var wasDragged = this.dragging && this.dragging.moved();

		if (this.hasEventListeners(e.type) || wasDragged) {
			L.DomEvent.stopPropagation(e);
		}

		if (wasDragged) { return; }

		if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }

		this.fire(e.type, {
			originalEvent: e,
			latlng: this._latlng
		});
	},

	_fireMouseEvent: function (e) {

		this.fire(e.type, {
			originalEvent: e,
			latlng: this._latlng
		});

		// TODO proper custom event propagation
		// this line will always be called if marker is in a FeatureGroup
		if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
			L.DomEvent.preventDefault(e);
		}
		if (e.type !== 'mousedown') {
			L.DomEvent.stopPropagation(e);
		}
	},

	setOpacity: function (opacity) {
		this.options.opacity = opacity;
		if (this._map) {
			this._updateOpacity();
		}
	},

	_updateOpacity: function () {
		L.DomUtil.setOpacity(this._icon, this.options.opacity);
		if (this._shadow) {
			L.DomUtil.setOpacity(this._shadow, this.options.opacity);
		}
	},

	_bringToFront: function () {
		this._updateZIndex(this.options.riseOffset);
	},

	_resetZIndex: function () {
		this._updateZIndex(0);
	}
});

L.marker = function (latlng, options) {
	return new L.Marker(latlng, options);
};
<commit_msg>add keyboard accessibility to markers, close #1355<commit_after>/*
 * L.Marker is used to display clickable/draggable icons on the map.
 */

L.Marker = L.Class.extend({

	includes: L.Mixin.Events,

	options: {
		icon: new L.Icon.Default(),
		title: '',
		clickable: true,
		draggable: false,
		keyboard: true,
		zIndexOffset: 0,
		opacity: 1,
		riseOnHover: false,
		riseOffset: 250
	},

	initialize: function (latlng, options) {
		L.setOptions(this, options);
		this._latlng = L.latLng(latlng);
	},

	onAdd: function (map) {
		this._map = map;

		map.on('viewreset', this.update, this);

		this._initIcon();
		this.update();

		if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
			map.on('zoomanim', this._animateZoom, this);
		}
	},

	addTo: function (map) {
		map.addLayer(this);
		return this;
	},

	onRemove: function (map) {
		if (this.dragging) {
			this.dragging.disable();
		}

		this._removeIcon();
		this._removeShadow();

		this.fire('remove');

		map.off({
			'viewreset': this.update,
			'zoomanim': this._animateZoom
		}, this);

		this._map = null;
	},

	getLatLng: function () {
		return this._latlng;
	},

	setLatLng: function (latlng) {
		this._latlng = L.latLng(latlng);

		this.update();

		return this.fire('move', { latlng: this._latlng });
	},

	setZIndexOffset: function (offset) {
		this.options.zIndexOffset = offset;
		this.update();

		return this;
	},

	setIcon: function (icon) {

		this.options.icon = icon;

		if (this._map) {
			this._initIcon();
			this.update();
		}

		return this;
	},

	update: function () {
		if (this._icon) {
			var pos = this._map.latLngToLayerPoint(this._latlng).round();
			this._setPos(pos);
		}

		return this;
	},

	_initIcon: function () {
		var options = this.options,
		    map = this._map,
		    animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
		    classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';

		var icon = options.icon.createIcon(this._icon),
			addIcon = false;

		// if we're not reusing the icon, remove the old one and init new one
		if (icon !== this._icon) {
			if (this._icon) {
				this._removeIcon();
			}
			addIcon = true;

			if (options.title) {
				icon.title = options.title;
			}
		}

		L.DomUtil.addClass(icon, classToAdd);

		if (options.keyboard) {
			icon.tabIndex = '0';
		}

		this._icon = icon;

		this._initInteraction();

		if (options.riseOnHover) {
			L.DomEvent
				.on(icon, 'mouseover', this._bringToFront, this)
				.on(icon, 'mouseout', this._resetZIndex, this);
		}

		var newShadow = options.icon.createShadow(this._shadow),
			addShadow = false;

		if (newShadow !== this._shadow) {
			this._removeShadow();
			addShadow = true;

			if (newShadow) {
				L.DomUtil.addClass(newShadow, classToAdd);
			}
		}
		this._shadow = newShadow;

		if (options.opacity < 1) {
			this._updateOpacity();
		}

		var panes = this._map._panes;

		if (addIcon) {
			panes.markerPane.appendChild(this._icon);
		}

		if (newShadow && addShadow) {
			panes.shadowPane.appendChild(this._shadow);
		}
	},

	_removeIcon: function () {
		if (this.options.riseOnHover) {
			L.DomEvent
			    .off(this._icon, 'mouseover', this._bringToFront)
			    .off(this._icon, 'mouseout', this._resetZIndex);
		}

		this._map._panes.markerPane.removeChild(this._icon);

		this._icon = null;
	},

	_removeShadow: function () {
		if (this._shadow) {
			this._map._panes.shadowPane.removeChild(this._shadow);
		}
		this._shadow = null;
	},

	_setPos: function (pos) {
		L.DomUtil.setPosition(this._icon, pos);

		if (this._shadow) {
			L.DomUtil.setPosition(this._shadow, pos);
		}

		this._zIndex = pos.y + this.options.zIndexOffset;

		this._resetZIndex();
	},

	_updateZIndex: function (offset) {
		this._icon.style.zIndex = this._zIndex + offset;
	},

	_animateZoom: function (opt) {
		var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);

		this._setPos(pos);
	},

	_initInteraction: function () {

		if (!this.options.clickable) { return; }

		// TODO refactor into something shared with Map/Path/etc. to DRY it up

		var icon = this._icon,
		    events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];

		L.DomUtil.addClass(icon, 'leaflet-clickable');
		L.DomEvent.on(icon, 'click', this._onMouseClick, this);
		L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);

		for (var i = 0; i < events.length; i++) {
			L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
		}

		if (L.Handler.MarkerDrag) {
			this.dragging = new L.Handler.MarkerDrag(this);

			if (this.options.draggable) {
				this.dragging.enable();
			}
		}
	},

	_onMouseClick: function (e) {
		var wasDragged = this.dragging && this.dragging.moved();

		if (this.hasEventListeners(e.type) || wasDragged) {
			L.DomEvent.stopPropagation(e);
		}

		if (wasDragged) { return; }

		if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }

		this.fire(e.type, {
			originalEvent: e,
			latlng: this._latlng
		});
	},

	_onKeyPress: function (e) {
		if (e.keyCode === 13) {
			this.fire('click', {
				originalEvent: e,
				latlng: this._latlng
			});
		}
	},

	_fireMouseEvent: function (e) {

		this.fire(e.type, {
			originalEvent: e,
			latlng: this._latlng
		});

		// TODO proper custom event propagation
		// this line will always be called if marker is in a FeatureGroup
		if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
			L.DomEvent.preventDefault(e);
		}
		if (e.type !== 'mousedown') {
			L.DomEvent.stopPropagation(e);
		}
	},

	setOpacity: function (opacity) {
		this.options.opacity = opacity;
		if (this._map) {
			this._updateOpacity();
		}
	},

	_updateOpacity: function () {
		L.DomUtil.setOpacity(this._icon, this.options.opacity);
		if (this._shadow) {
			L.DomUtil.setOpacity(this._shadow, this.options.opacity);
		}
	},

	_bringToFront: function () {
		this._updateZIndex(this.options.riseOffset);
	},

	_resetZIndex: function () {
		this._updateZIndex(0);
	}
});

L.marker = function (latlng, options) {
	return new L.Marker(latlng, options);
};
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');
var exec = require('child_process').exec;
var csv = require('csv');

var plotter = exec('R --no-save --interactive', {
  env: process.env,
});
var plotter_cb_queue = [];
plotter.stdin.write('repl = TRUE; source("plots.R")\n');
plotter.stdout.on('data', function (data) {
  if (data.match('--DONE--') != null)
    plotter_cb_queue.shift(0)();
  //console.log('stdout: ' + data);
});

plotter.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

var submitPlot = function (dir, expr, cb) {
  plotter_cb_queue.push(cb);
  plotter.stdin.write('setwd("' + dir + '"); ' + expr + ';\n');
}

$(function() {

//$('.btn-group').button();
/*$('#logs-othert').toggle(function() {
  console.log('toggle');
  //$('.btn-group').button('reset')
});
*/

var fill = function(name, div, opts) {
  for (var i in opts) {
    var active = i == 0 ? 'active' : '';
    div.append('' +
      '<input type="radio" name="' + name + '" value="' + opts[i] + '"> ' + opts[i] +
    '');
  }
  div.append('' +
      '<input type="radio" name="' + name + '" value="__other__">' +
      '<input type="text" name="' + name + '-other" class="form-control" placeholder="' + name + '">' +
    '');
};

fill('logs', $('#logs'), [
  'same',
  'diff',
  'diff-oldstale',
  'diff-oldminstale',
]);

fill('timing', $('#timing'), [
  'LAN',
  'WAN',
  'Delay1pct',
  'Down',
  'P1',
  'P2',
  'L1',
  'Deian',
  'BadRecv',
]);

fill('algorithm', $('#algorithm'), [
  'submission',
  'hesitant',
  'hesitant2',
  'nograntnobump',
  'stalelognobump',
  'zookeeper',
  'zookeeper2',
]);

fill('terms', $('#terms'), [
  'same',
  'diff',
]);

fill('cluster', $('#cluster'), [
  '3',
  '5',
  '7',
  '9',
  '5-2+2',
]);

var crypto = require('crypto');

var form = $('#form');
var args = $('#args', form);

form.change(function() {
  setTimeout(function() {
      form.submit();
  }, 0);
});

$('#pin').click(function() {
  $('#pinned').prepend($('#graph').clone().removeProp('id'));
});

var getArg = function(name) {
    var v = $('.active [name=' + name + ']', form).val();
    if (v == '__other__')
      v = $('[name=' + name + '-other]', form).val();
    return ' --' + name + '=' + v + ' ';
}

var zeropad = function(minlen, s) {
  while (s.length < minlen)
    s = "0" + s;
  return s;
}

form.submit(function() {
    var trace = $('#trace').val();
    var effargs = (args.val() +
                   getArg('logs') +
                   getArg('terms') +
                   getArg('timing') +
                   getArg('algorithm') +
                   getArg('cluster') +
                   '--trace ' + trace + ' ');
    console.log(effargs);

    var sha1sum = crypto.createHash('sha1');
    sha1sum.update(effargs);

    // nonce so that browser doesn't cache old graph
    // (defeats point of update(effargs), though)
    var nonce = crypto.randomBytes(8).toString();
    sha1sum.update(nonce);

    var dir = 'explore/' + sha1sum.digest('hex');
    try {
      fs.mkdirSync(dir);
    } catch (e) {
      if (e.code != "EEXIST")
        throw e;
    }

    console.log('Running ./main ' + effargs);
    var sim = exec('../../main ' + effargs, {
      cwd: dir,
      env: process.env,
    });

    sim.on('error', function (e) {
      console.log(e);
    });

    sim.stdout.on('data', function (data) {
      //console.log('stdout: ' + data);
    });

    sim.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });

    sim.on('exit', function (code) {
      console.log('sim exited with code ' + code);
      if (code != 0)
        return;

      $('#runs').html('');
      csv()
        .from.path(dir + '/samples.csv', {
          columns: true
        })
        .to.array(function (data) {
          console.log("finished reading samples.csv");
          data.forEach(function (row) {
            if (row.run >= trace)
              return;
            var link = $('')
              .prop('href', '')
              .append((row.election_time / 1e3).toFixed(0))
              .click(function() {
                fs.readFile(dir + '/trace' + zeropad(6, row.run.toString()) + '.html',
                            {encoding: 'utf8', flag: 'r'},
                            function (err, data) {
                  if (err)
                    console.log(err);
                  console.log(data);
                  $('#fulltrace').html('' + data);
                });
                submitPlot(dir, 'timeline(' + row.run + ')', function() {
                  console.log('R done');
                  $('#timeline').prop('src', dir + '/timeline' + zeropad(6, row.run.toString()) + '.svg');
                });
                return false;
              });
            $('#runs').append(link).append(' ');
          });
        })
        .transform(function(row){
          row.election_time = parseInt(row.election_time);
          row.run = parseInt(row.run);
          return row;
        });

      console.log('Running R');
      /*
      var plot = exec('Rscript ../../plots.R', {
        cwd: dir,
        env: process.env,
      });

      plot.stdout.on('data', function (data) {
        console.log('stdout: ' + data);
      });

      plot.stderr.on('data', function (data) {
        //console.log('stderr: ' + data);
      });

      plot.on('close', function (code) {
        console.log('plot exited with code ' + code);
        $('#graph').prop('src', dir + '/Rplots.svg');
      });
      */

      submitPlot(dir, 'cdf()', function() {
        console.log('R done');
        $('#graph').prop('src', dir + '/Rplots.svg');
      });
    });

    return false;
});

form.submit();

});
<commit_msg>Remove stray massive log call<commit_after>"use strict";

var fs = require('fs');
var exec = require('child_process').exec;
var csv = require('csv');

var plotter = exec('R --no-save --interactive', {
  env: process.env,
});
var plotter_cb_queue = [];
plotter.stdin.write('repl = TRUE; source("plots.R")\n');
plotter.stdout.on('data', function (data) {
  if (data.match('--DONE--') != null)
    plotter_cb_queue.shift(0)();
  //console.log('stdout: ' + data);
});

plotter.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

var submitPlot = function (dir, expr, cb) {
  plotter_cb_queue.push(cb);
  plotter.stdin.write('setwd("' + dir + '"); ' + expr + ';\n');
}

$(function() {

//$('.btn-group').button();
/*$('#logs-othert').toggle(function() {
  console.log('toggle');
  //$('.btn-group').button('reset')
});
*/

var fill = function(name, div, opts) {
  for (var i in opts) {
    var active = i == 0 ? 'active' : '';
    div.append('' +
      '<input type="radio" name="' + name + '" value="' + opts[i] + '"> ' + opts[i] +
    '');
  }
  div.append('' +
      '<input type="radio" name="' + name + '" value="__other__">' +
      '<input type="text" name="' + name + '-other" class="form-control" placeholder="' + name + '">' +
    '');
};

fill('logs', $('#logs'), [
  'same',
  'diff',
  'diff-oldstale',
  'diff-oldminstale',
]);

fill('timing', $('#timing'), [
  'LAN',
  'WAN',
  'Delay1pct',
  'Down',
  'P1',
  'P2',
  'L1',
  'Deian',
  'BadRecv',
]);

fill('algorithm', $('#algorithm'), [
  'submission',
  'hesitant',
  'hesitant2',
  'nograntnobump',
  'stalelognobump',
  'zookeeper',
  'zookeeper2',
]);

fill('terms', $('#terms'), [
  'same',
  'diff',
]);

fill('cluster', $('#cluster'), [
  '3',
  '5',
  '7',
  '9',
  '5-2+2',
]);

var crypto = require('crypto');

var form = $('#form');
var args = $('#args', form);

form.change(function() {
  setTimeout(function() {
      form.submit();
  }, 0);
});

$('#pin').click(function() {
  $('#pinned').prepend($('#graph').clone().removeProp('id'));
});

var getArg = function(name) {
    var v = $('.active [name=' + name + ']', form).val();
    if (v == '__other__')
      v = $('[name=' + name + '-other]', form).val();
    return ' --' + name + '=' + v + ' ';
}

var zeropad = function(minlen, s) {
  while (s.length < minlen)
    s = "0" + s;
  return s;
}

form.submit(function() {
    var trace = $('#trace').val();
    var effargs = (args.val() +
                   getArg('logs') +
                   getArg('terms') +
                   getArg('timing') +
                   getArg('algorithm') +
                   getArg('cluster') +
                   '--trace ' + trace + ' ');
    console.log(effargs);

    var sha1sum = crypto.createHash('sha1');
    sha1sum.update(effargs);

    // nonce so that browser doesn't cache old graph
    // (defeats point of update(effargs), though)
    var nonce = crypto.randomBytes(8).toString();
    sha1sum.update(nonce);

    var dir = 'explore/' + sha1sum.digest('hex');
    try {
      fs.mkdirSync(dir);
    } catch (e) {
      if (e.code != "EEXIST")
        throw e;
    }

    console.log('Running ./main ' + effargs);
    var sim = exec('../../main ' + effargs, {
      cwd: dir,
      env: process.env,
    });

    sim.on('error', function (e) {
      console.log(e);
    });

    sim.stdout.on('data', function (data) {
      //console.log('stdout: ' + data);
    });

    sim.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });

    sim.on('exit', function (code) {
      console.log('sim exited with code ' + code);
      if (code != 0)
        return;

      $('#runs').html('');
      csv()
        .from.path(dir + '/samples.csv', {
          columns: true
        })
        .to.array(function (data) {
          console.log("finished reading samples.csv");
          data.forEach(function (row) {
            if (row.run >= trace)
              return;
            var link = $('')
              .prop('href', '')
              .append((row.election_time / 1e3).toFixed(0))
              .click(function() {
                fs.readFile(dir + '/trace' + zeropad(6, row.run.toString()) + '.html',
                            {encoding: 'utf8', flag: 'r'},
                            function (err, data) {
                  if (err)
                    console.log(err);
                  $('#fulltrace').html('' + data);
                });
                submitPlot(dir, 'timeline(' + row.run + ')', function() {
                  console.log('R done');
                  $('#timeline').prop('src', dir + '/timeline' + zeropad(6, row.run.toString()) + '.svg');
                });
                return false;
              });
            $('#runs').append(link).append(' ');
          });
        })
        .transform(function(row){
          row.election_time = parseInt(row.election_time);
          row.run = parseInt(row.run);
          return row;
        });

      console.log('Running R');
      /*
      var plot = exec('Rscript ../../plots.R', {
        cwd: dir,
        env: process.env,
      });

      plot.stdout.on('data', function (data) {
        console.log('stdout: ' + data);
      });

      plot.stderr.on('data', function (data) {
        //console.log('stderr: ' + data);
      });

      plot.on('close', function (code) {
        console.log('plot exited with code ' + code);
        $('#graph').prop('src', dir + '/Rplots.svg');
      });
      */

      submitPlot(dir, 'cdf()', function() {
        console.log('R done');
        $('#graph').prop('src', dir + '/Rplots.svg');
      });
    });

    return false;
});

form.submit();

});
<|endoftext|>