<commit_before>/* globals plupload */
import Ember from "ember";
import File from "./file";
import trim from "./trim";

var get = Ember.get;
var set = Ember.set;
var bool = Ember.computed.bool;
var bind = Ember.run.bind;

var summation = function (target, key) {
  return target.reduce(function (E, obj) {
    return E + get(obj, key);
  }, 0);
};

/**

  @namespace ember-plupload
  @class UploadQueue
  @extend Ember.ArrayProxy
 */
export default Ember.ArrayProxy.extend({

  name: null,

  uploading: bool('length'),

  queues: null,

  init: function () {
    set(this, 'queues', Ember.A([]));
    set(this, 'orphanedQueues', Ember.A([]));

    set(this, 'content', Ember.A([]));
    this._super();
  },

  configure: function (config) {
    var uploader = new plupload.Uploader(config);

    uploader.bind('FilesAdded',     bind(this, 'filesAdded'));
    uploader.bind('FilesRemoved',   bind(this, 'filesRemoved'));
    uploader.bind('BeforeUpload',   bind(this, 'progressDidChange'));
    uploader.bind('UploadProgress', bind(this, 'progressDidChange'));
    uploader.bind('FileUploaded',   bind(this, 'fileUploaded'));
    uploader.bind('UploadComplete', bind(this, 'uploadComplete'));
    uploader.bind('Error',          bind(this, 'onError'));

    get(this, 'queues').pushObject(uploader);

    uploader.init();
    return uploader;
  },

  /**
    Orphan the active plupload object so
    we garbage collect the queues.
   */
  orphan: function () {
    var orphans = get(this, 'orphanedQueues');
    var activeQueues = get(this, 'queues').filter(function (queue) {
      return orphans.indexOf(queue) === -1;
    });
    var queue = get(Ember.A(activeQueues), 'lastObject');
    if (get(queue, 'total.queued') > 0) {
      orphans.pushObject(queue);
    } else {
      this.garbageCollectUploader(queue);
    }
  },

  destroy: function () {
    this._super();
    get(this, 'queues').invoke('unbindAll');
    set(this, 'content', Ember.A([]));
    set(this, 'queues', null);
  },

  progress: Ember.computed(function () {
    var queues        = get(this, 'queues'),
        totalSize     = summation(queues, 'total.size'),
        totalUploaded = summation(queues, 'total.loaded'),
        percent       = totalUploaded / totalSize || 0;

    return Math.floor(percent * 100);
  }),

  filesAdded: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = File.create({
        uploader: uploader,
        file: files[i]
      });

      this.pushObject(file);
      get(this, 'target').sendAction('when-queued', file, {
        name: get(this, 'name'),
        uploader: uploader,
        queue: this
      });
    }
  },

  filesRemoved: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = this.findProperty('id', files[i].id);
      if (file) {
        this.removeObject(file);
      }
    }
  },

  progressDidChange: function (uploader, file) {
    file = this.findProperty('id', file.id);
    if (file) {
      file.notifyPropertyChange('progress');
    }

    this.notifyPropertyChange('progress');
  },

  parseResponse: function (response) {
    var body = trim(response.response);
    var rawHeaders = Ember.A(response.responseHeaders.split('\n')).without('');
    var headers = rawHeaders.reduce(function (headers, header) {
      var parts = header.split(/^([A-Za-z_-]*:)/);
      if(parts.length > 0){
        headers[parts[1].slice(0, -1)] = trim(parts[2]);
      }
      return headers;
    }, {});

    var contentType = (headers['Content-Type'] || '').split(';');
    // Parse body according to the Content-Type received by the server
    if (contentType.indexOf('text/html') !== -1) {
      body = Ember.$.parseHTML(body);
    } else if (contentType.indexOf('text/xml') !== -1) {
      body = Ember.$.parseXML(body);
    } else if (contentType.indexOf('application/json') !== -1 ||
               contentType.indexOf('text/javascript') !== -1 ||
               contentType.indexOf('application/javascript') !== -1) {
      body = Ember.$.parseJSON(body);
    }

    return {
      status: response.status,
      body: body,
      headers: headers
    };
  },

  fileUploaded: function (uploader, file, response) {
    var results = this.parseResponse(response);
    file = this.findProperty('id', file.id);
    if (file) {
      this.removeObject(file);
    }

    // NOTE: Plupload calls UploadProgress upon triggering FileUploaded,
    //       so we don't need to trigger a progress event
    if (results.status === 204 ||
        results.status === 200) {
      file._deferred.resolve(results);
    } else {
      file._deferred.reject(results);
    }
  },

  garbageCollectUploader: function (uploader) {
    get(this, 'queues').removeObject(uploader);
    get(this, 'orphanedQueues').removeObject(uploader);
    this.filterProperty('uploader', uploader).invoke('destroy');
    uploader.unbindAll();
  },

  uploadComplete: function (uploader) {
    // Clean up the orphaned uploader and it's files
    if (get(this, 'orphanedQueues').indexOf(uploader) !== -1) {
      this.garbageCollectUploader(uploader);
    }
  },

  onError: function (uploader, error) {
    if (error.file) {
      var file = this.findProperty('id', error.file.id);
      set(file, 'error', error.file);
    } else {
      set(this, 'error', error);
    }
  }
});
<commit_msg>Manage both carriage returns<commit_after>/* globals plupload */
import Ember from "ember";
import File from "./file";
import trim from "./trim";

var get = Ember.get;
var set = Ember.set;
var bool = Ember.computed.bool;
var bind = Ember.run.bind;

var summation = function (target, key) {
  return target.reduce(function (E, obj) {
    return E + get(obj, key);
  }, 0);
};

/**

  @namespace ember-plupload
  @class UploadQueue
  @extend Ember.ArrayProxy
 */
export default Ember.ArrayProxy.extend({

  name: null,

  uploading: bool('length'),

  queues: null,

  init: function () {
    set(this, 'queues', Ember.A([]));
    set(this, 'orphanedQueues', Ember.A([]));

    set(this, 'content', Ember.A([]));
    this._super();
  },

  configure: function (config) {
    var uploader = new plupload.Uploader(config);

    uploader.bind('FilesAdded',     bind(this, 'filesAdded'));
    uploader.bind('FilesRemoved',   bind(this, 'filesRemoved'));
    uploader.bind('BeforeUpload',   bind(this, 'progressDidChange'));
    uploader.bind('UploadProgress', bind(this, 'progressDidChange'));
    uploader.bind('FileUploaded',   bind(this, 'fileUploaded'));
    uploader.bind('UploadComplete', bind(this, 'uploadComplete'));
    uploader.bind('Error',          bind(this, 'onError'));

    get(this, 'queues').pushObject(uploader);

    uploader.init();
    return uploader;
  },

  /**
    Orphan the active plupload object so
    we garbage collect the queues.
   */
  orphan: function () {
    var orphans = get(this, 'orphanedQueues');
    var activeQueues = get(this, 'queues').filter(function (queue) {
      return orphans.indexOf(queue) === -1;
    });
    var queue = get(Ember.A(activeQueues), 'lastObject');
    if (get(queue, 'total.queued') > 0) {
      orphans.pushObject(queue);
    } else {
      this.garbageCollectUploader(queue);
    }
  },

  destroy: function () {
    this._super();
    get(this, 'queues').invoke('unbindAll');
    set(this, 'content', Ember.A([]));
    set(this, 'queues', null);
  },

  progress: Ember.computed(function () {
    var queues        = get(this, 'queues'),
        totalSize     = summation(queues, 'total.size'),
        totalUploaded = summation(queues, 'total.loaded'),
        percent       = totalUploaded / totalSize || 0;

    return Math.floor(percent * 100);
  }),

  filesAdded: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = File.create({
        uploader: uploader,
        file: files[i]
      });

      this.pushObject(file);
      get(this, 'target').sendAction('when-queued', file, {
        name: get(this, 'name'),
        uploader: uploader,
        queue: this
      });
    }
  },

  filesRemoved: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = this.findProperty('id', files[i].id);
      if (file) {
        this.removeObject(file);
      }
    }
  },

  progressDidChange: function (uploader, file) {
    file = this.findProperty('id', file.id);
    if (file) {
      file.notifyPropertyChange('progress');
    }

    this.notifyPropertyChange('progress');
  },

  parseResponse: function (response) {
    var body = trim(response.response);
    var rawHeaders = Ember.A(response.responseHeaders.split(/\\n|\\r/)).without('');
    var headers = rawHeaders.reduce(function (headers, header) {
      var parts = header.split(/^([A-Za-z_-]*:)/);
      if(parts.length > 0){
        headers[parts[1].slice(0, -1)] = trim(parts[2]);
      }
      return headers;
    }, {});

    var contentType = (headers['Content-Type'] || '').split(';');
    // Parse body according to the Content-Type received by the server
    if (contentType.indexOf('text/html') !== -1) {
      body = Ember.$.parseHTML(body);
    } else if (contentType.indexOf('text/xml') !== -1) {
      body = Ember.$.parseXML(body);
    } else if (contentType.indexOf('application/json') !== -1 ||
               contentType.indexOf('text/javascript') !== -1 ||
               contentType.indexOf('application/javascript') !== -1) {
      body = Ember.$.parseJSON(body);
    }

    return {
      status: response.status,
      body: body,
      headers: headers
    };
  },

  fileUploaded: function (uploader, file, response) {
    var results = this.parseResponse(response);
    file = this.findProperty('id', file.id);
    if (file) {
      this.removeObject(file);
    }

    // NOTE: Plupload calls UploadProgress upon triggering FileUploaded,
    //       so we don't need to trigger a progress event
    if (results.status === 204 ||
        results.status === 200) {
      file._deferred.resolve(results);
    } else {
      file._deferred.reject(results);
    }
  },

  garbageCollectUploader: function (uploader) {
    get(this, 'queues').removeObject(uploader);
    get(this, 'orphanedQueues').removeObject(uploader);
    this.filterProperty('uploader', uploader).invoke('destroy');
    uploader.unbindAll();
  },

  uploadComplete: function (uploader) {
    // Clean up the orphaned uploader and it's files
    if (get(this, 'orphanedQueues').indexOf(uploader) !== -1) {
      this.garbageCollectUploader(uploader);
    }
  },

  onError: function (uploader, error) {
    if (error.file) {
      var file = this.findProperty('id', error.file.id);
      set(file, 'error', error.file);
    } else {
      set(this, 'error', error);
    }
  }
});
<|endoftext|>


<commit_before>/*
 * moleculer
 * Copyright (c) 2018 MoleculerJS (https://github.com/moleculerjs/moleculer)
 * MIT Licensed
 */

"use strict";

const chalk 	= require("chalk");
const _ 		= require("lodash");
const util 		= require("util");

const LOG_LEVELS = ["fatal", "error", "warn", "info", "debug", "trace"];

module.exports = {

	/**
	 * Extend a logger class if missing log level methods
	 *
	 * @param {Object} logger
	 * @returns {Object} logger
	 */
	extend(logger) {
		LOG_LEVELS.forEach(type => {
			let method = logger[type];
			if (!method) {
				switch(type) {
					case "fatal":method = logger["error"] || logger["info"]; break;
					case "trace": method = logger["debug"] || logger["info"]; break;
					default: method = logger["info"];
				}
				logger[type] = method.bind(logger);
			}
		});
		return logger;
	},

	/**
	 * Create a default logger for `console` logger.
	 *
	 * @param {Object} baseLogger
	 * @param {Object} bindings
	 * @param {String?} logLevel
	 * @param {Function?} logFormatter Custom log formatter function
	 * @returns {Object} logger
	 */
	createDefaultLogger(baseLogger, bindings, logLevel, logFormatter) {
		const noop = function() {};

		const getModuleName = () => {
			let mod;
			if (bindings.svc) {
				mod = bindings.svc.toUpperCase();
				if (bindings.ver) {
					mod += ":" + (typeof(bindings.ver) == "number" ? "v" + bindings.ver : bindings.ver);
				}
			} else if (bindings.mod)
				mod = bindings.mod.toUpperCase();

			return bindings.nodeID + "/" + mod;
		};

		const getColor = type => {
			switch(type) {
				case "fatal": return chalk.red.inverse;
				case "error": return chalk.red;
				case "warn": return chalk.yellow;
				case "debug": return chalk.magenta;
				case "trace": return chalk.gray;
				default: return chalk.green;
			}
		};
		const getType = type => getColor(type)(_.padEnd(type.toUpperCase(), 5));

		let logger = {};
		LOG_LEVELS.forEach((type, i) => {
			if (!baseLogger || (logLevel && i > LOG_LEVELS.indexOf(logLevel))) {
				logger[type] = noop;
				return;
			}

			let method = baseLogger[type];

			/* istanbul ignore next */
			if (baseLogger === console && process.versions.node.split(".")[0] >= 8 && type === "debug")
				method = null;

			if (!method) {
				switch(type) {
					case "fatal":method = baseLogger["error"] || baseLogger["info"]; break;
					case "trace": method = baseLogger["debug"] || baseLogger["info"]; break;
					default: method = baseLogger["info"];
				}
			}

			// Wrap the original method
			logger[type] = function(...args) {
				const format = logFormatter;
				if (_.isFunction(format))
					return method.call(baseLogger, logFormatter(type, args, bindings));

				// Format arguments (inspect & colorize the objects & array)
				let pargs = args.map(p => {
					if (_.isObject(p) || _.isArray(p))
						return util.inspect(p, { showHidden: false, depth: 2, colors: chalk.enabled });
					return p;
				});

				if (format == "simple") {
					method.call(baseLogger, getType(type), "-", ...pargs);
				} else {
					method.call(baseLogger, chalk.grey(`[${new Date().toISOString()}]`), getType(type), chalk.grey(getModuleName() + ":"), ...pargs);
				}

			}.bind(baseLogger);

		});

		return logger;
	}

};
<commit_msg>fixes big objects logging<commit_after>/*
 * moleculer
 * Copyright (c) 2018 MoleculerJS (https://github.com/moleculerjs/moleculer)
 * MIT Licensed
 */

"use strict";

const chalk 	= require("chalk");
const _ 		= require("lodash");
const util 		= require("util");

const LOG_LEVELS = ["fatal", "error", "warn", "info", "debug", "trace"];

module.exports = {

	/**
	 * Extend a logger class if missing log level methods
	 *
	 * @param {Object} logger
	 * @returns {Object} logger
	 */
	extend(logger) {
		LOG_LEVELS.forEach(type => {
			let method = logger[type];
			if (!method) {
				switch(type) {
					case "fatal":method = logger["error"] || logger["info"]; break;
					case "trace": method = logger["debug"] || logger["info"]; break;
					default: method = logger["info"];
				}
				logger[type] = method.bind(logger);
			}
		});
		return logger;
	},

	/**
	 * Create a default logger for `console` logger.
	 *
	 * @param {Object} baseLogger
	 * @param {Object} bindings
	 * @param {String?} logLevel
	 * @param {Function?} logFormatter Custom log formatter function
	 * @returns {Object} logger
	 */
	createDefaultLogger(baseLogger, bindings, logLevel, logFormatter) {
		const noop = function() {};

		const getModuleName = () => {
			let mod;
			if (bindings.svc) {
				mod = bindings.svc.toUpperCase();
				if (bindings.ver) {
					mod += ":" + (typeof(bindings.ver) == "number" ? "v" + bindings.ver : bindings.ver);
				}
			} else if (bindings.mod)
				mod = bindings.mod.toUpperCase();

			return bindings.nodeID + "/" + mod;
		};

		const getColor = type => {
			switch(type) {
				case "fatal": return chalk.red.inverse;
				case "error": return chalk.red;
				case "warn": return chalk.yellow;
				case "debug": return chalk.magenta;
				case "trace": return chalk.gray;
				default: return chalk.green;
			}
		};
		const getType = type => getColor(type)(_.padEnd(type.toUpperCase(), 5));

		let logger = {};
		LOG_LEVELS.forEach((type, i) => {
			if (!baseLogger || (logLevel && i > LOG_LEVELS.indexOf(logLevel))) {
				logger[type] = noop;
				return;
			}

			let method = baseLogger[type];

			/* istanbul ignore next */
			if (baseLogger === console && process.versions.node.split(".")[0] >= 8 && type === "debug")
				method = null;

			if (!method) {
				switch(type) {
					case "fatal":method = baseLogger["error"] || baseLogger["info"]; break;
					case "trace": method = baseLogger["debug"] || baseLogger["info"]; break;
					default: method = baseLogger["info"];
				}
			}

			// Wrap the original method
			logger[type] = function(...args) {
				const format = logFormatter;
				if (_.isFunction(format))
					return method.call(baseLogger, logFormatter(type, args, bindings));

				// Format arguments (inspect & colorize the objects & array)
				let pargs = args.map(p => {
					if (_.isObject(p) || _.isArray(p))
						return util.inspect(p, { showHidden: false, depth: 2, colors: chalk.enabled, breakLength: Number.POSITIVE_INFINITY });
					return p;
				});

				if (format == "simple") {
					method.call(baseLogger, getType(type), "-", ...pargs);
				} else {
					method.call(baseLogger, chalk.grey(`[${new Date().toISOString()}]`), getType(type), chalk.grey(getModuleName() + ":"), ...pargs);
				}

			}.bind(baseLogger);

		});

		return logger;
	}

};
<|endoftext|>


<commit_before>import React from 'react';

const friday = [{
    start: '6:00 PM',
    name: 'Check in begins 📋',
    info: 'Loeb Playhouse'
},{
    start: '8:00 PM',
    name: 'Opening Ceremonies 🎤',
    info: 'Loeb Playhouse'
},{
    start: '9:00 PM',
    name: 'Team assembly 🤝',
    info: 'CoRec Black & Gold Gyms'
},{
    start: '9:30 PM',
    name: 'Dinner from Moe\'s 🌮',
    info: 'taco bar (yes there\'s  queso)'
},{
    start: '10:00 PM',
    name: 'Hacking Begins 💻'
},{
    start: '10:00 PM',
    name: 'Workshop/talk 1',
    info: 'CoRec 2265'
},{
    start: '11:59 PM',
    name: 'Showers close 🚿'
}];

let saturday = [{
    start: '3:00 AM',
    name: 'Late Night Snack'
},{
    start: '8:00 AM',
    name: 'Breakfast 🥓',
    info: 'eggs, potatoes, bacon, fruit, bagels'
},{
    start: '8:00 AM',
    name: 'Showers reopen 🚿'
},{
    start: '9:00 AM',
    name: 'Workshop/talk 2: TBD',
    info: 'CoRec 2265'
},{
    start: '10:00 AM',
    name: 'A Peek into the Decentralized Future with Blockchains',
    info: 'CoRec 2265'
},{
    start: '11:30 AM',
    name: 'Yoga'
},{
    start: '12:30 PM',
    name: 'Lunch - Pasta Bar 🍝',
    info: 'chicken, marinara, alfredo, veggies, salad, rolls'
},{
    start: '1:00 PM',
    name: 'Workshop/talk 4',
    info: 'CoRec 2265'
},{
    start: '1:00 PM',
    name: 'Snack'
},{
    start: '1:30 PM',
    name: 'Yoga'
},{
    start: '3:00 PM',
    name: 'The New Frontiers in Systems Level Data Sciences and Human Space Exploration',
    info: 'CoRec 2265'
},{
    start: '4:30 PM',
    name: 'MLH Cup Stacking'
},{
    start: '6:00 PM',
    name: 'Dinner from Hotbox 🍕',
    info: 'pizza, breadsticks, salad'
},{
    start: '6:00 PM',
    name: 'Workshop/talk 6',
    info: 'CoRec 2265'
},{
    start: '10:00 PM',
    name: 'Donuts! 🍩 '
},{
    start: '11:59 PM',
    name: 'Showers close🚿'
}];

let sunday = [{
    start: '1:00 AM',
    name: 'Late Night Snack'
},{
    start: '8:00 AM',
    name: 'Breakfast 🍳',
    info: 'egg casseroles, potatoes, fruit, yogurt, bagels, pastries'
},{
    start: '9:30 AM',
    name: 'Hacking Ends 🛑'
},{
    start: '10:00 AM',
    name: 'Expo Begins'
},{
    start: '10:00 AM',
    name: 'Showers reopen 🚿'
},{
    start: '11:30 AM',
    name: 'Lunch from Potbelly 🍞',
    info: 'sandwiches'
},{
    start: '1:00 PM',
    name: 'Closing Ceremonies',
    info: 'Loeb Playhouse'
},{
    start: '2:30 PM',
    name: 'Buses Depart 🚌',
    info: 'Loeb Playhouse'
}];

const ScheduleDay =  ({dayData, title}) =>

{title}

        { dayData.map(item =>

{item.start}

{item.name}
{item.info}

        )}

;

const Schedule = () => (

Schedule

      <ScheduleDay dayData={friday} title="Friday (9/29)"/>
      <ScheduleDay dayData={saturday} title="Saturday (9/30)"/>
      <ScheduleDay dayData={sunday} title="Sunday (10/1)"/>

);

export default Schedule;
<commit_msg>remove placeholder tech talks from schedule<commit_after>import React from 'react';

const friday = [{
    start: '6:00 PM',
    name: 'Check in begins 📋',
    info: 'Loeb Playhouse'
},{
    start: '8:00 PM',
    name: 'Opening Ceremonies 🎤',
    info: 'Loeb Playhouse'
},{
    start: '9:00 PM',
    name: 'Team assembly 🤝',
    info: 'CoRec Black & Gold Gyms'
},{
    start: '9:30 PM',
    name: 'Dinner from Moe\'s 🌮',
    info: 'taco bar (yes there\'s  queso)'
},{
    start: '10:00 PM',
    name: 'Hacking Begins 💻'
},{
    start: '11:59 PM',
    name: 'Showers close 🚿'
}];

let saturday = [{
    start: '3:00 AM',
    name: 'Late Night Snack'
},{
    start: '8:00 AM',
    name: 'Breakfast 🥓',
    info: 'eggs, potatoes, bacon, fruit, bagels'
},{
    start: '8:00 AM',
    name: 'Showers reopen 🚿'
},{
    start: '10:00 AM',
    name: 'A Peek into the Decentralized Future with Blockchains',
    info: 'CoRec 2265'
},{
    start: '11:30 AM',
    name: 'Yoga'
},{
    start: '12:30 PM',
    name: 'Lunch - Pasta Bar 🍝',
    info: 'chicken, marinara, alfredo, veggies, salad, rolls'
},{
    start: '1:00 PM',
    name: 'Snack'
},{
    start: '1:30 PM',
    name: 'Yoga'
},{
    start: '3:00 PM',
    name: 'The New Frontiers in Systems Level Data Sciences and Human Space Exploration',
    info: 'CoRec 2265'
},{
    start: '4:30 PM',
    name: 'MLH Cup Stacking'
},{
    start: '6:00 PM',
    name: 'Dinner from Hotbox 🍕',
    info: 'pizza, breadsticks, salad'
},{
    start: '10:00 PM',
    name: 'Donuts! 🍩 '
},{
    start: '11:59 PM',
    name: 'Showers close🚿'
}];

let sunday = [{
    start: '1:00 AM',
    name: 'Late Night Snack'
},{
    start: '8:00 AM',
    name: 'Breakfast 🍳',
    info: 'egg casseroles, potatoes, fruit, yogurt, bagels, pastries'
},{
    start: '9:30 AM',
    name: 'Hacking Ends 🛑'
},{
    start: '10:00 AM',
    name: 'Expo Begins'
},{
    start: '10:00 AM',
    name: 'Showers reopen 🚿'
},{
    start: '11:30 AM',
    name: 'Lunch from Potbelly 🍞',
    info: 'sandwiches'
},{
    start: '1:00 PM',
    name: 'Closing Ceremonies',
    info: 'Loeb Playhouse'
},{
    start: '2:30 PM',
    name: 'Buses Depart 🚌',
    info: 'Loeb Playhouse'
}];

const ScheduleDay =  ({dayData, title}) =>

{title}

        { dayData.map(item =>

{item.start}

{item.name}
{item.info}

        )}

;

const Schedule = () => (

Schedule

      <ScheduleDay dayData={friday} title="Friday (9/29)"/>
      <ScheduleDay dayData={saturday} title="Saturday (9/30)"/>
      <ScheduleDay dayData={sunday} title="Sunday (10/1)"/>

);

export default Schedule;
<|endoftext|>


<commit_before>angular.module('NutrifApp').controller('listarFuncionariosCtrl', function ($scope, $mdToast, funcionarioService) {

    $scope.funcionarios = [];

    $scope.getAll = function (){
    	funcionarioService.getAll()
    	.success(onSuccessCallback)
		.error(onErrorCallback);
    };

    function onSuccessCallback(data, status) {
        $scope.funcionarios = data;
    }

    function onErrorCallback(data, status) {
        var _message = '';

        if (!data) {
            _message = 'Não foram encontrados funcionários com esses dados'
        } else {
            _message = data.mensagem
        }

        $mdToast.show(
            $mdToast.simple()
            .textContent(_message)
            .position('top right')
            .action('OK')
            .hideDelay(6000)
        );
    }

    $scope.query = {
        order: 'nome',
        limit: 8,
        page: 1
    };

});
<commit_msg>- Updates<commit_after>angular.module('NutrifApp').controller('listarFuncionariosCtrl', function ($scope, $mdToast, funcionarioService) {

    $scope.funcionarios = [];

    $scope.getAll = function (){
    	funcionarioService.getAll()
    	.success(onSuccessCallback)
		.error(onErrorCallback);
    };

    function onSuccessCallback(data, status) {
        $scope.funcionarios = data;
    }

    function onErrorCallback(data, status) {
        var _message = '';

        if (!data) {
            _message = 'Nenhum funcionário cadastrado'
        } else {
            _message = data.mensagem
        }

        $mdToast.show(
            $mdToast.simple()
            .textContent(_message)
            .position('top right')
            .action('OK')
            .hideDelay(6000)
        );
    }

    $scope.query = {
        order: 'nome',
        limit: 8,
        page: 1
    };

});
<|endoftext|>


<commit_before>export const RECEIVE_ONBOARDING_ALERT = 'RECEIVE_ONBOARDING_ALERT';<commit_msg>Minor JavaScript fix for linter<commit_after>export const RECEIVE_ONBOARDING_ALERT = 'RECEIVE_ONBOARDING_ALERT';
<|endoftext|>


<commit_before>recommended_friends = [];
var spinner;

function diff(array1, array2) {
  var a1 = $.map(array1, function(item) {return item.uid;});
  var a2 = $.map(array2, function(item) {return item.uid;});
  var uids = a1.filter(function(i) {
    return a2.indexOf(i) < 0;
  });
  return array1.filter(function(i) { return uids.indexOf(i.uid) >= 0; });
}

function createSpinner() {
  var opts = {
    lines: 13, // The number of lines to draw
    length: 7, // The length of each line
    width: 4, // The line thickness
    radius: 10, // The radius of the inner circle
    corners: 1, // Corner roundness (0..1)
    rotate: 0, // The rotation offset
    color: '#000', // #rgb or #rrggbb
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 2e9, // The z-index (defaults to 2000000000)
    top: 'auto', // Top position relative to parent in px
    left: 'auto' // Left position relative to parent in px
  };
  var target = $('#facebookFriendsModal .modal-body').get(0);
  return new Spinner(opts).spin(target);
}

function buildMultiFriendSelector() {
  $(recommended_friends).each(function(index, item) {
    var checked = item.preselect ? 'checked' : '';
    var friend = $(
      '
'+
        '<input type="checkbox" '+checked+' value="'+item.uid+'"/>'+
        '
'+item.name+'
'+
      '
'
    );
    var id = '#' + item.type;
    $('.facebook_friend_widget ' + id + ' .friend_list').append(friend);
    $(id).removeClass('hide');
  });
}

function postToMeAndFriends() {
  var domain = location.href.replace(/\?.*/,"");
  var memberHash = $.cookie('member_id');
  var url = [domain, '?recommend_ref=', memberHash].join('');
  var message = $('#message-to-friends').val();

  var friends = (function() {
    return $('.friend_lists input[type="checkbox"]').filter(function(i) {
      return $(this).attr('checked');
    }).map(function() {
      return $(this).val();
    });
  })().toArray().concat(['me']);

  (function send(i) {
    if(!(uid = friends[i])) { return; }
    FB.api('/'+uid+'/feed', 'post', {link: url, message: message}, function(res){
      send(i+1);
    });
  })(0);

  $('#facebookFriendsModal').modal('toggle');
}

function findRecommendedFriends(groups) {
  var tier1 = diff(groups.friends_notifying, groups.friends_involved);
  var friends_not_involved = diff(groups.friends, groups.friends_involved);
  var tier2 = diff(friends_not_involved, tier1);
  var tier3 = diff(groups.friends, tier1.concat(tier2));
  var suggested = tier1.concat(tier2);
  remaining = suggested.slice(25);
  suggested = suggested.slice(0, 25);
  remaining = remaining.concat(tier3);

  recommended_friends = $.map(suggested, function(friend) {
    return {uid: friend.uid, name: friend.name, type: 'suggested', preselect: true};
  });

  $(remaining).each(function(index, friend){
    recommended_friends.push({uid: friend.uid, name: friend.name, type: 'other', preselect: false});
  });

  buildMultiFriendSelector();
  spinner.stop();
  $('.btn-success').click(postToMeAndFriends);
}

function queryFacebook(query, groups) {
  FB.api("/fql?q=" +  encodeURIComponent(JSON.stringify(query)),
  function(response) {
      $(response.data).each(function(index, object) {
        var name = object.name;
        var resultSet = object.fql_result_set;
        $(resultSet).each(function(i, friend) {
          if(!groups[name]) { return; }
          groups[name].push(friend);
        });
      });

      findRecommendedFriends(groups);
    }
  );
}

function getFriendsWithAppInstalled() {
  spinner = createSpinner();

  var groups = {
    friends_notifying: [],
    friends_involved: [],
    friends: []
  };

  var query = {
    "friend_ids":"select uid2 from friend where uid1 = me()",
    "friends_notifying":"select name, uid from user where uid "+
      "in (select sender_id from notification where recipient_id = me()) "+
      "order by profile_update_time desc",
    "friends_involved":"select name, uid from user where uid in "+
      "(select user_id from url_like where user_id in (select uid2 from #friend_ids) "+
      "and strpos(url, 'watchdog.net') > 0) order by profile_update_time desc",
    "friends":"select name, uid from user where uid in (select uid2 from #friend_ids) "+
      "order by profile_update_time desc"
  };

  queryFacebook(query, groups);
}

function submitAppRequest() {
  $("#thanksModal").modal('hide');
  FB.login(function (response) {
    if (response.authResponse) {
      $('#facebookFriendsModal').modal('toggle');
      if(recommended_friends.length === 0) { getFriendsWithAppInstalled(); }
      setupSocialTrackingControllerRequest('recommend');
     }
  }, {scope: 'publish_actions, manage_notifications, publish_stream'});
}

function bindFacebookRecommendationButton() {
  $('.fb_recommend_btn').click(submitAppRequest);
}
<commit_msg>removes manage_notifications<commit_after>recommended_friends = [];
var spinner;

function diff(array1, array2) {
  var a1 = $.map(array1, function(item) {return item.uid;});
  var a2 = $.map(array2, function(item) {return item.uid;});
  var uids = a1.filter(function(i) {
    return a2.indexOf(i) < 0;
  });
  return array1.filter(function(i) { return uids.indexOf(i.uid) >= 0; });
}

function createSpinner() {
  var opts = {
    lines: 13, // The number of lines to draw
    length: 7, // The length of each line
    width: 4, // The line thickness
    radius: 10, // The radius of the inner circle
    corners: 1, // Corner roundness (0..1)
    rotate: 0, // The rotation offset
    color: '#000', // #rgb or #rrggbb
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 2e9, // The z-index (defaults to 2000000000)
    top: 'auto', // Top position relative to parent in px
    left: 'auto' // Left position relative to parent in px
  };
  var target = $('#facebookFriendsModal .modal-body').get(0);
  return new Spinner(opts).spin(target);
}

function buildMultiFriendSelector() {
  $(recommended_friends).each(function(index, item) {
    var checked = item.preselect ? 'checked' : '';
    var friend = $(
      '
'+
        '<input type="checkbox" '+checked+' value="'+item.uid+'"/>'+
        '
'+item.name+'
'+
      '
'
    );
    var id = '#' + item.type;
    $('.facebook_friend_widget ' + id + ' .friend_list').append(friend);
    $(id).removeClass('hide');
  });
}

function postToMeAndFriends() {
  var domain = location.href.replace(/\?.*/,"");
  var memberHash = $.cookie('member_id');
  var url = [domain, '?recommend_ref=', memberHash].join('');
  var message = $('#message-to-friends').val();

  var friends = (function() {
    return $('.friend_lists input[type="checkbox"]').filter(function(i) {
      return $(this).attr('checked');
    }).map(function() {
      return $(this).val();
    });
  })().toArray().concat(['me']);

  (function send(i) {
    if(!(uid = friends[i])) { return; }
    FB.api('/'+uid+'/feed', 'post', {link: url, message: message}, function(res){
      send(i+1);
    });
  })(0);

  $('#facebookFriendsModal').modal('toggle');
}

function findRecommendedFriends(groups) {
  var tier1 = diff(groups.friends_notifying, groups.friends_involved);
  var friends_not_involved = diff(groups.friends, groups.friends_involved);
  var tier2 = diff(friends_not_involved, tier1);
  var tier3 = diff(groups.friends, tier1.concat(tier2));
  var suggested = tier1.concat(tier2);
  remaining = suggested.slice(25);
  suggested = suggested.slice(0, 25);
  remaining = remaining.concat(tier3);

  recommended_friends = $.map(suggested, function(friend) {
    return {uid: friend.uid, name: friend.name, type: 'suggested', preselect: true};
  });

  $(remaining).each(function(index, friend){
    recommended_friends.push({uid: friend.uid, name: friend.name, type: 'other', preselect: false});
  });

  buildMultiFriendSelector();
  spinner.stop();
  $('.btn-success').click(postToMeAndFriends);
}

function queryFacebook(query, groups) {
  FB.api("/fql?q=" +  encodeURIComponent(JSON.stringify(query)),
  function(response) {
      $(response.data).each(function(index, object) {
        var name = object.name;
        var resultSet = object.fql_result_set;
        $(resultSet).each(function(i, friend) {
          if(!groups[name]) { return; }
          groups[name].push(friend);
        });
      });

      findRecommendedFriends(groups);
    }
  );
}

function getFriendsWithAppInstalled() {
  spinner = createSpinner();

  var groups = {
    friends_notifying: [],
    friends_involved: [],
    friends: []
  };

  var query = {
    "friend_ids":"select uid2 from friend where uid1 = me()",
    "friends_notifying":"select name, uid from user where uid "+
      "in (select sender_id from notification where recipient_id = me()) "+
      "order by profile_update_time desc",
    "friends_involved":"select name, uid from user where uid in "+
      "(select user_id from url_like where user_id in (select uid2 from #friend_ids) "+
      "and strpos(url, 'watchdog.net') > 0) order by profile_update_time desc",
    "friends":"select name, uid from user where uid in (select uid2 from #friend_ids) "+
      "order by profile_update_time desc"
  };

  queryFacebook(query, groups);
}

function submitAppRequest() {
  $("#thanksModal").modal('hide');
  FB.login(function (response) {
    if (response.authResponse) {
      $('#facebookFriendsModal').modal('toggle');
      if(recommended_friends.length === 0) { getFriendsWithAppInstalled(); }
      setupSocialTrackingControllerRequest('recommend');
     }
  }, {scope: 'publish_actions, publish_stream'});
}

function bindFacebookRecommendationButton() {
  $('.fb_recommend_btn').click(submitAppRequest);
}
<|endoftext|>


<commit_before>/**
 * An easy way to create path instructions for arbitrary shapes.
 *
 * @author Joschi <josua.krause@gmail.com>
 */

jkjs = window.jkjs || {}; // init namespace

jkjs.Path = function() {
  this.slack = "";
  this.strs = [];
};
jkjs.Path.prototype.isEmpty = function() {
  return !this.strs.length;
};
jkjs.Path.prototype.move = function(x, y) {
  if(!this.slack.length) {
    this.slack = "M".concat(x, " ", y);
  }
  this.strs.push(" M".concat(x, " ", y));
};
jkjs.Path.prototype.line = function(x, y) {
  this.strs.push(" L".concat(x, " ", y));
};
jkjs.Path.prototype.quad = function(mx, my, x, y) {
  this.strs.push(" Q".concat(mx, " ", my, " ", x, " ", y));
};
jkjs.Path.prototype.moveBy = function(dx, dy) {
  this.strs.push(" m".concat(dx, " ", dy));
};
jkjs.Path.prototype.lineBy = function(dx, dy) {
  this.strs.push(" l".concat(dx, " ", dy));
};
jkjs.Path.prototype.quadBy = function(dmx, dmy, dx, dy) {
  this.strs.push(" q".concat(dmx, " ", dmy, " ", dx, " ", dy));
};
jkjs.Path.prototype.close = function() {
  this.strs.push(" Z");
};
jkjs.Path.prototype.pointAdder = function(size) {
  // for tight loops
  var that = this;
  var s2 = size * 0.5;
  var down  = " l0 " + size;
  var right = " l" + size + " 0";
  var up    = " l0 " + (-size);
  var left  = " l" + (-size) + " 0";
  return function(x, y) {
    that.move(x - s2, y - s2);
    that.strs.push(down, right, up, left, " Z");
  };
};
jkjs.Path.prototype.toString = function() {
  // we always have a meaningless move before the actual path
  // so transitioning from an empty path will not try to animate
  // from an arbitrary position but will emerge at the correct position
  if(!this.slack.length) {
    if(!this.strs.length) {
      return "M0 0";
    }
    console.warn("meaningless start of path", this.strs);
  }
  // this.strs.length is larger than zero
  return String.prototype.concat.apply(this.slack, this.strs);
};
jkjs.Path.prototype.add = function(path) {
  if (path.isEmpty())
    return this;
  if (this.isEmpty()) {
    this.slack = path.slack;
  }
  this.strs = this.strs.concat(path.strs);
  return this;
};
// careful when using this method -- it just reverses the order of operations
jkjs.Path.prototype.reverse = function() {
  this.strs.reverse();
  return this;
};
<commit_msg>handle many many path entries<commit_after>/**
 * An easy way to create path instructions for arbitrary shapes.
 *
 * @author Joschi <josua.krause@gmail.com>
 */

jkjs = window.jkjs || {}; // init namespace

jkjs.Path = function() {
  this.slack = "";
  this.strs = [];
};
jkjs.Path.prototype.isEmpty = function() {
  return !this.strs.length;
};
jkjs.Path.prototype.move = function(x, y) {
  if(!this.slack.length) {
    this.slack = "M".concat(x, " ", y);
  }
  this.strs.push(" M".concat(x, " ", y));
};
jkjs.Path.prototype.line = function(x, y) {
  this.strs.push(" L".concat(x, " ", y));
};
jkjs.Path.prototype.quad = function(mx, my, x, y) {
  this.strs.push(" Q".concat(mx, " ", my, " ", x, " ", y));
};
jkjs.Path.prototype.moveBy = function(dx, dy) {
  this.strs.push(" m".concat(dx, " ", dy));
};
jkjs.Path.prototype.lineBy = function(dx, dy) {
  this.strs.push(" l".concat(dx, " ", dy));
};
jkjs.Path.prototype.quadBy = function(dmx, dmy, dx, dy) {
  this.strs.push(" q".concat(dmx, " ", dmy, " ", dx, " ", dy));
};
jkjs.Path.prototype.close = function() {
  this.strs.push(" Z");
};
jkjs.Path.prototype.pointAdder = function(size) {
  // for tight loops
  var that = this;
  var s2 = size * 0.5;
  var down  = " l0 " + size;
  var right = " l" + size + " 0";
  var up    = " l0 " + (-size);
  var left  = " l" + (-size) + " 0";
  return function(x, y) {
    that.move(x - s2, y - s2);
    that.strs.push(down, right, up, left, " Z");
  };
};
jkjs.Path.prototype.toString = function() {
  // we always have a meaningless move before the actual path
  // so transitioning from an empty path will not try to animate
  // from an arbitrary position but will emerge at the correct position
  if(!this.slack.length) {
    if(!this.strs.length) {
      return "M0 0";
    }
    console.warn("meaningless start of path", this.strs);
  }
  // this.strs.length is larger than zero
  if(this.strs.length <= 100000) {
    return String.prototype.concat.apply(this.slack, this.strs);
  }
  console.warn("slow path");
  // slow concatenation for very long paths
  var res = this.slack;
  this.strs.forEach(function(s) {
    res += s;
  });
  return res;
};
jkjs.Path.prototype.add = function(path) {
  if (path.isEmpty())
    return this;
  if (this.isEmpty()) {
    this.slack = path.slack;
  }
  this.strs = this.strs.concat(path.strs);
  return this;
};
// careful when using this method -- it just reverses the order of operations
jkjs.Path.prototype.reverse = function() {
  this.strs.reverse();
  return this;
};
<|endoftext|>


<commit_before>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.CSSCrossTransform=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var ElmSelect=require("elm-select"),CrossStyle=require("cross-style");var STYLES=CrossStyle("transform");function CSSCrossTransform(elm,value){var i=0;if(typeof elm==="string"){elm=ElmSelect(elm,CSSCrossTransform,[value]);return elm[0]}for(;i<STYLES.length;++i){elm.style[styles[i]]=value}return elm}module.exports=CSSCrossTransform},{"cross-style":2,"elm-select":3}],2:[function(require,module,exports){var UFirst=require("ucfirst");function CrossStyle(input){var uInput=UFirst(input);return["webkit"+uInput,"moz"+uInput,"ms"+uInput,"o"+uInput,input]}module.exports=CrossStyle},{ucfirst:4}],3:[function(require,module,exports){function ElmSelect(elm,fn,args){var i=0;if(typeof elm==="string"){elm=document.querySelectorAll(elm)}if(elm.constructor!==NodeList){elm=[elm]}if(typeof fn==="function"){if(!Array.isArray(args)){args=[args]}args=[elm].concat(args);for(;i<elm.length;++i){fn.apply(this,args)}}return elm}module.exports=ElmSelect},{}],4:[function(require,module,exports){"use strict";module.exports=function(s){return s.substr(0,1).toUpperCase()+s.substring(1)}},{}]},{},[1])(1)});<commit_msg>Rebuild<commit_after>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.CSSCrossTransform=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var ElmSelect=require("elm-select"),CrossStyle=require("cross-style");var STYLES=CrossStyle("transform");function CSSCrossTransform(elm,value){var i=0;if(typeof elm==="string"){elm=ElmSelect(elm,CSSCrossTransform,[value]);return elm[0]}for(;i<STYLES.length;++i){elm.style[STYLES[i]]=value}return elm}module.exports=CSSCrossTransform},{"cross-style":2,"elm-select":3}],2:[function(require,module,exports){var UFirst=require("ucfirst");function CrossStyle(input){var uInput=UFirst(input);return["webkit"+uInput,"moz"+uInput,"ms"+uInput,"o"+uInput,input]}module.exports=CrossStyle},{ucfirst:4}],3:[function(require,module,exports){function ElmSelect(elm,fn,args){var i=0;if(typeof elm==="string"){elm=document.querySelectorAll(elm)}if(elm.constructor!==NodeList){elm=[elm]}if(typeof fn==="function"){if(!Array.isArray(args)){args=[args]}args=[elm].concat(args);for(;i<elm.length;++i){fn.apply(this,args)}}return elm}module.exports=ElmSelect},{}],4:[function(require,module,exports){"use strict";module.exports=function(s){return s.substr(0,1).toUpperCase()+s.substring(1)}},{}]},{},[1])(1)});<|endoftext|>


<commit_before>//jquery utils

String.prototype.ssplit = function (char, amount) {
    if (amount === 0) return [];
    var parts = this.split(char);
    var len = parts.length - 1;
    if (amount && Math.abs(amount) < len) {
        if (amount > 0) {
            var splited = parts.splice(0, amount);
            var toJoin = parts.splice(0,len).join(char);
            parts = splited.concat(toJoin);
        }else{
            var splited = parts.splice(amount, len);
            var toJoin = parts.splice(0,len).join(char);
            parts = [].concat(toJoin, splited);
        }
    }
    return parts;
};

$.extend({
    textToHtml: function(text){
        /*
        This function will transform the given text into HTML text.
        For example:
            "this is a\nmultiline\nString" -> "this is a
multiline
String"

        More to come.
        */

        if (text !== undefined) {
            var htmlText = $('

').text(text).html();
            return htmlText.replace(/\n/g, '
');
        }

        return "";
    },
    htmlToText: function(htmlText){
        /*
        This function does the oposite of textToHtml
        */

        if (htmlText !== undefined) {

            var text = htmlText.replace(/
|<\/br>/g, '\n');
            return $('

').html(text).text();
            // return text;
        }

        return "";

    },
    sorted : function(obj, sortFunction){
        var type = $.type(obj);
        if(type === "object"){
            var keys = Object.keys(obj).sort(sortFunction);
            var sortedObj = {};
            for (var i = 0; i < keys.length; i++) {
                sortedObj[keys[i]] = obj[keys[i]];
            }
            return sortedObj;
        }

        return obj;
    },
    toLinearArray : function(){
        /*
        Merge and converts a multi dimentional array into a single dimentional array
        For instance:
            $.toLinearArray(0,1,[[[4, 5],2],3], [8], 3, null, [0]) -> [0, 1, 4, 5, 2, 3, 8, 3, null, 0]
        */

        var dest = [];
        var objToMerge = Array.prototype.slice.call(arguments, 0);

        function append(d, o){
            var len = o.length;
            for (var i = 0; i < len; i++) {
                var obj = o[i];
                if (!$.isArray(obj)){
                    d.push(obj);
                }else{
                    append(d, obj);
                }
            }
        }

        append(dest, objToMerge);

        return dest;
    },
    attribute : function(){
        function getAttrFromPath(o, p){
            var pp = p.split('.');
            var i = 0;
            while(i < pp.length && o !== undefined){
                o = o[pp[i]];
                i = i + 1;
            }
            return o;
        };
        switch(arguments.length){
            case 2:
                // console.log('path' + arguments[1]);
                return getAttrFromPath(arguments[0], arguments[1]);
            case 3:
                var res = arguments[1].split('.');
                var obj = arguments[0];
                for(var i = 0; i < res.length - 1; i++) {
                    var a = res.shift();
                    if (obj[a] === undefined) {
                        obj[a] = {};
                    }
                    obj = obj[a];
                }
                obj[res[0]] = arguments[2];
                return
            default:
                throw "$.attribute must receive 2 or 3 arguments";
        }
    },
    changeLocation : function(href, data){
        /*
        This method navigates to the href address sending data in post method
        */
        var div = $('

');
        $('body').append(div);
        var html = '<form action="'+href+'" method="post">';
        for (var k in data){
            html += '<input name="' + k + '" value="' + data[k] + '"/>';
        }
        html += '</form>';

        div.html(html);

        div.children('form').submit();

    }
});

$.fn.extend({
    relative : function(rel){
        /*
        This function returns the position of an object relative to the argument rel.
        If rel is not defined, the position is relative to the page.
        */

        var $rel = $(rel);
        var res = this.offset();

        if ($rel.size() > 0) {
            var relOffset = $rel.offset();
            return {'top': (res.top - relOffset.top), 'left':(res.left - relOffset.left)};
        }else{
            return res;
        }
    },
    humanize : function(text){
        /*
        This function sets or gets a human version of the text inside an html object
        */
        if (arguments.length === 0){
            //Get the inner html as a string
            return $.htmlToText(this.html());
        }else{
            //Set inner html to this
            this.html($.textToHtml(text));
        }
    },
    dimensions : function(rel){
        if (arguments.length === 0){
            var res = {
                'top': this[0].offsetTop,
                'left': this[0].offsetLeft,
                'width': this[0].scrollWidth,
                'height': this[0].scrollHeight
            };
            return res;
        }

        var res = this.relative(rel);
        res['width'] = this[0].scrollWidth;
        res['height'] = this[0].scrollHeight;

        return res;
    },
    contains : function(rel){
        //This function returns if a jQuery object contains graphicaly another object
        var myDim = this.dimensions();
        var relDim = $(rel).dimensions();

        if (relDim.top < myDim.top ||
            relDim.left < myDim.left ||
            relDim.top + relDim.height > myDim.top + myDim.height ||
            relDim.left + relDim.width > myDim.left + myDim.width
            ){
            return false;
        }

        return true;
    },
    formAttributes : function(){
        //This functions transforms the serializeArray's array of object result into a single object
        //  with one unique key for each element name

        var result = {};
        var fields = this.serializeArray();

        for (var i = fields.length - 1; i >= 0; i--) {
            var value = fields[i].value !== ""?fields[i].value:null;
            var attr = $.attribute(result, fields[i].name);
            if(attr === undefined){
                $.attribute(result, fields[i].name, value);
            }else{
                if (attr && attr.push){
                    attr.push(value);
                }else{
                    $.attribute(result, fields[i].name, [attr, value]);
                }
            }
        }
        return result;
    },
});

$(function(){
    //Some functions to modify html default behavior
    $(document).on('group-change', '.toggle:radio', function(e, originalTarget){
        var that = e.target;
        that.dataset['checked'] = that == originalTarget && that.dataset['checked'] !== "true";
        that.checked = that.dataset['checked'] === "true";

        //Triggering change event on each associate label
        for (var i = that.labels.length - 1; i >= 0; i--) {
            $(that.labels[i]).trigger('change', {checked:that.checked});
        };
    });

    $(document).on('click', '.toggle:radio', function(e){
        $('.toggle:radio[name="'+ e.target.name +'"]').trigger('group-change', [e.target]);
    });
});

<commit_msg>Adding fillFromObject function to fill tables from objects<commit_after>//jquery utils

String.prototype.ssplit = function (char, amount) {
    if (amount === 0) return [];
    var parts = this.split(char);
    var len = parts.length - 1;
    if (amount && Math.abs(amount) < len) {
        if (amount > 0) {
            var splited = parts.splice(0, amount);
            var toJoin = parts.splice(0,len).join(char);
            parts = splited.concat(toJoin);
        }else{
            var splited = parts.splice(amount, len);
            var toJoin = parts.splice(0,len).join(char);
            parts = [].concat(toJoin, splited);
        }
    }
    return parts;
};

$.extend({
    textToHtml: function(text){
        /*
        This function will transform the given text into HTML text.
        For example:
            "this is a\nmultiline\nString" -> "this is a
multiline
String"

        More to come.
        */

        if (text !== undefined) {
            var htmlText = $('

').text(text).html();
            return htmlText.replace(/\n/g, '
');
        }

        return "";
    },
    htmlToText: function(htmlText){
        /*
        This function does the oposite of textToHtml
        */

        if (htmlText !== undefined) {

            var text = htmlText.replace(/
|<\/br>/g, '\n');
            return $('

').html(text).text();
            // return text;
        }

        return "";

    },
    sorted : function(obj, sortFunction){
        var type = $.type(obj);
        if(type === "object"){
            var keys = Object.keys(obj).sort(sortFunction);
            var sortedObj = {};
            for (var i = 0; i < keys.length; i++) {
                sortedObj[keys[i]] = obj[keys[i]];
            }
            return sortedObj;
        }

        return obj;
    },
    toLinearArray : function(){
        /*
        Merge and converts a multi dimentional array into a single dimentional array
        For instance:
            $.toLinearArray(0,1,[[[4, 5],2],3], [8], 3, null, [0]) -> [0, 1, 4, 5, 2, 3, 8, 3, null, 0]
        */

        var dest = [];
        var objToMerge = Array.prototype.slice.call(arguments, 0);

        function append(d, o){
            var len = o.length;
            for (var i = 0; i < len; i++) {
                var obj = o[i];
                if (!$.isArray(obj)){
                    d.push(obj);
                }else{
                    append(d, obj);
                }
            }
        }

        append(dest, objToMerge);

        return dest;
    },
    attribute : function(){
        function getAttrFromPath(o, p){
            var pp = p.split('.');
            var i = 0;
            while(i < pp.length && o !== undefined){
                o = o[pp[i]];
                i = i + 1;
            }
            return o;
        };
        switch(arguments.length){
            case 2:
                // console.log('path' + arguments[1]);
                return getAttrFromPath(arguments[0], arguments[1]);
            case 3:
                var res = arguments[1].split('.');
                var obj = arguments[0];
                for(var i = 0; i < res.length - 1; i++) {
                    var a = res.shift();
                    if (obj[a] === undefined) {
                        obj[a] = {};
                    }
                    obj = obj[a];
                }
                obj[res[0]] = arguments[2];
                return
            default:
                throw "$.attribute must receive 2 or 3 arguments";
        }
    },
    changeLocation : function(href, data){
        /*
        This method navigates to the href address sending data in post method
        */
        var div = $('

');
        $('body').append(div);
        var html = '<form action="'+href+'" method="post">';
        for (var k in data){
            html += '<input name="' + k + '" value="' + data[k] + '"/>';
        }
        html += '</form>';

        div.html(html);

        div.children('form').submit();

    }
});

$.fn.extend({
    relative : function(rel){
        /*
        This function returns the position of an object relative to the argument rel.
        If rel is not defined, the position is relative to the page.
        */

        var $rel = $(rel);
        var res = this.offset();

        if ($rel.size() > 0) {
            var relOffset = $rel.offset();
            return {'top': (res.top - relOffset.top), 'left':(res.left - relOffset.left)};
        }else{
            return res;
        }
    },
    humanize : function(text){
        /*
        This function sets or gets a human version of the text inside an html object
        */
        if (arguments.length === 0){
            //Get the inner html as a string
            return $.htmlToText(this.html());
        }else{
            //Set inner html to this
            this.html($.textToHtml(text));
        }
    },
    dimensions : function(rel){
        if (arguments.length === 0){
            var res = {
                'top': this[0].offsetTop,
                'left': this[0].offsetLeft,
                'width': this[0].scrollWidth,
                'height': this[0].scrollHeight
            };
            return res;
        }

        var res = this.relative(rel);
        res['width'] = this[0].scrollWidth;
        res['height'] = this[0].scrollHeight;

        return res;
    },
    containsInside : function(rel){
        //This function returns if a jQuery object contains graphicaly another object
        var myDim = this.dimensions();
        var relDim = $(rel).dimensions();

        if (relDim.top < myDim.top ||
            relDim.left < myDim.left ||
            relDim.top + relDim.height > myDim.top + myDim.height ||
            relDim.left + relDim.width > myDim.left + myDim.width
            ){
            return false;
        }

        return true;
    },
    formAttributes : function(){
        //This functions transforms the serializeArray's array of object result into a single object
        //  with one unique key for each element name

        var result = {};
        var fields = this.serializeArray();

        for (var i = fields.length - 1; i >= 0; i--) {
            var value = fields[i].value !== ""?fields[i].value:null;
            var attr = $.attribute(result, fields[i].name);
            if(attr === undefined){
                $.attribute(result, fields[i].name, value);
            }else{
                if (attr && attr.push){
                    attr.push(value);
                }else{
                    $.attribute(result, fields[i].name, [attr, value]);
                }
            }
        }
        return result;
    },
    fillFromObject : function(obj){
        if (this[0].tagName.toUpperCase() !== 'TABLE') {
            //By the moment, no other element than TABLE will be filled with this function
            throw this.toString() + ' is not a TABLE element';
        }

        var html = '';
        var body = '';
        var bodyObj = !$.isArray(obj.body);
        if(bodyObj){
            //Is an Object
            for(var k in obj.body){
                body += '
';
                body += '' + k + '	';
                for (var i = 0; i < obj.body[k].length; i++) {
                    body += '' + obj.body[k][i] + '	';
                }
                body += '
';
            }
        }else{
            //Is an Array
            for(var r = 0; obj.body.length; r++){
                body += '
';
                for (var i = 0; i < obj.body[r].length; i++) {
                    body += '' + obj.body[r][i] + '	';
                }
                body += '
';
            }
        }

        if (obj.head) {
            html += '
';
            if (bodyObj) {
                html += '	';
            }
            for (var i = 0; i < obj.head.length; i++) {
                html += '' + obj.head[i] + '	';
            }
            html += '
';
        }

        this.html(html + body);
    },
    fillFromJson : function(json){

    }
});

$(function(){
    //Some functions to modify html default behavior
    $(document).on('group-change', '.toggle:radio', function(e, originalTarget){
        var that = e.target;
        that.dataset['checked'] = that == originalTarget && that.dataset['checked'] !== "true";
        that.checked = that.dataset['checked'] === "true";

        //Triggering change event on each associate label
        for (var i = that.labels.length - 1; i >= 0; i--) {
            $(that.labels[i]).trigger('change', {checked:that.checked});
        };
    });

    $(document).on('click', '.toggle:radio', function(e){
        $('.toggle:radio[name="'+ e.target.name +'"]').trigger('group-change', [e.target]);
    });
});

<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name MatchCalendarApp.controller:PostGeneratorGameType
 * @description
 * # PostGeneratorGameType
 * Service of the MatchCalendarApp
 */
angular.module('MatchCalendarApp')
    .factory('PostGeneratorGameType', ['PostGeneratorGameTypeField', function (PostGeneratorGameTypeField) {

        /**
         * Create a new game type
         *
         * @param {Object} options
         * @param {String} options.name - the name of the game mode
         * @param {String} options.description - a short description of the game mode
         * @param {PostGeneratorGameTypeField[]} [options.fields] - list of fields needed for the gamemode
         * @param {Function} [options.formatter] - optional formatter to override the default
         * @constructor
         */
        var GameType = function(options) {
            this.name = options.name;
            this.description = options.description || 'No description set';
            this.fields = options.fields || [];
            this.format = options.formatter || function() { return 'ERROR CREATING GAME TYPE'; };
        };

        GameType.prototype.defaultValues = function() {
            return this.fields.reduce(function(acc, cur) {
                acc[cur.name] = cur.defaultValue;

                return acc;
            }, {});
        };

        // generic formatter to use with size based game types
        var genericSizeFormatter = function(fieldAnswers) {
            return this.name + ' To' + fieldAnswers.size;
        };

        GameType.types = {};

        GameType.types.FFA = new GameType({
            name: 'FFA',
            description: 'Every man for himself.',
            fields: [],
            format: function() {
                return 'FFA';
            }
        });

        GameType.types.CHOSEN = new GameType({
            name: 'Chosen',
            description: 'Players form their teams before the match.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.RANDOM = new GameType({
            name: 'Random',
            description: 'Players are assigned random teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.PICKED = new GameType({
            name: 'Picked',
            description: 'Players take turns joining a team.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.MYSTERY = new GameType({
            name: 'Mystery',
            description: 'Players are assigned unknown teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.CAPTAINS = new GameType({
            name: 'Captains',
            description: 'Selected team leaders pick their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of captains',
                    defaultValue: 4,
                    type: 'number',
                    name: 'captains'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Selection Method',
                    defaultValue: '',
                    name: 'selection'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.captains + ' Captains ' + fieldAnswers.selection;
            }
        });

        GameType.types.AUCTION = new GameType({
            name: 'Auction',
            description: 'Selected team leaders buy their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of buyers',
                    defaultValue: 4,
                    type: 'number',
                    name: 'buyers'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Currency',
                    defaultValue: 'diamonds',
                    type: 'text',
                    name: 'currency'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.buyers + ' buyers Auction (' + fieldAnswers.currency;
            }
        });

        GameType.types.ALLIANCES = new GameType({
            name: 'Alliance',
            description: 'Players can form informal teams on their own.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Max amount of players for an alliance',
                    defaultValue: 8,
                    type: 'number',
                    name: 'max'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Can alliances win?',
                    defaultValue: true,
                    type: 'checkbox',
                    name: 'canWin'
                })
            ],
            format: function(fieldAnswers) {
                return 'Alliances up to ' + fieldAnswers.max + '. Alliances can' + (fieldAnswers.canWin ? '' : 'not') + ' win';
            }
        });

        GameType.types.CUSTOM = new GameType({
            name: 'Custom',
            description: 'Custom team types',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'What to show in post title',
                    defaultValue: 'Custom',
                    type: 'text',
                    name: 'custom'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.custom;
            }
        });

        return GameType;
    }]);
<commit_msg>fix(PostGeneratorGameType): fix using wrong variable name<commit_after>'use strict';

/**
 * @ngdoc function
 * @name MatchCalendarApp.controller:PostGeneratorGameType
 * @description
 * # PostGeneratorGameType
 * Service of the MatchCalendarApp
 */
angular.module('MatchCalendarApp')
    .factory('PostGeneratorGameType', ['PostGeneratorGameTypeField', function (PostGeneratorGameTypeField) {

        /**
         * Create a new game type
         *
         * @param {Object} options
         * @param {String} options.name - the name of the game mode
         * @param {String} options.description - a short description of the game mode
         * @param {PostGeneratorGameTypeField[]} [options.fields] - list of fields needed for the gamemode
         * @param {Function} [options.format] - optional formatter to override the default
         * @constructor
         */
        var GameType = function(options) {
            this.name = options.name;
            this.description = options.description || 'No description set';
            this.fields = options.fields || [];
            this.format = options.format || function() { return 'ERROR CREATING GAME TYPE'; };
        };

        GameType.prototype.defaultValues = function() {
            return this.fields.reduce(function(acc, cur) {
                acc[cur.name] = cur.defaultValue;

                return acc;
            }, {});
        };

        // generic formatter to use with size based game types
        var genericSizeFormatter = function(fieldAnswers) {
            return this.name + ' To' + fieldAnswers.size;
        };

        GameType.types = {};

        GameType.types.FFA = new GameType({
            name: 'FFA',
            description: 'Every man for himself.',
            fields: [],
            format: function() {
                return 'FFA';
            }
        });

        GameType.types.CHOSEN = new GameType({
            name: 'Chosen',
            description: 'Players form their teams before the match.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.RANDOM = new GameType({
            name: 'Random',
            description: 'Players are assigned random teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.PICKED = new GameType({
            name: 'Picked',
            description: 'Players take turns joining a team.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.MYSTERY = new GameType({
            name: 'Mystery',
            description: 'Players are assigned unknown teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.CAPTAINS = new GameType({
            name: 'Captains',
            description: 'Selected team leaders pick their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of captains',
                    defaultValue: 4,
                    type: 'number',
                    name: 'captains'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Selection Method',
                    defaultValue: '',
                    name: 'selection'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.captains + ' Captains ' + fieldAnswers.selection;
            }
        });

        GameType.types.AUCTION = new GameType({
            name: 'Auction',
            description: 'Selected team leaders buy their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of buyers',
                    defaultValue: 4,
                    type: 'number',
                    name: 'buyers'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Currency',
                    defaultValue: 'diamonds',
                    type: 'text',
                    name: 'currency'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.buyers + ' buyers Auction (' + fieldAnswers.currency;
            }
        });

        GameType.types.ALLIANCES = new GameType({
            name: 'Alliance',
            description: 'Players can form informal teams on their own.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Max amount of players for an alliance',
                    defaultValue: 8,
                    type: 'number',
                    name: 'max'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Can alliances win?',
                    defaultValue: true,
                    type: 'checkbox',
                    name: 'canWin'
                })
            ],
            format: function(fieldAnswers) {
                return 'Alliances up to ' + fieldAnswers.max + '. Alliances can' + (fieldAnswers.canWin ? '' : 'not') + ' win';
            }
        });

        GameType.types.CUSTOM = new GameType({
            name: 'Custom',
            description: 'Custom team types',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'What to show in post title',
                    defaultValue: 'Custom',
                    type: 'text',
                    name: 'custom'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.custom;
            }
        });

        return GameType;
    }]);
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
"use strict";

const assert = require('assert');

const defs    = require('./defs.js');
const ldebug  = require('./ldebug.js');
const lobject = require('./lobject.js');
const lstring = require('./lstring.js');
const CT      = defs.constant_types;

const table_hash = function(key) {
    switch(key.type) {
    case CT.LUA_TBOOLEAN:
    case CT.LUA_TLIGHTUSERDATA: /* XXX: if user pushes conflicting lightuserdata then the table will do odd things */
    case CT.LUA_TNUMFLT:
    case CT.LUA_TNUMINT:
    case CT.LUA_TTABLE:
    case CT.LUA_TLCL:
    case CT.LUA_TLCF:
    case CT.LUA_TCCL:
    case CT.LUA_TUSERDATA:
    case CT.LUA_TTHREAD:
        return key.value;
    case CT.LUA_TSHRSTR:
    case CT.LUA_TLNGSTR:
        return lstring.luaS_hashlongstr(key.tsvalue());
    default:
        throw new Error("unknown key type: " + key.type);
    }
};

class Table {
    constructor(L) {
        this.id = L.l_G.id_counter++;
        this.strong = new Map();
        this.dead_strong = new Map();
        this.dead_weak = void 0; /* initialised when needed */
        this.f = void 0; /* first entry */
        this.l = void 0; /* last entry */
        this.metatable = null;
    }
}

const add = function(t, hash, key, value) {
    t.dead_strong.clear();
    t.dead_weak = void 0;
    let prev = null;
    let entry = {
        key: key,
        value: value,
        p: prev = t.l,
        n: void 0
    };
    if (!t.f) t.f = entry;
    if (prev) prev.n = entry;
    t.strong.set(hash, entry);
    t.l = entry;
};

const is_valid_weakmap_key = function(k) {
    return typeof k === 'object' ? k !== null : typeof k === 'function';
};

/* Move out of 'strong' part and into 'dead' part. */
const mark_dead = function(t, hash) {
    let e = t.strong.get(hash);
    if (e) {
        e.key.setdeadvalue();
        e.value = void 0;
        let next = e.n;
        let prev = e.p;
        e.p = void 0; /* no need to know previous item any more */
        if(prev) prev.n = next;
        if(next) next.p = prev;
        if(t.f === e) t.f = next;
        if(t.l === e) t.l = prev;
        t.strong.delete(hash);
        if (is_valid_weakmap_key(hash)) {
            if (!t.dead_weak) t.dead_weak = new WeakMap();
            t.dead_weak.set(hash, e);
        } else {
            /* can't be used as key in weakmap */
            t.dead_strong.set(hash, e);
        }
    }
};

const luaH_new = function(L) {
    return new Table(L);
};

const getgeneric = function(t, hash) {
    let v = t.strong.get(hash);
    return v ? v.value : lobject.luaO_nilobject;
};

const luaH_getint = function(t, key) {
    assert(typeof key == "number" && (key|0) === key);
    return getgeneric(t, key);
};

const luaH_getstr = function(t, key) {
    assert(key instanceof lstring.TString);
    return getgeneric(t, lstring.luaS_hashlongstr(key));
};

const luaH_get = function(t, key) {
    assert(key instanceof lobject.TValue);
    if (key.ttisnil())
        return lobject.luaO_nilobject;
    return getgeneric(t, table_hash(key));
};

const setgeneric = function(t, hash, key) {
    let v = t.strong.get(hash);
    if (v)
        return v.value;

    let tv = new lobject.TValue(CT.LUA_TNIL, null);
    add(t, hash, key, tv);
    return tv;
};

const luaH_setint = function(t, key, value) {
    assert(typeof key == "number" && (key|0) === key && value instanceof lobject.TValue);
    let hash = key; /* table_hash known result */
    if (value.ttisnil()) {
        mark_dead(t, hash);
        return;
    }
    let v = t.strong.get(hash);
    if (v) {
        let tv = v.value;
        tv.setfrom(value);
    } else {
        let k = new lobject.TValue(CT.LUA_TNUMINT, key);
        let v = new lobject.TValue(value.type, value.value);
        add(t, hash, k, v);
    }
};

const luaH_set = function(t, key) {
    assert(key instanceof lobject.TValue);
    let hash = table_hash(key);
    return setgeneric(t, hash, new lobject.TValue(key.type, key.value));
};

const luaH_delete = function(t, key) {
    assert(key instanceof lobject.TValue);
    let hash = table_hash(key);
    return mark_dead(t, hash);
};

/*
** Try to find a boundary in table 't'. A 'boundary' is an integer index
** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
*/
const luaH_getn = function(t) {
    let i = 0;
    let j = t.strong.size + 1; /* use known size of Map to bound search */
    /* now do a binary search between them */
    while (j - i > 1) {
        let m = Math.floor((i+j)/2);
        if (luaH_getint(t, m).ttisnil()) j = m;
        else i = m;
    }
    return i;
};

const luaH_next = function(L, table, keyI) {
    let keyO = L.stack[keyI];

    let entry;
    if (keyO.type === CT.LUA_TNIL) {
        entry = table.f;
        if (!entry)
            return false;
    } else {
        /* First find current key */
        let hash = table_hash(keyO);
        /* Look in main part of table */
        entry = table.strong.get(hash);
        if (entry) {
            entry = entry.n;
            if (!entry)
                return false;
        } else {
            /* Try dead keys */
            entry = table.dead_weak.get(hash) || table.dead_strong.get(hash);
            if (!entry)
                /* item not in table */
                return ldebug.luaG_runerror(L, defs.to_luastring("invalid key to 'next'"));
            /* Iterate until either out of keys, or until finding a non-dead key */
            do {
                entry = entry.n;
                if (!entry)
                    return false;
            } while (entry.key.ttisdeadkey());
        }
    }
    L.stack[keyI] = new lobject.TValue(entry.key.type, entry.key.value);
    L.stack[keyI+1] = new lobject.TValue(entry.value.type, entry.value.value);
    return true;
};

module.exports.luaH_delete  = luaH_delete;
module.exports.luaH_get     = luaH_get;
module.exports.luaH_getint  = luaH_getint;
module.exports.luaH_getn    = luaH_getn;
module.exports.luaH_getstr  = luaH_getstr;
module.exports.luaH_set     = luaH_set;
module.exports.luaH_setint  = luaH_setint;
module.exports.luaH_new     = luaH_new;
module.exports.luaH_next    = luaH_next;
<commit_msg>test dead_weak for undefined in luaH_next<commit_after>/*jshint esversion: 6 */
"use strict";

const assert = require('assert');

const defs    = require('./defs.js');
const ldebug  = require('./ldebug.js');
const lobject = require('./lobject.js');
const lstring = require('./lstring.js');
const CT      = defs.constant_types;

const table_hash = function(key) {
    switch(key.type) {
    case CT.LUA_TBOOLEAN:
    case CT.LUA_TLIGHTUSERDATA: /* XXX: if user pushes conflicting lightuserdata then the table will do odd things */
    case CT.LUA_TNUMFLT:
    case CT.LUA_TNUMINT:
    case CT.LUA_TTABLE:
    case CT.LUA_TLCL:
    case CT.LUA_TLCF:
    case CT.LUA_TCCL:
    case CT.LUA_TUSERDATA:
    case CT.LUA_TTHREAD:
        return key.value;
    case CT.LUA_TSHRSTR:
    case CT.LUA_TLNGSTR:
        return lstring.luaS_hashlongstr(key.tsvalue());
    default:
        throw new Error("unknown key type: " + key.type);
    }
};

class Table {
    constructor(L) {
        this.id = L.l_G.id_counter++;
        this.strong = new Map();
        this.dead_strong = new Map();
        this.dead_weak = void 0; /* initialised when needed */
        this.f = void 0; /* first entry */
        this.l = void 0; /* last entry */
        this.metatable = null;
    }
}

const add = function(t, hash, key, value) {
    t.dead_strong.clear();
    t.dead_weak = void 0;
    let prev = null;
    let entry = {
        key: key,
        value: value,
        p: prev = t.l,
        n: void 0
    };
    if (!t.f) t.f = entry;
    if (prev) prev.n = entry;
    t.strong.set(hash, entry);
    t.l = entry;
};

const is_valid_weakmap_key = function(k) {
    return typeof k === 'object' ? k !== null : typeof k === 'function';
};

/* Move out of 'strong' part and into 'dead' part. */
const mark_dead = function(t, hash) {
    let e = t.strong.get(hash);
    if (e) {
        e.key.setdeadvalue();
        e.value = void 0;
        let next = e.n;
        let prev = e.p;
        e.p = void 0; /* no need to know previous item any more */
        if(prev) prev.n = next;
        if(next) next.p = prev;
        if(t.f === e) t.f = next;
        if(t.l === e) t.l = prev;
        t.strong.delete(hash);
        if (is_valid_weakmap_key(hash)) {
            if (!t.dead_weak) t.dead_weak = new WeakMap();
            t.dead_weak.set(hash, e);
        } else {
            /* can't be used as key in weakmap */
            t.dead_strong.set(hash, e);
        }
    }
};

const luaH_new = function(L) {
    return new Table(L);
};

const getgeneric = function(t, hash) {
    let v = t.strong.get(hash);
    return v ? v.value : lobject.luaO_nilobject;
};

const luaH_getint = function(t, key) {
    assert(typeof key == "number" && (key|0) === key);
    return getgeneric(t, key);
};

const luaH_getstr = function(t, key) {
    assert(key instanceof lstring.TString);
    return getgeneric(t, lstring.luaS_hashlongstr(key));
};

const luaH_get = function(t, key) {
    assert(key instanceof lobject.TValue);
    if (key.ttisnil())
        return lobject.luaO_nilobject;
    return getgeneric(t, table_hash(key));
};

const setgeneric = function(t, hash, key) {
    let v = t.strong.get(hash);
    if (v)
        return v.value;

    let tv = new lobject.TValue(CT.LUA_TNIL, null);
    add(t, hash, key, tv);
    return tv;
};

const luaH_setint = function(t, key, value) {
    assert(typeof key == "number" && (key|0) === key && value instanceof lobject.TValue);
    let hash = key; /* table_hash known result */
    if (value.ttisnil()) {
        mark_dead(t, hash);
        return;
    }
    let v = t.strong.get(hash);
    if (v) {
        let tv = v.value;
        tv.setfrom(value);
    } else {
        let k = new lobject.TValue(CT.LUA_TNUMINT, key);
        let v = new lobject.TValue(value.type, value.value);
        add(t, hash, k, v);
    }
};

const luaH_set = function(t, key) {
    assert(key instanceof lobject.TValue);
    let hash = table_hash(key);
    return setgeneric(t, hash, new lobject.TValue(key.type, key.value));
};

const luaH_delete = function(t, key) {
    assert(key instanceof lobject.TValue);
    let hash = table_hash(key);
    return mark_dead(t, hash);
};

/*
** Try to find a boundary in table 't'. A 'boundary' is an integer index
** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
*/
const luaH_getn = function(t) {
    let i = 0;
    let j = t.strong.size + 1; /* use known size of Map to bound search */
    /* now do a binary search between them */
    while (j - i > 1) {
        let m = Math.floor((i+j)/2);
        if (luaH_getint(t, m).ttisnil()) j = m;
        else i = m;
    }
    return i;
};

const luaH_next = function(L, table, keyI) {
    let keyO = L.stack[keyI];

    let entry;
    if (keyO.type === CT.LUA_TNIL) {
        entry = table.f;
        if (!entry)
            return false;
    } else {
        /* First find current key */
        let hash = table_hash(keyO);
        /* Look in main part of table */
        entry = table.strong.get(hash);
        if (entry) {
            entry = entry.n;
            if (!entry)
                return false;
        } else {
            /* Try dead keys */
            entry = (table.dead_weak && table.dead_weak.get(hash)) || table.dead_strong.get(hash);
            if (!entry)
                /* item not in table */
                return ldebug.luaG_runerror(L, defs.to_luastring("invalid key to 'next'"));
            /* Iterate until either out of keys, or until finding a non-dead key */
            do {
                entry = entry.n;
                if (!entry)
                    return false;
            } while (entry.key.ttisdeadkey());
        }
    }
    L.stack[keyI] = new lobject.TValue(entry.key.type, entry.key.value);
    L.stack[keyI+1] = new lobject.TValue(entry.value.type, entry.value.value);
    return true;
};

module.exports.luaH_delete  = luaH_delete;
module.exports.luaH_get     = luaH_get;
module.exports.luaH_getint  = luaH_getint;
module.exports.luaH_getn    = luaH_getn;
module.exports.luaH_getstr  = luaH_getstr;
module.exports.luaH_set     = luaH_set;
module.exports.luaH_setint  = luaH_setint;
module.exports.luaH_new     = luaH_new;
module.exports.luaH_next    = luaH_next;
<|endoftext|>


<commit_before>;(function () {
    function initWatch(vm, watch) {
        vm._watchers || (vm._watchers = []);
        for (var key in watch) {
            var handler = watch[key]
            if (BI.isArray(handler)) {
                for (var i = 0; i < handler.length; i++) {
                    vm._watchers.push(createWatcher(vm, key, handler[i]))
                }
            } else {
                vm._watchers.push(createWatcher(vm, key, handler))
            }
        }
    }

    function createWatcher(vm, keyOrFn, handler, options) {
        if (BI.isPlainObject(handler)) {
            options = handler
            handler = handler.handler
        }
        if (typeof handler === 'string') {
            handler = vm[handler]
        }
        return Fix.watch(vm, keyOrFn, handler, options)
    }

    var _init = BI.Widget.prototype._init;
    BI.Widget.prototype._init = function () {
        if (window.Fix && this._store) {
            this.store = this._store();
            if (this.store instanceof Fix.VM) {
                this.model = this.store.model;
            } else {
                this.model = this.store;
            }
            initWatch(this, this.watch);
        }
        _init.apply(this, arguments);
    };

    var unMount = BI.Widget.prototype._unMount;
    BI.Widget.prototype._unMount = function () {
        unMount.apply(this, arguments);
        this.store && this.store.destroy();
        BI.each(this._watchers, function (i, unwatches) {
            unwatches = BI.isArray(unwatches) ? unwatches : [unwatches];
            BI.each(unwatches, function (j, unwatch) {
                unwatch();
            })
        });
        this._watchers && (this._watchers = []);
        this.store && (this.store = null);
    }
}());<commit_msg>update<commit_after>;(function () {
    function initWatch(vm, watch) {
        vm._watchers || (vm._watchers = []);
        for (var key in watch) {
            var handler = watch[key]
            if (BI.isArray(handler)) {
                for (var i = 0; i < handler.length; i++) {
                    vm._watchers.push(createWatcher(vm, key, handler[i]))
                }
            } else {
                vm._watchers.push(createWatcher(vm, key, handler))
            }
        }
    }

    function createWatcher(vm, keyOrFn, handler, options) {
        return Fix.watch(vm, keyOrFn, handler, options)
    }

    var _init = BI.Widget.prototype._init;
    BI.Widget.prototype._init = function () {
        if (window.Fix && this._store) {
            this.store = this._store();
            if (this.store instanceof Fix.VM) {
                this.model = this.store.model;
            } else {
                this.model = this.store;
            }
            initWatch(this, this.watch);
        }
        _init.apply(this, arguments);
    };

    var unMount = BI.Widget.prototype._unMount;
    BI.Widget.prototype._unMount = function () {
        unMount.apply(this, arguments);
        this.store && this.store.destroy();
        BI.each(this._watchers, function (i, unwatches) {
            unwatches = BI.isArray(unwatches) ? unwatches : [unwatches];
            BI.each(unwatches, function (j, unwatch) {
                unwatch();
            })
        });
        this._watchers && (this._watchers = []);
        this.store && (this.store = null);
    }
}());<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 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/>.
 */
import React, { Component } from 'react'

class SuccessContent extends Component {

  clickHandler = (event) => {
    event.preventDefault();
    this.props.onShowRegisterForm();
  }

  render() {
    return (

        Registration success

Please check your email for further instructions. Or display register form.

    );
  }
}

export default class RegisterComponent extends React.Component {
  submitHandler = (event) => {
    event.preventDefault();

    let form = event.target;

    if (form.password.value != form.password_repeat.value) {
      form.password_repeat.setCustomValidity("Passwords don't match");
      return;
    }

    form.password_repeat.setCustomValidity('');

    if (!form.agree.checked) {
      form.agree.setCustomValidity('You have to agree to Terms before registering');
      return;
    }

    this.props.onRegisterUser(
      form.username.value,
      form.password.value,
      form.email.value,
      form.firstName.value,
      form.lastName.value
    );
  };

  render() {
    if (this.props.registration_success) {
      return ( <SuccessContent onShowRegisterForm={this.props.onShowRegisterForm} /> );
    }
    return (

      Register
      <form action="" onSubmit={this.submitHandler}>

              Username
              <input className="input input-block" type="text" id="registerUsername" name="username" required="required"/>

              First name
              <input className="input input-block" type="text" id="registerFirstName" name="firstName"/>

              Last name
              <input className="input input-block" type="text" id="registerLastName"name="lastName"/>

              Email
              <input className="input input-block" type="email" id="registerEmail"name="email" required="required"/>

              Password
              <input className="input input-block" type="password" id="registerPassword"name="password" required="required"/>

              Repeat password
              <input className="input input-block" type="password" id="registerPasswordRepeat"name="password_repeat" required="required"/>

            <input type="checkbox" className="checkbox" name="agree" required="required" />I agree to T&C
            <button className="button button-wide button-yellow">Create account</button>

      </form>

    )
  }
}
<commit_msg>Register component starting redesign new UI<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 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/>.
 */
import React, { Component } from 'react'

class SuccessContent extends Component {

  clickHandler = (event) => {
    event.preventDefault();
    this.props.onShowRegisterForm();
  }

  render() {
    return (

        Registration success

Please check your email for further instructions. Or display register form.

    );
  }
}

export default class RegisterComponent extends React.Component {
  submitHandler = (event) => {
    event.preventDefault();

    let form = event.target;

    if (form.password.value != form.password_repeat.value) {
      form.password_repeat.setCustomValidity("Passwords don't match");
      return;
    }

    form.password_repeat.setCustomValidity('');

    if (!form.agree.checked) {
      form.agree.setCustomValidity('You have to agree to Terms before registering');
      return;
    }

    this.props.onRegisterUser(
      form.username.value,
      form.password.value,
      form.email.value,
      form.firstName.value,
      form.lastName.value
    );
  };

  render() {
    if (this.props.registration_success) {
      return ( <SuccessContent onShowRegisterForm={this.props.onShowRegisterForm} /> );
    }
    return (

Create new account

Be the change

Connect with parents and education professionals from around the world to make education better for all children in all schools and families worldwide.

      <form action="" onSubmit={this.submitHandler}>

              Username
              <input className="input input-block" type="text" id="registerUsername" name="username" required="required"/>

              First name
              <input className="input input-block" type="text" id="registerFirstName" name="firstName"/>

              Last name
              <input className="input input-block" type="text" id="registerLastName"name="lastName"/>

              Email
              <input className="input input-block" type="email" id="registerEmail"name="email" required="required"/>

              Password
              <input className="input input-block" type="password" id="registerPassword"name="password" required="required"/>

              Repeat password
              <input className="input input-block" type="password" id="registerPasswordRepeat"name="password_repeat" required="required"/>

            <input type="checkbox" className="checkbox" name="agree" required="required" />I agree to T&C
            <button className="button button-wide button-yellow">Create account</button>

      </form>

    )
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import {observer} from 'mobx-react';
import {observable, computed} from 'mobx';

const ESCAPE_KEY = 27;
const ENTER_KEY = 13;

class State {
	@observable editText = '';
	constructor(editText){
		this.editText = editText;
	}
}

@observer
export default class TodoItem extends React.Component {
	constructor(props, context) {
		super(props, context);
		this.state = new State(props.todo.title);
	}

	render() {
		const {viewStore, todo} = this.props;
		return (

 todo === viewStore.todoBeingEdited ? "editing" : "").get()
			].join(" ")}>

					<input
						className="toggle"
						type="checkbox"
						checked={todo.completed}
						onChange={this.handleToggle}
					/>

						{todo.title}

					<button className="destroy" onClick={this.handleDestroy} />

				<input
					ref="editField"
					className="edit"
					value={this.state.editText}
					onBlur={this.handleSubmit}
					onChange={this.handleChange}
					onKeyDown={this.handleKeyDown}
				/>

		);
	}

	handleSubmit = (event) => {
		const val = this.state.editText.trim();
		if (val) {
			this.props.todo.setTitle(val);
			this.state.editText = val;
		} else {
			this.handleDestroy();
		}
		this.props.viewStore.todoBeingEdited = null;
	};

	handleDestroy = () => {
		this.props.todo.destroy();
		this.props.viewStore.todoBeingEdited = null;
	};

	handleEdit = () => {
		const todo = this.props.todo;
		this.props.viewStore.todoBeingEdited = todo;
		this.state.editText = todo.title;
	};

	handleKeyDown = (event) => {
		if (event.which === ESCAPE_KEY) {
			this.state.editText = this.props.todo.title;
			this.props.viewStore.todoBeingEdited = null;
		} else if (event.which === ENTER_KEY) {
			this.handleSubmit(event);
		}
	};

	handleChange = (event) => {
		this.state.editText = event.target.value;
	};

	handleToggle = () => {
		this.props.todo.toggle();
	};
}

TodoItem.propTypes = {
	todo: React.PropTypes.object.isRequired,
	viewStore: React.PropTypes.object.isRequired
};
<commit_msg>replaced computed with expr<commit_after>import React from 'react';
import {observer} from 'mobx-react';
import {observable, expr} from 'mobx';

const ESCAPE_KEY = 27;
const ENTER_KEY = 13;

class State {
	@observable editText = '';
	constructor(editText){
		this.editText = editText;
	}
}

@observer
export default class TodoItem extends React.Component {
	constructor(props, context) {
		super(props, context);
		this.state = new State(props.todo.title);
	}

	render() {
		const {viewStore, todo} = this.props;
		return (

 todo === viewStore.todoBeingEdited ? "editing" : "")
			].join(" ")}>

					<input
						className="toggle"
						type="checkbox"
						checked={todo.completed}
						onChange={this.handleToggle}
					/>

						{todo.title}

					<button className="destroy" onClick={this.handleDestroy} />

				<input
					ref="editField"
					className="edit"
					value={this.state.editText}
					onBlur={this.handleSubmit}
					onChange={this.handleChange}
					onKeyDown={this.handleKeyDown}
				/>

		);
	}

	handleSubmit = (event) => {
		const val = this.state.editText.trim();
		if (val) {
			this.props.todo.setTitle(val);
			this.state.editText = val;
		} else {
			this.handleDestroy();
		}
		this.props.viewStore.todoBeingEdited = null;
	};

	handleDestroy = () => {
		this.props.todo.destroy();
		this.props.viewStore.todoBeingEdited = null;
	};

	handleEdit = () => {
		const todo = this.props.todo;
		this.props.viewStore.todoBeingEdited = todo;
		this.state.editText = todo.title;
	};

	handleKeyDown = (event) => {
		if (event.which === ESCAPE_KEY) {
			this.state.editText = this.props.todo.title;
			this.props.viewStore.todoBeingEdited = null;
		} else if (event.which === ENTER_KEY) {
			this.handleSubmit(event);
		}
	};

	handleChange = (event) => {
		this.state.editText = event.target.value;
	};

	handleToggle = () => {
		this.props.todo.toggle();
	};
}

TodoItem.propTypes = {
	todo: React.PropTypes.object.isRequired,
	viewStore: React.PropTypes.object.isRequired
};
<|endoftext|>