<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

var utils = IPython.utils;

require(["base/js/events"], function (events) {

    // IPython.load_extensions('module-sidebar/module-sidebar');
    // IPython.load_extensions('module-tabs/module-tabs');
    //IPython.load_extensions('module-tree/module-tree');
});

var nbname = '';

;(function () {

require(["custom/module-tabs",
		"custom/module-sidebar",
		'custom/jquery.cookie',
		'custom/jquery.treeview',
		'custom/jquery.ui.position',
		'custom/jquery.contextMenu'
		],
		function (events) {

//require(['custom/jquery.cookie'], function () {

	'use strict';
	window.console && console.log('custom module loaded');

	$('#data.tab-pane').html('');

   	var list_loaded = function (data, status, xhr, param) {

    	var len = data.length;

    	if (len > 0) {
    		$('

')
    			.appendTo('#directory.tab-pane');
    	}
    	for (var i=0; i<len; i++) {
			var item = data[len];
			if (data[i].type === 'directory') {
				$('

')
					//.append('' + data[i].name + '')
					.append('' + data[i].name + '' +
						'

')
					.appendTo('#directory-tree');
			} else {
				$('

')
					.append('' + data[i].name + '')
					//.append('' + data[i].name + '')
					.appendTo('#directory-tree');
			}
    	}

 //    	$('
' +
	// 	'
Folder 1' +
	// 		'
' +
	// 			'
Item 1.1' +
	// 				'
' +
	// 					'
Item 1.1.1
' +
	// 				'
' +
	// 			'
' +
	// 			'
Folder 2' +
	// 				'
' +
	// 					'
Subfolder 2.1' +
	// 						'
' +
	// 							'
File 2.1.1
' +
	// 							'
File 2.1.2
' +
	// 						'
' +
	// 					'
' +
	// 					'
Subfolder 2.2' +
	// 						'
' +
	// 							'
File 2.2.1
' +
	// 							'
File 2.2.2
' +
	// 						'
' +
	// 					'
' +
	// 				'
' +
	// 			'
' +
	// 			'
Folder 3 (closed at start)' +
	// 				'
' +
	// 					'
File 3.1
' +
	// 				'
' +
	// 			'
' +
	// 			'
File 4
' +
	// 		'
' +
	// 	'
' +
	// '
').appendTo('#directory-tree');
    	//$('#directory-tree.filetree').appendTo('#directory.tab-pane');
    	$('#directory').tab('show');
    	$('#directory-tree .file a').click(function () {

    	});

		$('#directory-tree').treeview({
			animated: "fast",
			collapsed: true,
			unique: true,
			persist: "cookie",
			"toggle": function() {

			},
			'click.treeview': function () {
				window.console && console.log("%o was toggled", this);
			}
		});

		$.contextMenu({
	        selector: '.context-menu-one',
	        callback: function(key, options) {
	            var m = "clicked: " + key;
	            window.console && console.log(m);
				if (key == 'delete') {
					nbname = $(this).find('a').html();
					delete_notebook();
		        } else if (key == 'add') {
		        	new_notebook();
		        }
	        },
	        items: {
	            "delete": {name: "Delete", icon: "delete"},
	            "add": {name: "Add", icon: "add"}
	        }
	    });

	    $('.context-menu-one').on('click', function(e){
	        console.log('clicked', this);

	    })
   	};

    var settings = {
        processData : false,
        cache : false,
        type : "GET",
        dataType : "json",
        success : $.proxy(list_loaded, this),
        error : $.proxy( function(xhr, status, error){
            utils.log_ajax_error(xhr, status, error);
            list_loaded([], null, null, {msg:"Error connecting to server."});
                         },this)
    };

    var url = utils.url_join_encode(
                '/',
                'api',
                'notebooks'
        );

	$.ajax(url, settings);

	var delete_notebook = function () {

		var message = 'Are you sure you want to permanently delete the notebook: ' + nbname + '?';
		IPython.dialog.modal({
			title : "Delete notebook",
			body : message,
			buttons : {
				Delete: {
					class: "btn-danger",
					click: function () {
						var settings = {
				            processData : false,
				            cache : false,
				            type : "DELETE",
				            dataType : "json",
				            success : function (data, status, xhr) {
				                //parent_item.remove();
				                $('a[href="' + nbname + '"').parent().parent().remove();
				            },
				            error : utils.log_ajax_error,
				        };
				        var url = utils.url_join_encode(
				            '/',
				            'api/notebooks',
				            "",
				            nbname
				        );
				        $.ajax(url, settings);
					}
				},
				Cancel: {}
			}
		});

	}

	var new_notebook = function(){
        var path = '';
        var base_url = '/';
        var settings = {
            processData : false,
            cache : false,
            type : "POST",
            dataType : "json",
            async : false,
            success : function (data, status, xhr) {
                var notebook_name = data.name;
                window.location.replace(utils.url_join_encode(
                        base_url,
                        'notebooks',
                        path,
                        notebook_name));
            },
            error : $.proxy(new_notebook_failed, this),
        };
        var url = utils.url_join_encode(
            base_url,
            'api/notebooks',
            path
        );
        $.ajax(url, settings);
    };

    var new_notebook_failed = function (xhr, status, error) {
        utils.log_ajax_error(xhr, status, error);
        var msg;
        if (xhr.responseJSON && xhr.responseJSON.message) {
            msg = xhr.responseJSON.message;
        } else {
            msg = xhr.statusText;
        }
        IPython.dialog.modal({
            title : 'Creating Notebook Failed',
            body : "The error was: " + msg,
            buttons : {'OK' : {'class' : 'btn-primary'}}
        });
    }
//});
});

}).call(this);<commit_msg>Move tab-directory to js<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

var utils = IPython.utils;

require(["base/js/events"], function (events) {

    // IPython.load_extensions('module-sidebar/module-sidebar');
    // IPython.load_extensions('module-tabs/module-tabs');
    //IPython.load_extensions('module-tree/module-tree');
});

require(["custom/module-directory"],
		function (events) {

});<|endoftext|>


<commit_before>var win = Ti.UI.createWindow({
	backgroundColor: '#fff'
});
var button = Ti.UI.createButton({
	title: 'button'
});
win.add(button);

for (var i = 0; i < 10; i++) {
	win.add(Ti.UI.createView({
		height: Math.random() * Ti.Platform.displayCaps.platformHeight,
		width: Math.random() * Ti.Platform.displayCaps.platformWidth,
		left: Math.random() * Ti.Platform.displayCaps.platformWidth,
		top: Math.random() * Ti.Platform.displayCaps.platformHeight,
		backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16)
	}));
}

win.open();

win.children.length;<commit_msg>stop the color warnings<commit_after>var win = Ti.UI.createWindow({
	backgroundColor: '#fff'
});
var button = Ti.UI.createButton({
	title: 'button'
});
win.add(button);

for (var i = 0; i < 10; i++) {
	var color = '#'+Math.floor(Math.random()*16777215).toString(16);
	while (color.length < 7) { color = color.substr(0,1) + '0' + color.substr(1); }

	win.add(Ti.UI.createView({
		height: Math.random() * Ti.Platform.displayCaps.platformHeight,
		width: Math.random() * Ti.Platform.displayCaps.platformWidth,
		left: Math.random() * Ti.Platform.displayCaps.platformWidth,
		top: Math.random() * Ti.Platform.displayCaps.platformHeight,
		backgroundColor: color
	}));
}

win.open();

win.children.length;<|endoftext|>


<commit_before>/*
 * Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import StandardDialect from './standard/StandardDialect';

import {flatten}                  from '@ultraq/array-utils';
import {merge}                    from '@ultraq/object-utils';
import fs                         from 'fs';
import {jsdom, serializeDocument} from 'jsdom';

const DEFAULT_CONFIGURATION = {
	dialects: [
		new StandardDialect()
	]
};
const XML_NAMESPACE_ATTRIBUTE = 'xmlns:th';

/**
 * A highly-configurable class responsible for processing the Thymeleaf
 * directives found in HTML documents and fragments.
 *
 * @author Emanuel Rabina
 */
export default class TemplateEngine {

	/**
	 * Constructor, set up a new template engine instance.
	 *
	 * @param {Array} dialects
	 *   List of dialects to use in the new template engine.  Defaults to just the
	 *   standard dialect.
	 */
	constructor({ dialects } = DEFAULT_CONFIGURATION) {

		// Create the engine's instance of processors from all of the configured
		// dialect processors
		this.processors = flatten(dialects.map(dialect => dialect.processors));
	}

	/**
	 * Process a DOM element.
	 *
	 * @param {Element} element
	 * @param {Object} context
	 */
	processNode(element, context) {

		// TODO: Standardize this data attribute somewhere.  Shared const?
		let localVariables = JSON.parse(element.dataset.localVariables);
		let localContext = merge({}, context, localVariables);

		// Process the current element
		this.processors.forEach(processor => {
			let attribute = `${processor.prefix}:${processor.name}`;
			if (!(attribute in element)) {
				attribute = `data-${processor.prefix}-${processor.name}`;
				if (!(attribute in element)) {
					return;
				}
			}
			let attributeValue = element[attribute];
			processor.process(element, attribute, attributeValue, localContext);
		});

		// Process this element's children
		Array.from(element.children).forEach(child => {
			this.processNode(child, localContext);
		});
	}

	/**
	 * Process the Thymeleaf template data, returning the processed template.
	 *
	 * @param {String} template
	 * @param {Object} context
	 * @return {Promise}
	 *   A promise resolved with the processed template, or rejected with an error
	 *   message.
	 */
	process(template, context) {

		return new Promise((resolve, reject) => {
			try {
				let document = jsdom(template, {
					features: {
						FetchExternalResources: false,
						ProcessExternalResources: false
					}
				});

				let htmlElement = document.documentElement;
				this.processNode(htmlElement, context);

				// TODO: Special case, remove the xmlns:th namespace from the document.
				//       This should be handled like in main Thymeleaf where it's just
				//       another processor that runs on the document.
				if (htmlElement.hasAttribute(XML_NAMESPACE_ATTRIBUTE)) {
					htmlElement.removeAttribute(XML_NAMESPACE_ATTRIBUTE);
				}

				let documentAsString = serializeDocument(document);
				resolve(documentAsString);
			}
			catch (exception) {
				reject(exception);
			}
		});
	}

	/**
	 * Process the Thymeleaf template at the given path, returning a promise of the
	 * processed template.
	 *
	 * @param {String} filePath
	 * @param {Object} context
	 * @return {Promise}
	 *   A promise resolved with the processed template, or rejected with an error
	 *   message.
	 */
	processFile(filePath, context) {

		return new Promise((resolve, reject) => {
			fs.readFile(filePath, (error, data) => {
				if (error) {
					reject(new Error(error));
				}
				else {
					resolve(this.process(data, context));
				}
			});
		});
	}
}
<commit_msg>Undo using 'in' - doesn't always work for attributes<commit_after>/*
 * Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import StandardDialect from './standard/StandardDialect';

import {flatten}                  from '@ultraq/array-utils';
import {merge}                    from '@ultraq/object-utils';
import fs                         from 'fs';
import {jsdom, serializeDocument} from 'jsdom';

const DEFAULT_CONFIGURATION = {
	dialects: [
		new StandardDialect()
	]
};
const XML_NAMESPACE_ATTRIBUTE = 'xmlns:th';

/**
 * A highly-configurable class responsible for processing the Thymeleaf
 * directives found in HTML documents and fragments.
 *
 * @author Emanuel Rabina
 */
export default class TemplateEngine {

	/**
	 * Constructor, set up a new template engine instance.
	 *
	 * @param {Array} dialects
	 *   List of dialects to use in the new template engine.  Defaults to just the
	 *   standard dialect.
	 */
	constructor({ dialects } = DEFAULT_CONFIGURATION) {

		// Create the engine's instance of processors from all of the configured
		// dialect processors
		this.processors = flatten(dialects.map(dialect => dialect.processors));
	}

	/**
	 * Process a DOM element.
	 *
	 * @param {Element} element
	 * @param {Object} context
	 */
	processNode(element, context) {

		// TODO: Standardize this data attribute somewhere.  Shared const?
		let {dataset} = element;
		let localVariables = dataset ? JSON.parse(dataset.localVariables) : {};
		let localContext = merge({}, context, localVariables);

		// Process the current element
		this.processors.forEach(processor => {
			let attribute = `${processor.prefix}:${processor.name}`;
			if (!element.hasAttribute(attribute)) {
				attribute = `data-${processor.prefix}-${processor.name}`;
				if (!element.hasAttribute(attribute)) {
					return;
				}
			}
			let attributeValue = element.getAttribute(attribute);
			processor.process(element, attribute, attributeValue, localContext);
		});

		// Process this element's children
		Array.from(element.children).forEach(child => {
			this.processNode(child, localContext);
		});
	}

	/**
	 * Process the Thymeleaf template data, returning the processed template.
	 *
	 * @param {String} template
	 * @param {Object} context
	 * @return {Promise}
	 *   A promise resolved with the processed template, or rejected with an error
	 *   message.
	 */
	process(template, context) {

		return new Promise((resolve, reject) => {
			try {
				let document = jsdom(template, {
					features: {
						FetchExternalResources: false,
						ProcessExternalResources: false
					}
				});

				let htmlElement = document.documentElement;
				this.processNode(htmlElement, context);

				// TODO: Special case, remove the xmlns:th namespace from the document.
				//       This should be handled like in main Thymeleaf where it's just
				//       another processor that runs on the document.
				if (htmlElement.hasAttribute(XML_NAMESPACE_ATTRIBUTE)) {
					htmlElement.removeAttribute(XML_NAMESPACE_ATTRIBUTE);
				}

				let documentAsString = serializeDocument(document);
				resolve(documentAsString);
			}
			catch (exception) {
				reject(exception);
			}
		});
	}

	/**
	 * Process the Thymeleaf template at the given path, returning a promise of the
	 * processed template.
	 *
	 * @param {String} filePath
	 * @param {Object} context
	 * @return {Promise}
	 *   A promise resolved with the processed template, or rejected with an error
	 *   message.
	 */
	processFile(filePath, context) {

		return new Promise((resolve, reject) => {
			fs.readFile(filePath, (error, data) => {
				if (error) {
					reject(new Error(error));
				}
				else {
					resolve(this.process(data, context));
				}
			});
		});
	}
}
<|endoftext|>


<commit_before>///////////////////   Parameters   /////////////////

var width = 1366,
    height = 700,
    paperMinRadius = 5,
    paperMaxRadius = 15,
    paperOutlineWidth = 4,	// this divided by 2 must be > min radius
    paperMarginBottom = 5,
    titleBaselineOffset = 6;

var colors={
	"blue":"#00A1CB",
	"green":"#61AE24",
	"pink":"#D70060",
	"orange":"#F18D05",
	"darkblue":"#113F8C",
	"turquoise":"#01A4A4",	// not to be used for the nodes
	"red":"#E54028",	// not to be used for the nodes
	"darkgray":"#616161"	// not to be used for the nodes
}

var currentYear=2010;

////////////////	Global variables    //////////////

var view=2;	// 0=core, 1=to read, 2=fringe

////////////////	Main rendering      //////////////

// I'm not sure what was the point of .select("body").append("svg") instead of select("svg")...
var svg = d3.select("body").append("svg");

d3.tsv("data/SmallDataset.tsv", function(data){
	console.log(data);

    var papers = svg.selectAll("paper")
    	.data(data)
    .enter()
    .append("g")
    	.attr("class","paper")

    papers.append("circle")
    	.attr("class", "node")
    	.attr("cx", function(d,i) { return fringePaperX(i);})
    	.attr("cy", function(d,i) { return fringePaperY(i);})
    	.attr("r", function(d,i) {return radius(d.year);})
    	.attr("fill",randomColor);

   	papers.append("circle")
    	.attr("cx", function(d,i) { return fringePaperX(i);})
    	.attr("cy", function(d,i) {return fringePaperY(i);})
    	.attr("r", function(d,i) {return radius(d.year)*.4;})
    	.attr("fill","white");

    papers.append("text")
    	.attr("class", "title")
    	.attr("x", 2*paperMaxRadius)
    	.attr("y", function(d,i) {return paperMaxRadius+titleBaselineOffset+i*(2*paperMaxRadius+paperMarginBottom);})
    	.text(function(d,i) {return d.title;});

    // sidebar
/*    svg.append("rect")
    	.attr("x","")
    	.attr("y","0")
    	.attr("width","100")
    	.attr("height","100%")
    	.attr("fill",colors.darkgray);*/
});

////////////////	Helper functions    //////////////

// Compute X coordinate for the i-th paper on the fringe
function fringePaperX(){
	return paperMaxRadius;
}

// Compute Y coordinate for the i-th paper on the fringe
function fringePaperY(i){
	return paperMaxRadius+i*(2*paperMaxRadius+paperMarginBottom);
}

// Compute a node radius from the value supplied, between min and max
// If we want to display an outline instead of a fill circle, the radius must be smaller
function radius(value){
	return Math.max(paperMinRadius, Math.min(paperMaxRadius,
		currentYear-value));
}

// Return a random color except red or turquoise
function randomColor(){
	var keys=Object.keys(colors);
	return colors[keys[ (keys.length-2) * Math.random() << 0]];
}<commit_msg>display core and move away fringe<commit_after>///////////////////   Parameters   /////////////////

var paperMinRadius = 5,
    paperMaxRadius = 15,
    paperInnerWhiteCircleRatio =.4,
    paperOutlineWidth = 4,	// UNUSED - this divided by 2 must be > min radius
    paperMarginBottom = 5,
    titleBaselineOffset = 6;

// horizontal sizes of the different regions based on the current view (core, toread, fringe)
var coreSize = [1000,200,150],
	toreadSize = [200,1000,250];

var colors={
	"blue":"#00A1CB",
	"green":"#61AE24",
	"pink":"#D70060",
	"orange":"#F18D05",
	"darkblue":"#113F8C",
	"turquoise":"#01A4A4",	// not to be used for the nodes
	"red":"#E54028",	// not to be used for the nodes
	"darkgray":"#616161"	// not to be used for the nodes
}

var currentYear=2010;

////////////////	Global variables    //////////////

var view=2;	// 0=core, 1=to read, 2=fringe

////////////////	Main rendering      //////////////

// I'm not sure what was the point of .select("body").append("svg") instead of select("svg")...
var svg = d3.select("body").append("svg");

d3.tsv("data/SmallDataset.tsv", function(data){
	console.log(data);

	// fringe

    var papers = svg.selectAll("paper")
    	.data(data)
    .enter()
    .append("g")
    	.attr("class","paper")

    papers.append("circle")
    	.attr("class", "node")
    	.attr("cx", function(d,i) { return fringePaperX(i);} )
    	.attr("cy", function(d,i) { return fringePaperY(i);} )
    	.attr("r", function(d,i) {return radius(d.year);} )
    	.attr("fill",randomColor);

   	papers.append("circle")
    	.attr("cx", function(d,i) { return fringePaperX(i);} )
    	.attr("cy", function(d,i) {return fringePaperY(i);} )
    	.attr("r", function(d,i) {return radius(d.year)*paperInnerWhiteCircleRatio;} )
    	.attr("fill","white");

    papers.append("text")
    	.attr("class", "title")
    	.attr("x", function(d,i) { return fringePaperX(i)+paperMaxRadius;} )
    	.attr("y", function(d,i) {return paperMaxRadius+titleBaselineOffset+i*(2*paperMaxRadius+paperMarginBottom);} )
    	.text(function(d,i) {return d.title;} );

    // core

    svg.append("circle")
    	.attr("cx",0)
    	.attr("cy","50%")
    	.attr("r",coreSize[view])
    	.attr("fill",colors.red);

    // sidebar
/*    svg.append("rect")
    	.attr("x","")
    	.attr("y","0")
    	.attr("width","100")
    	.attr("height","100%")
    	.attr("fill",colors.darkgray);*/
});

////////////////	Helper functions    //////////////

// Compute X coordinate for the i-th paper on the fringe
function fringePaperX(i){
	return coreSize[view]+toreadSize[view]+paperMaxRadius;
}

// Compute Y coordinate for the i-th paper on the fringe
function fringePaperY(i){
	return paperMaxRadius+i*(2*paperMaxRadius+paperMarginBottom);
}

// Compute a node radius from the value supplied, between min and max
// If we want to display an outline instead of a fill circle, the radius must be smaller
function radius(value){
	return Math.max(paperMinRadius, Math.min(paperMaxRadius,
		currentYear-value));
}

// Return a random color except red or turquoise
function randomColor(){
	var keys=Object.keys(colors);
	return colors[keys[ (keys.length-2) * Math.random() << 0]];
}<|endoftext|>


<commit_before>/**
 Copyright (c) 2016,2017,2018,2019,2020 Klaus Landsdorf (https://bianco-royal.com/)
 All rights reserved.
 node-red-contrib-modbus - The BSD 3-Clause License

 @author Klaus Landsdorf (Bianco Royal)
 **/
'use strict'
// SOURCE-MAP-REQUIRED

var de = de || { biancoroyal: { modbus: { basics: {} } } } // eslint-disable-line no-use-before-define
de.biancoroyal.modbus.basics.internalDebug = de.biancoroyal.modbus.basics.internalDebug || require('debug')('contribModbus:basics') // eslint-disable-line no-use-before-define
de.biancoroyal.modbus.basics.util = de.biancoroyal.modbus.basics.util || require('util') // eslint-disable-line no-use-before-define

/**
 * Modbus core node basics.
 * @module NodeRedModbusBasics
 */
de.biancoroyal.modbus.basics.statusLog = false
/**
 *
 * @param unit
 * @returns {string}
 */
de.biancoroyal.modbus.basics.get_timeUnit_name = function (unit) {
  let unitAbbreviation = ''

  switch (unit) {
    case 'ms':
      unitAbbreviation = 'msec.'
      break
    case 's':
      unitAbbreviation = 'sec.'
      break
    case 'm':
      unitAbbreviation = 'min.'
      break
    case 'h':
      unitAbbreviation = 'h.'
      break
    default:
      break
  }

  return unitAbbreviation
}

de.biancoroyal.modbus.basics.calc_rateByUnit = function (rate, rateUnit) {
  switch (rateUnit) {
    case 'ms':
      break
    case 's':
      rate = parseInt(rate) * 1000 // seconds
      break
    case 'm':
      rate = parseInt(rate) * 60000 // minutes
      break
    case 'h':
      rate = parseInt(rate) * 3600000 // hours
      break
    default:
      rate = 10000 // 10 sec.
      break
  }

  return rate
}
/**
 *
 * @param statusValue
 * @param showActivities
 * @returns {{fill: string, shape: string, status: *}}
 */
de.biancoroyal.modbus.basics.setNodeStatusProperties = function (statusValue, showActivities) {
  let fillValue = 'yellow'
  let shapeValue = 'ring'

  if (!statusValue) {
    statusValue = 'waiting'
  }

  let statusText = statusValue.value || statusValue

  switch (statusText) {
    case 'connecting':
      fillValue = 'yellow'
      shapeValue = 'ring'
      break

    case 'error':
      fillValue = 'red'
      shapeValue = 'ring'
      break

    case 'initialized':
    case 'init':
      fillValue = 'yellow'
      shapeValue = 'dot'
      break

    case 'not ready to read':
    case 'not ready to write':
      fillValue = 'yellow'
      shapeValue = 'ring'
      break

    case 'connected':
    case 'queueing':
    case 'queue':
      fillValue = 'green'
      shapeValue = 'ring'
      break

    case 'timeout':
      fillValue = 'red'
      shapeValue = 'ring'
      break

    case 'active':
    case 'reading':
    case 'writing':
    case 'active reading':
    case 'active writing':
      if (!showActivities) {
        statusText = 'active'
      }
      fillValue = 'green'
      shapeValue = 'dot'
      break

    case 'disconnected':
    case 'terminated':
      fillValue = 'red'
      shapeValue = 'ring'
      break

    case 'stopped':
      fillValue = 'red'
      shapeValue = 'dot'
      break

    case 'polling':
      fillValue = 'green'
      if (showActivities) {
        shapeValue = 'ring'
      } else {
        statusText = 'active'
        shapeValue = 'dot'
      }
      break

    default:
      if (statusText === 'waiting') {
        fillValue = 'blue'
        statusText = 'waiting ...'
      }
      break
  }

  return { fill: fillValue, shape: shapeValue, status: statusText }
}

de.biancoroyal.modbus.basics.setNodeStatusByResponseTo = function (statusValue, response, node) {
  let fillValue = 'red'
  let shapeValue = 'dot'

  switch (statusValue) {
    case 'initialized':
    case 'queue':
      fillValue = 'green'
      shapeValue = 'ring'
      break

    case 'active':
      fillValue = 'green'
      shapeValue = 'dot'
      break

    default:
      if (!statusValue || statusValue === 'waiting') {
        fillValue = 'blue'
        statusValue = 'waiting ...'
      }
      break
  }

  node.status({ fill: fillValue, shape: shapeValue, text: this.util.inspect(response, false, null) })
}

de.biancoroyal.modbus.basics.setNodeStatusResponse = function (length, node) {
  node.status({
    fill: 'green',
    shape: 'dot',
    text: 'active got length: ' + length
  })
}

de.biancoroyal.modbus.basics.setModbusError = function (node, modbusClient, err, msg) {
  if (err) {
    switch (err.message) {
      case 'Timed out':
        this.setNodeStatusTo('timeout', node)
        break
      case 'FSM Not Ready To Reconnect':
        this.setNodeStatusTo('not ready to reconnect', node)
        break
      case 'Port Not Open':
        this.setNodeStatusTo('reconnect', node)
        modbusClient.emit('reconnect')
        break
      default:
        this.internalDebug(err.message)
        if (node.showErrors) {
          this.setNodeStatusTo('error ' + err.message, node)
        }
    }
  }
}

de.biancoroyal.modbus.basics.setNodeStatusTo = function (statusValue, node) {
  if (node.showStatusActivities) {
    if (statusValue !== node.statusText) {
      const statusOptions = this.setNodeStatusProperties(statusValue, node.showStatusActivities)
      node.statusText = statusValue
      node.status({
        fill: statusOptions.fill,
        shape: statusOptions.shape,
        text: statusOptions.status
      })
    } else {
      this.setNodeDefaultStatus()
    }
  }
}

de.biancoroyal.modbus.basics.onModbusInit = function (node) {
  this.setNodeStatusTo('initialize', node)
}

de.biancoroyal.modbus.basics.onModbusConnect = function (node) {
  this.setNodeStatusTo('connected', node)
}

de.biancoroyal.modbus.basics.onModbusActive = function (node) {
  this.setNodeStatusTo('active', node)
}

de.biancoroyal.modbus.basics.onModbusError = function (node, failureMsg) {
  this.setNodeStatusTo('failure', node)
  if (node.showErrors) {
    node.warn(failureMsg)
  }
}

de.biancoroyal.modbus.basics.onModbusClose = function (node) {
  this.setNodeStatusTo('closed', node)
}

de.biancoroyal.modbus.basics.onModbusQueue = function (node) {
  this.setNodeStatusTo('queueing', node)
}

de.biancoroyal.modbus.basics.onModbusBroken = function (node, modbusClient) {
  this.setNodeStatusTo('reconnecting after ' + modbusClient.reconnectTimeout + ' msec.', node)
}

de.biancoroyal.modbus.basics.setNodeDefaultStatus = function (node) {
  node.status({ fill: 'green', shape: 'ring', text: 'active' })
}

de.biancoroyal.modbus.basics.initModbusClientEvents = function (node, modbusClient) {
  if (node.showStatusActivities) {
    modbusClient.on('mbinit', () => { this.onModbusInit(node) })
    modbusClient.on('mbqueue', () => { this.onModbusQueue(node) })
    modbusClient.on('mbconnected', () => { this.onModbusConnect(node) })
    modbusClient.on('mbbroken', () => { this.onModbusBroken(node, modbusClient) })
    modbusClient.on('mbactive', () => { this.onModbusActive(node) })
    modbusClient.on('mberror', (failureMsg) => { this.onModbusError(node, failureMsg) })
    modbusClient.on('mbclosed', () => { this.onModbusClose(node) })
  } else {
    this.setNodeDefaultStatus(node)
  }
}

de.biancoroyal.modbus.basics.invalidPayloadIn = function (msg) {
  return !(msg && Object.prototype.hasOwnProperty.call(msg, 'payload'))
}

de.biancoroyal.modbus.basics.sendEmptyMsgOnFail = function (node, err, msg) {
  if (node.emptyMsgOnFail) {
    msg.payload = ''

    if (err && err.message && err.name) {
      msg.error = err
    } else {
      msg.error = Error(err)
    }
    msg.error.nodeStatus = node.statusText

    node.send([msg, msg])
  }
}

de.biancoroyal.modbus.basics.logMsgError = function (node, err, msg) {
  if (node.showErrors) {
    node.error(err, msg)
  }
}

de.biancoroyal.modbus.basics.buildNewMessage = function (keepMsgProperties, msg, minMsg) {
  if (keepMsgProperties) {
    return Object.assign(msg, minMsg)
  } else {
    return minMsg
  }
}

module.exports = de.biancoroyal.modbus.basics
<commit_msg>fix(basics): #210 missing parameter node<commit_after>/**
 Copyright (c) 2016,2017,2018,2019,2020 Klaus Landsdorf (https://bianco-royal.com/)
 All rights reserved.
 node-red-contrib-modbus - The BSD 3-Clause License

 @author Klaus Landsdorf (Bianco Royal)
 **/
'use strict'
// SOURCE-MAP-REQUIRED

var de = de || { biancoroyal: { modbus: { basics: {} } } } // eslint-disable-line no-use-before-define
de.biancoroyal.modbus.basics.internalDebug = de.biancoroyal.modbus.basics.internalDebug || require('debug')('contribModbus:basics') // eslint-disable-line no-use-before-define
de.biancoroyal.modbus.basics.util = de.biancoroyal.modbus.basics.util || require('util') // eslint-disable-line no-use-before-define

/**
 * Modbus core node basics.
 * @module NodeRedModbusBasics
 */
de.biancoroyal.modbus.basics.statusLog = false
/**
 *
 * @param unit
 * @returns {string}
 */
de.biancoroyal.modbus.basics.get_timeUnit_name = function (unit) {
  let unitAbbreviation = ''

  switch (unit) {
    case 'ms':
      unitAbbreviation = 'msec.'
      break
    case 's':
      unitAbbreviation = 'sec.'
      break
    case 'm':
      unitAbbreviation = 'min.'
      break
    case 'h':
      unitAbbreviation = 'h.'
      break
    default:
      break
  }

  return unitAbbreviation
}

de.biancoroyal.modbus.basics.calc_rateByUnit = function (rate, rateUnit) {
  switch (rateUnit) {
    case 'ms':
      break
    case 's':
      rate = parseInt(rate) * 1000 // seconds
      break
    case 'm':
      rate = parseInt(rate) * 60000 // minutes
      break
    case 'h':
      rate = parseInt(rate) * 3600000 // hours
      break
    default:
      rate = 10000 // 10 sec.
      break
  }

  return rate
}
/**
 *
 * @param statusValue
 * @param showActivities
 * @returns {{fill: string, shape: string, status: *}}
 */
de.biancoroyal.modbus.basics.setNodeStatusProperties = function (statusValue, showActivities) {
  let fillValue = 'yellow'
  let shapeValue = 'ring'

  if (!statusValue) {
    statusValue = 'waiting'
  }

  let statusText = statusValue.value || statusValue

  switch (statusText) {
    case 'connecting':
      fillValue = 'yellow'
      shapeValue = 'ring'
      break

    case 'error':
      fillValue = 'red'
      shapeValue = 'ring'
      break

    case 'initialized':
    case 'init':
      fillValue = 'yellow'
      shapeValue = 'dot'
      break

    case 'not ready to read':
    case 'not ready to write':
      fillValue = 'yellow'
      shapeValue = 'ring'
      break

    case 'connected':
    case 'queueing':
    case 'queue':
      fillValue = 'green'
      shapeValue = 'ring'
      break

    case 'timeout':
      fillValue = 'red'
      shapeValue = 'ring'
      break

    case 'active':
    case 'reading':
    case 'writing':
    case 'active reading':
    case 'active writing':
      if (!showActivities) {
        statusText = 'active'
      }
      fillValue = 'green'
      shapeValue = 'dot'
      break

    case 'disconnected':
    case 'terminated':
      fillValue = 'red'
      shapeValue = 'ring'
      break

    case 'stopped':
      fillValue = 'red'
      shapeValue = 'dot'
      break

    case 'polling':
      fillValue = 'green'
      if (showActivities) {
        shapeValue = 'ring'
      } else {
        statusText = 'active'
        shapeValue = 'dot'
      }
      break

    default:
      if (statusText === 'waiting') {
        fillValue = 'blue'
        statusText = 'waiting ...'
      }
      break
  }

  return { fill: fillValue, shape: shapeValue, status: statusText }
}

de.biancoroyal.modbus.basics.setNodeStatusByResponseTo = function (statusValue, response, node) {
  let fillValue = 'red'
  let shapeValue = 'dot'

  switch (statusValue) {
    case 'initialized':
    case 'queue':
      fillValue = 'green'
      shapeValue = 'ring'
      break

    case 'active':
      fillValue = 'green'
      shapeValue = 'dot'
      break

    default:
      if (!statusValue || statusValue === 'waiting') {
        fillValue = 'blue'
        statusValue = 'waiting ...'
      }
      break
  }

  node.status({ fill: fillValue, shape: shapeValue, text: this.util.inspect(response, false, null) })
}

de.biancoroyal.modbus.basics.setNodeStatusResponse = function (length, node) {
  node.status({
    fill: 'green',
    shape: 'dot',
    text: 'active got length: ' + length
  })
}

de.biancoroyal.modbus.basics.setModbusError = function (node, modbusClient, err, msg) {
  if (err) {
    switch (err.message) {
      case 'Timed out':
        this.setNodeStatusTo('timeout', node)
        break
      case 'FSM Not Ready To Reconnect':
        this.setNodeStatusTo('not ready to reconnect', node)
        break
      case 'Port Not Open':
        this.setNodeStatusTo('reconnect', node)
        modbusClient.emit('reconnect')
        break
      default:
        this.internalDebug(err.message)
        if (node.showErrors) {
          this.setNodeStatusTo('error ' + err.message, node)
        }
    }
  }
}

de.biancoroyal.modbus.basics.setNodeStatusTo = function (statusValue, node) {
  if (node.showStatusActivities) {
    if (statusValue !== node.statusText) {
      const statusOptions = this.setNodeStatusProperties(statusValue, node.showStatusActivities)
      node.statusText = statusValue
      node.status({
        fill: statusOptions.fill,
        shape: statusOptions.shape,
        text: statusOptions.status
      })
    } else {
      this.setNodeDefaultStatus(node)
    }
  }
}

de.biancoroyal.modbus.basics.onModbusInit = function (node) {
  this.setNodeStatusTo('initialize', node)
}

de.biancoroyal.modbus.basics.onModbusConnect = function (node) {
  this.setNodeStatusTo('connected', node)
}

de.biancoroyal.modbus.basics.onModbusActive = function (node) {
  this.setNodeStatusTo('active', node)
}

de.biancoroyal.modbus.basics.onModbusError = function (node, failureMsg) {
  this.setNodeStatusTo('failure', node)
  if (node.showErrors) {
    node.warn(failureMsg)
  }
}

de.biancoroyal.modbus.basics.onModbusClose = function (node) {
  this.setNodeStatusTo('closed', node)
}

de.biancoroyal.modbus.basics.onModbusQueue = function (node) {
  this.setNodeStatusTo('queueing', node)
}

de.biancoroyal.modbus.basics.onModbusBroken = function (node, modbusClient) {
  this.setNodeStatusTo('reconnecting after ' + modbusClient.reconnectTimeout + ' msec.', node)
}

de.biancoroyal.modbus.basics.setNodeDefaultStatus = function (node) {
  node.status({ fill: 'green', shape: 'ring', text: 'active' })
}

de.biancoroyal.modbus.basics.initModbusClientEvents = function (node, modbusClient) {
  if (node.showStatusActivities) {
    modbusClient.on('mbinit', () => { this.onModbusInit(node) })
    modbusClient.on('mbqueue', () => { this.onModbusQueue(node) })
    modbusClient.on('mbconnected', () => { this.onModbusConnect(node) })
    modbusClient.on('mbbroken', () => { this.onModbusBroken(node, modbusClient) })
    modbusClient.on('mbactive', () => { this.onModbusActive(node) })
    modbusClient.on('mberror', (failureMsg) => { this.onModbusError(node, failureMsg) })
    modbusClient.on('mbclosed', () => { this.onModbusClose(node) })
  } else {
    this.setNodeDefaultStatus(node)
  }
}

de.biancoroyal.modbus.basics.invalidPayloadIn = function (msg) {
  return !(msg && Object.prototype.hasOwnProperty.call(msg, 'payload'))
}

de.biancoroyal.modbus.basics.sendEmptyMsgOnFail = function (node, err, msg) {
  if (node.emptyMsgOnFail) {
    msg.payload = ''

    if (err && err.message && err.name) {
      msg.error = err
    } else {
      msg.error = Error(err)
    }
    msg.error.nodeStatus = node.statusText

    node.send([msg, msg])
  }
}

de.biancoroyal.modbus.basics.logMsgError = function (node, err, msg) {
  if (node.showErrors) {
    node.error(err, msg)
  }
}

de.biancoroyal.modbus.basics.buildNewMessage = function (keepMsgProperties, msg, minMsg) {
  if (keepMsgProperties) {
    return Object.assign(msg, minMsg)
  } else {
    return minMsg
  }
}

module.exports = de.biancoroyal.modbus.basics
<|endoftext|>


<commit_before>/**
 * FN is a functional library providing functions
 * inspired (ripped off) by LISP/Clojure.
 *
 * No, I have no shame.
 *
 * This is kinda just research, experimenting with
 * functional programming in JS. If you however
 * find this library useful let me know and I'll
 * keep working on it, if you have suggestions, I
 * might even incorporate your ideas.
 *
 * This is designed to be used from within ES6.
 * Other older versions of ES may not work properly.
 *
 * Copyright (c) Neil Munro 2015-2016.
 * @constructor
 * @author Neil Munro <neilmunro@gmail.com>
 */

const FN = Object.create({
  "version": "0.0.1",
  "default": Symbol(":default"),

  /**
   * FN.any is a function which evaluates a number of
   * expressions and returns true if ANY of the expressions
   * themselves are true.
   *
   * Example(s):
   *
   * FN.any([1 === 1, 5 === 5]);
   *
   * @param {array} lst - The list of boolean expressions to FN.any.
   * @return {boolean} The result of any of the expressions being true.
   */
  "any": function(lst) {
    return lst.some(elm => elm);
  },

  /**
   * FN.all is a function which evaluates a number of
   * expressions and returns true only if ALL of the
   * expressions are themselves true.
   *
   * Example(s):
   *
   * FN.all([1 === 1, 5 === 5]);
   *
   * @param {array} lst - The list of boolean expressions to FN.all.
   * @return {boolean} The result of all of the expressions being true.
   */
  "all": function(lst) {
    return lst.every(elm => elm);
  },

  /**
   * FN.first returns the first element of a list.
   *
   * Example(s):
   *
   * FN.first([1, 2, 3, 4, 5]);
   *
   * @param {array} lst - The list to get the first element of.
   * @return {(object|undefined)} The first element of the list or undefined.
   */
  "first": function(lst) {
    return (lst[0] !== undefined) ? lst[0] : undefined;
  },

  /**
   * FN.last is the inverse of FN.first and returns the final element in a list.
   *
   * Example(s):
   *
   * FN.last([1, 2, 3, 4, 5]);
   *
   * @param {array} lst - The arguments to FN.last.
   * @return {(object|undefined)} The last element of the list or undefined.
   * @see FN.first
   */
  "last": function(lst) {
    return (lst[lst.length-1] !== undefined) ? lst[lst.length-1] : undefined;
  },

  /**
   * FN.nth complements FN.first and FN.last by providing
   * a means to grab an arbitrary element in a list by numeric
   * index.
   *
   * Example(s):
   *
   * FN.nth([1, 2, 3, 4, 5], 2);
   *
   * @param {array} lst - The list to get the nth element of.
   * @param {number} n - The nth element in the list to try and get.
   * @return {(object|undefined)} The nth element of the list or undefined.
   * @see FN.first
   * @see FN.last
   */
  "nth": function(lst, n) {
    return(lst[n] !== undefined) ? lst[n] : undefined;
  },

  /**
   * FN.rest complements FN.first by passing everything
   * execept the first element into a callback.
   *
   * Example(s):
   *
   * FN.rest([1, 2, 3, 4, 5]);
   *
   * @param {array} lst - The arguments to FN.rest.
   * @return {(array|undefined)} The rest of the list or undefined.
   * @see FN.first
   */
  "rest": function(lst) {
    return(lst !== undefined && lst.length > 1) ? lst.slice(1) : undefined;
  },

  /**
   * FN.take returns a new list from the n number of elements from the
   * list passed into it.
   *
   * Example(s):
   *
   * FN.take(["Lions", "Tigers", "Bears"], 2);
   *
   * FN.take(FN.range(10, 0, 2), 2);
   *
   * @param {array} lst - The arguments to FN.take.
   * @param {number} n - The number of elements to take from the array lst.
   * @return {array} A new list made up of the n number of elements, if n is bigger than the list the whole list is returned.
   */
  "take": function(lst, n) {
    return lst.filter((element, index) => n >= index+1);
  },

  /**
   * FN.if is a single branch function. It expects a
   * callback and a single boolean expression.
   *
   * NOTE: FN.any and FN.all can be used here.
   *
   * Example(s):
   *
   * FN.if(true, () => { console.log("Is true"); });
   *
   * FN.if(FN.any([1 === 1, 2 === 2]), () => {
   *   console.log("Is true");
   * });
   *
   * @param {boolean} cond - The single boolean expression to FN.if.
   * @param {function} cb - The callback to execute if true.
   * @return {(object|undefined)} The result of the callback or undefined.
   * @see FN.ifElse
   */
  "if": function(cond, cb) {
    return(cb !== undefined && cond) ? cb() : undefined;
  },

  /**
   * FN.ifElse expands upon FN.if by permitting the user
   * to provide a second callback function to be executed
   * in the event that the if expression evaluates to false.
   *
   * NOTE: Multiple FN.fElse can be nested inside of the callback functions.
   *
   * Example(s):
   *
   * FN.ifElse(true,
   * () => {
   *   console.log("Is true");
   * },() => {
   *  console.log("Is false");
   * });
   *
   * FN.ifElse(FN.all([1 === 1, 2 === 2]),
   * () => {
   *   console.log("Is true");
   * }, () => {
   *  console.log("Is false");
   * });
   *
   * @param {boolean} cond - The boolean expression to FN.ifElse.
   * @param {function} cb1 - The callback to execute in the form: () =>  {...} if true.
   * @param {function} cb2 - The callback to execute in the form: () =>  {...} if false.
   * @return {(object|undefined)} The result of the callback or undefined.
   * @see FN.if
   */
  "ifElse": function(cond, cb1, cb2) {
    return(cb1 !== undefined && cb2 !== undefined) ?
      (cond) ?
        cb1() :
        cb2() :
      undefined;
  },

  /**
  * FN.let creates a new isolated execution context with a set of values initilised
  * within the context and visible only for the duration of the callback function.
  * Note that it acts as a closure and does have access to outer variables.
  *
  * Example(s):
  *
  * FN.let({"age": 29, "name": "Neil Munro"}, function() {
  *   console.log("Hi my name is " + this.name + " and I am " + this.age + " years old.");
  * });
  *
  * @param {object} objectContext - An object containing the key/value pairs
  * @param {function} cb - The callback to execute in the form: function() {...}.
  * You MUST use the original function() {} form as these bind a 'this' value to
  * the scope that FN.let provides.
  * that are to be created inside the execution context.
  * @return {object} The return value of the callback function.
  * @see FN.if
  */
  "let": function(obj, cb) {
    const f = () => {
      const tmp = {};
      Object.keys(obj).forEach((key) => tmp[key] = obj[key]);
      return cb.bind(tmp)();
    };
    f();
  },

  /**
  * FN.range generates and array of numeric values based on criteria that
  * the programmer enters.
  *
  * Example(s):
  *
  * FN.range(0, 10, 1);
  *
  * @param {number=} start - The number to start from.
  * @param {number} stop - The number to go to.
  * @param {number=} step - The number of steps/intervals.
  * @return {array} The array built from lst.
  */
  "range": function(...lst) {
    var start = (lst.length > 1) ? lst[0] : 0;
    const arr = [];
    const step = (lst[2] !== undefined) ? lst[2] : 1;
    const stop = (lst[1] !== undefined) ? lst[1] : lst[0];
    const f1 = (() => { update(() => { start += step; }); });
    const f2 = (() => { update(() => { start -= step; }); });
    const update = (cb) => {
      arr.push(start);
      cb();
    };

    const func = ((stop - start) >= 0) ?
      () => { while(start <= stop) f1(); } :
      () => { while(start >= stop) f2(); };
    func();

    return arr;
  },

  /**
  * FN.cond is analogous to a switch statement. It evaluates each expression
  * in turn until it first the first one that evaluates to true and runs its
  * acompanying function.
  *
  * Example(s):
  *
  * FN.cond(
  *   1 === 2, () => { console.log("first");  },
  *   2 === 3, () => { console.log("second");  },
  *   "tmp" === "tmp", () => { console.log("third");  }
  * );
  *
  * @param {...(boolean|function)} lst - An array of expression/function pairs to evaluate/run.
  * @return {object|undefined} The result of the executed function or undefined.
  */
  "cond": function(...lst) {
    const func = ((lst.length % 2) === 0) ? (() => {
      var tmp;
      lst.forEach((element, index) => {
        // Expression is true, store the next argument (a function) for later use.
        if(((index % 2) === 0) && tmp === undefined && element) tmp = index+1;
      });
      return (lst[tmp] !== undefined) ? lst[tmp]() : undefined;
    }) : undefined;
    return(func !== undefined) ? func() : undefined;
  },

  /**
  * FN.everyOther is a function for applying the callback for every N elemet in
  * an array.
  *
  * Example(s):
  *
  * FN.everyOther((elm) => { console.log(elm);  }, [0, 1, 2, 3, 4, 5, 6], 2);
  *
  * @param {function} cb - The function to apply to n elements of the array.
  * @param {array} arr - The array containing the elements to apply the function to.
  * @param {number} step - The interval of steps to apply a function to.
  * @return {undefined} everyOther does not return anything it applies a callback for
  * every other element in a list.
  */
  "everyOther": function(arr, step, cb) {
    arr.forEach((element, index) => {
      if(((index+1) % step) === 0) cb(element);
    });
  },

  /**
   * FN.case is a function that evaluates a set of conditions against a sentinal
   * condition, the acompanying function is ran. A default condition can be passed
   * and a final callback passed for the default condition.
   *
   * Example(s):
   *
   * FN.case(9, 1, () => 1*2, 2, () => 2*2, 3, () => 3*2, FN.default, () => 19);
   *
   * @param {(number|string)} val - The sentinal condition.
   * @param {...(number|string|boolean|function)} lst - The condition/function pairs to check against the sentinal
   * and execute, if true.
   * @return {(object|undefined)} The result of the executed function or undefined.
   */
  "case": function(val, ...lst) {
    const func = ((lst.length % 2) === 0) ? (() => {
      var found;
      var defaultCase;
      lst.forEach((element, index) => {
        if(((index % 2) === 0) && found === undefined && element === val) found = index+1;
        else if(element === this.default) defaultCase = lst[index+1];
      });

      return(lst[found] !== undefined) ?
        lst[found]() :
        (defaultCase !== undefined) ?
          defaultCase() :
          undefined;
    }) : undefined;
    return(func !== undefined) ? func() : undefined;
  },

  /**
   * FN.sum is a function that takes a variable number of arguments and returns
   * the sum of all arguments all arguments must be numbers, if not undefined
   * is returned.
   *
   * Example(s):
   *
   * FN.sum([1, 2, 3, 4, 5]);
   *
   * @param {array} lst The list of numbers to sum.
   * @return {number|undefined} The sum of the provided arguments.
   */
  "sum": function(lst) {
    return(lst.every(elm => (typeof elm === "number"))) ?
      lst.reduce((prev, curr) => prev + curr) :
      undefined;
  },

  /**
   * FN.isOdd is a function that determines if a number is odd, or not.
   *
   * Example(s):
   *
   * FN.isOdd(1);
   *
   * @param {number} num The number to test.
   * @return {boolean} The oddity of the number.
   */
  "isOdd": (num) => {
    return num % 2 !== 0;
  }
});<commit_msg>Fixed the isOdd function.<commit_after>/**
 * FN is a functional library providing functions
 * inspired (ripped off) by LISP/Clojure.
 *
 * No, I have no shame.
 *
 * This is kinda just research, experimenting with
 * functional programming in JS. If you however
 * find this library useful let me know and I'll
 * keep working on it, if you have suggestions, I
 * might even incorporate your ideas.
 *
 * This is designed to be used from within ES6.
 * Other older versions of ES may not work properly.
 *
 * Copyright (c) Neil Munro 2015-2016.
 * @constructor
 * @author Neil Munro <neilmunro@gmail.com>
 */

const FN = Object.create({
  "version": "0.0.1",
  "default": Symbol(":default"),

  /**
   * FN.any is a function which evaluates a number of
   * expressions and returns true if ANY of the expressions
   * themselves are true.
   *
   * Example(s):
   *
   * FN.any([1 === 1, 5 === 5]);
   *
   * @param {array} lst - The list of boolean expressions to FN.any.
   * @return {boolean} The result of any of the expressions being true.
   */
  "any": function(lst) {
    return lst.some(elm => elm);
  },

  /**
   * FN.all is a function which evaluates a number of
   * expressions and returns true only if ALL of the
   * expressions are themselves true.
   *
   * Example(s):
   *
   * FN.all([1 === 1, 5 === 5]);
   *
   * @param {array} lst - The list of boolean expressions to FN.all.
   * @return {boolean} The result of all of the expressions being true.
   */
  "all": function(lst) {
    return lst.every(elm => elm);
  },

  /**
   * FN.first returns the first element of a list.
   *
   * Example(s):
   *
   * FN.first([1, 2, 3, 4, 5]);
   *
   * @param {array} lst - The list to get the first element of.
   * @return {(object|undefined)} The first element of the list or undefined.
   */
  "first": function(lst) {
    return (lst[0] !== undefined) ? lst[0] : undefined;
  },

  /**
   * FN.last is the inverse of FN.first and returns the final element in a list.
   *
   * Example(s):
   *
   * FN.last([1, 2, 3, 4, 5]);
   *
   * @param {array} lst - The arguments to FN.last.
   * @return {(object|undefined)} The last element of the list or undefined.
   * @see FN.first
   */
  "last": function(lst) {
    return (lst[lst.length-1] !== undefined) ? lst[lst.length-1] : undefined;
  },

  /**
   * FN.nth complements FN.first and FN.last by providing
   * a means to grab an arbitrary element in a list by numeric
   * index.
   *
   * Example(s):
   *
   * FN.nth([1, 2, 3, 4, 5], 2);
   *
   * @param {array} lst - The list to get the nth element of.
   * @param {number} n - The nth element in the list to try and get.
   * @return {(object|undefined)} The nth element of the list or undefined.
   * @see FN.first
   * @see FN.last
   */
  "nth": function(lst, n) {
    return(lst[n] !== undefined) ? lst[n] : undefined;
  },

  /**
   * FN.rest complements FN.first by passing everything
   * execept the first element into a callback.
   *
   * Example(s):
   *
   * FN.rest([1, 2, 3, 4, 5]);
   *
   * @param {array} lst - The arguments to FN.rest.
   * @return {(array|undefined)} The rest of the list or undefined.
   * @see FN.first
   */
  "rest": function(lst) {
    return(lst !== undefined && lst.length > 1) ? lst.slice(1) : undefined;
  },

  /**
   * FN.take returns a new list from the n number of elements from the
   * list passed into it.
   *
   * Example(s):
   *
   * FN.take(["Lions", "Tigers", "Bears"], 2);
   *
   * FN.take(FN.range(10, 0, 2), 2);
   *
   * @param {array} lst - The arguments to FN.take.
   * @param {number} n - The number of elements to take from the array lst.
   * @return {array} A new list made up of the n number of elements, if n is bigger than the list the whole list is returned.
   */
  "take": function(lst, n) {
    return lst.filter((element, index) => n >= index+1);
  },

  /**
   * FN.if is a single branch function. It expects a
   * callback and a single boolean expression.
   *
   * NOTE: FN.any and FN.all can be used here.
   *
   * Example(s):
   *
   * FN.if(true, () => { console.log("Is true"); });
   *
   * FN.if(FN.any([1 === 1, 2 === 2]), () => {
   *   console.log("Is true");
   * });
   *
   * @param {boolean} cond - The single boolean expression to FN.if.
   * @param {function} cb - The callback to execute if true.
   * @return {(object|undefined)} The result of the callback or undefined.
   * @see FN.ifElse
   */
  "if": function(cond, cb) {
    return(cb !== undefined && cond) ? cb() : undefined;
  },

  /**
   * FN.ifElse expands upon FN.if by permitting the user
   * to provide a second callback function to be executed
   * in the event that the if expression evaluates to false.
   *
   * NOTE: Multiple FN.fElse can be nested inside of the callback functions.
   *
   * Example(s):
   *
   * FN.ifElse(true,
   * () => {
   *   console.log("Is true");
   * },() => {
   *  console.log("Is false");
   * });
   *
   * FN.ifElse(FN.all([1 === 1, 2 === 2]),
   * () => {
   *   console.log("Is true");
   * }, () => {
   *  console.log("Is false");
   * });
   *
   * @param {boolean} cond - The boolean expression to FN.ifElse.
   * @param {function} cb1 - The callback to execute in the form: () =>  {...} if true.
   * @param {function} cb2 - The callback to execute in the form: () =>  {...} if false.
   * @return {(object|undefined)} The result of the callback or undefined.
   * @see FN.if
   */
  "ifElse": function(cond, cb1, cb2) {
    return(cb1 !== undefined && cb2 !== undefined) ?
      (cond) ?
        cb1() :
        cb2() :
      undefined;
  },

  /**
  * FN.let creates a new isolated execution context with a set of values initilised
  * within the context and visible only for the duration of the callback function.
  * Note that it acts as a closure and does have access to outer variables.
  *
  * Example(s):
  *
  * FN.let({"age": 29, "name": "Neil Munro"}, function() {
  *   console.log("Hi my name is " + this.name + " and I am " + this.age + " years old.");
  * });
  *
  * @param {object} objectContext - An object containing the key/value pairs
  * @param {function} cb - The callback to execute in the form: function() {...}.
  * You MUST use the original function() {} form as these bind a 'this' value to
  * the scope that FN.let provides.
  * that are to be created inside the execution context.
  * @return {object} The return value of the callback function.
  * @see FN.if
  */
  "let": function(obj, cb) {
    const f = () => {
      const tmp = {};
      Object.keys(obj).forEach((key) => tmp[key] = obj[key]);
      return cb.bind(tmp)();
    };
    f();
  },

  /**
  * FN.range generates and array of numeric values based on criteria that
  * the programmer enters.
  *
  * Example(s):
  *
  * FN.range(0, 10, 1);
  *
  * @param {number=} start - The number to start from.
  * @param {number} stop - The number to go to.
  * @param {number=} step - The number of steps/intervals.
  * @return {array} The array built from lst.
  */
  "range": function(...lst) {
    var start = (lst.length > 1) ? lst[0] : 0;
    const arr = [];
    const step = (lst[2] !== undefined) ? lst[2] : 1;
    const stop = (lst[1] !== undefined) ? lst[1] : lst[0];
    const f1 = (() => { update(() => { start += step; }); });
    const f2 = (() => { update(() => { start -= step; }); });
    const update = (cb) => {
      arr.push(start);
      cb();
    };

    const func = ((stop - start) >= 0) ?
      () => { while(start <= stop) f1(); } :
      () => { while(start >= stop) f2(); };
    func();

    return arr;
  },

  /**
  * FN.cond is analogous to a switch statement. It evaluates each expression
  * in turn until it first the first one that evaluates to true and runs its
  * acompanying function.
  *
  * Example(s):
  *
  * FN.cond(
  *   1 === 2, () => { console.log("first");  },
  *   2 === 3, () => { console.log("second");  },
  *   "tmp" === "tmp", () => { console.log("third");  }
  * );
  *
  * @param {...(boolean|function)} lst - An array of expression/function pairs to evaluate/run.
  * @return {object|undefined} The result of the executed function or undefined.
  */
  "cond": function(...lst) {
    const func = ((lst.length % 2) === 0) ? (() => {
      var tmp;
      lst.forEach((element, index) => {
        // Expression is true, store the next argument (a function) for later use.
        if(((index % 2) === 0) && tmp === undefined && element) tmp = index+1;
      });
      return (lst[tmp] !== undefined) ? lst[tmp]() : undefined;
    }) : undefined;
    return(func !== undefined) ? func() : undefined;
  },

  /**
  * FN.everyOther is a function for applying the callback for every N elemet in
  * an array.
  *
  * Example(s):
  *
  * FN.everyOther((elm) => { console.log(elm);  }, [0, 1, 2, 3, 4, 5, 6], 2);
  *
  * @param {function} cb - The function to apply to n elements of the array.
  * @param {array} arr - The array containing the elements to apply the function to.
  * @param {number} step - The interval of steps to apply a function to.
  * @return {undefined} everyOther does not return anything it applies a callback for
  * every other element in a list.
  */
  "everyOther": function(arr, step, cb) {
    arr.forEach((element, index) => {
      if(((index+1) % step) === 0) cb(element);
    });
  },

  /**
   * FN.case is a function that evaluates a set of conditions against a sentinal
   * condition, the acompanying function is ran. A default condition can be passed
   * and a final callback passed for the default condition.
   *
   * Example(s):
   *
   * FN.case(9, 1, () => 1*2, 2, () => 2*2, 3, () => 3*2, FN.default, () => 19);
   *
   * @param {(number|string)} val - The sentinal condition.
   * @param {...(number|string|boolean|function)} lst - The condition/function pairs to check against the sentinal
   * and execute, if true.
   * @return {(object|undefined)} The result of the executed function or undefined.
   */
  "case": function(val, ...lst) {
    const func = ((lst.length % 2) === 0) ? (() => {
      var found;
      var defaultCase;
      lst.forEach((element, index) => {
        if(((index % 2) === 0) && found === undefined && element === val) found = index+1;
        else if(element === this.default) defaultCase = lst[index+1];
      });

      return(lst[found] !== undefined) ?
        lst[found]() :
        (defaultCase !== undefined) ?
          defaultCase() :
          undefined;
    }) : undefined;
    return(func !== undefined) ? func() : undefined;
  },

  /**
   * FN.sum is a function that takes a variable number of arguments and returns
   * the sum of all arguments all arguments must be numbers, if not undefined
   * is returned.
   *
   * Example(s):
   *
   * FN.sum([1, 2, 3, 4, 5]);
   *
   * @param {array} lst The list of numbers to sum.
   * @return {number|undefined} The sum of the provided arguments.
   */
  "sum": function(lst) {
    return(lst.every(elm => (typeof elm === "number"))) ?
      lst.reduce((prev, curr) => prev + curr) :
      undefined;
  },

  /**
   * FN.isOdd is a function that determines if a number is odd, or not.
   *
   * Example(s):
   *
   * FN.isOdd(1);
   *
   * @param {number} num The number to test.
   * @return {boolean} The oddity of the number.
   */
  "isOdd": function(num) {
    return num % 2 !== 0;
  }
});
<|endoftext|>


<commit_before>/* global describe, it, global */

var chai = require('chai')
var expect = chai.expect

var jshiki = require('../../index')

var jeval = (expression, scope) =>
  jshiki.parse(expression, { scope: scope }).eval()

var y = '1' // eslint-disable-line no-unused-vars
global.z = '2'

describe('Scope', () => {
  it('should be able to access scoped properties', () => {
    expect(jeval('x', { x: '1' })).to.equal('1')
  })

  it('should be able to invoke scoped functions', () => {
    expect(jeval('x()', { x: () => '1' })).to.equal('1')
  })

  it('should not be able to access global variables', () => {
    expect(jeval('y')).to.equal(undefined)
  })

  it('should not be able to access unscoped variables', () => {
    expect(jeval('z')).to.equal(undefined)
  })
})
<commit_msg>Fix scope test<commit_after>/* global describe, it, global */

var chai = require('chai')
var expect = chai.expect

var jshiki = require('../../index')

var jeval = (expression, scope) =>
  jshiki.parse(expression, { scope: scope }).eval()

describe('Scope', () => {
  it('should be able to access scoped properties', () => {
    expect(jeval('x', { x: '1' })).to.equal('1')
  })

  it('should be able to invoke scoped functions', () => {
    expect(jeval('x()', { x: () => '1' })).to.equal('1')
  })

  it('should not be able to access global variables', () => {
    global.y = '1'
    expect(jeval('y')).to.equal(undefined)
  })

  it('should not be able to access unscoped variables', () => {
    var z = '1' // eslint-disable-line no-unused-vars
    expect(jeval('z')).to.equal(undefined)
  })
})
<|endoftext|>


<commit_before>var chai = require('chai');
var spawn = require('child_process').spawn;
var tmp = require('tmp');
var path = require('path');

var NODE = 'node';
var INDEX = 'index.js';

chai.use(require('chai-fs'));

var assert = chai.assert;

function run(args, cb) {
    args = !!args ? args : [];
    var process = spawn(NODE, [INDEX].concat(args));
    var stdout = '', stderr = '';
    process.stdout.on('data', function (data) {
        stdout += data.toString();
    });
    process.stderr.on('data', function (data) {
        stderr += data.toString();
    });

    process.on('close', function (code) {
        return cb(null, code, stdout, stderr);
    });
}

describe("Tagit", function () {
    var workDir;
    var cleanupWorkDir;

    before(function () {
        tmp.dir({unsafeCleanup: true}, function (err, path, cleanupCallback) {
            if (err) throw err;
            workDir = path;
            cleanupWorkDir = cleanupCallback;
        });
    });

    after(function () {
        cleanupWorkDir();
    });

    it('should print help when no args', function (done) {
        run([], function (err, code, stdout) {
            assert.include(stdout, "Usage");
            //expect(stdout).to.have.string("Commands");
            //expect(stdout).to.have.string("Options");
            done();
        });
    });

    it('should create file structore on init', function (done) {
        run(['init', workDir], function (err, code, stdout) {
            assert.isDirectory(path.join(workDir, '.tagit'));
            assert.isFile(path.join(workDir, '.tagit/data.json'));
            done();
        })
    });

});<commit_msg>Add test for reinitialization<commit_after>var chai = require('chai');
var spawn = require('child_process').spawn;
var tmp = require('tmp');
var path = require('path');

var NODE = 'node';
var INDEX = 'index.js';

chai.use(require('chai-fs'));

var assert = chai.assert;

function run(args, cb) {
    args = !!args ? args : [];
    var process = spawn(NODE, [INDEX].concat(args));
    var stdout = '', stderr = '';
    process.stdout.on('data', function (data) {
        stdout += data.toString();
    });
    process.stderr.on('data', function (data) {
        stderr += data.toString();
    });

    process.on('close', function (code) {
        return cb(null, code, stdout, stderr);
    });
}

describe("Tagit before initialization", function () {
    var workDir;
    var cleanupWorkDir;

    beforeEach(function (done) {
        tmp.dir({unsafeCleanup: true}, function (err, path, cleanupCallback) {
            if (err) throw err;
            workDir = path;
            cleanupWorkDir = cleanupCallback;
            done();
        });
    });

    afterEach(function () {
        cleanupWorkDir();
    });

    it('should print help when no args', function (done) {
        run([], function (err, code, stdout) {
            assert.include(stdout, "Usage");
            //expect(stdout).to.have.string("Commands");
            //expect(stdout).to.have.string("Options");
            done();
        });
    });

    it('should create file structore on init', function (done) {
        run(['init', workDir], function (err, code, stdout) {
            assert.isDirectory(path.join(workDir, '.tagit'));
            assert.isFile(path.join(workDir, '.tagit/data.json'));
            done();
        })
    });

    describe("Tagit after initialized directory", function () {
        beforeEach(function (done) {
            run(['init', workDir], function (err, code, stdout) {
                done();
            });
        });

        it('shoult fail to init already initialized directories', function (done) {
            run(['init', workDir], function (err, code, stdout) {
                assert.notEqual(code, 0);
                done();
            });
        });
    });
});<|endoftext|>


<commit_before>var path

path = require( 'path' )

exports.get = function ( request, response ) {
  response.sendFile( path.join( __dirname + '/templates/login.html' ) )
}

exports.post = function ( request, response ) {
  response.status( 200 )
  response.json( request.user )
}
<commit_msg>Bring login endpoint response up to spec<commit_after>var path, Rat

path = require( 'path' )

Rat = require( '../models/rat' )

exports.get = function ( request, response ) {
  response.sendFile( path.join( __dirname + '/templates/login.html' ) )
}

exports.post = function ( request, response ) {
  var responseModel

  responseModel = {
    links: {
      self: request.originalUrl
    }
  }

  Rat.findById( request.user.rat )
  .exec( function ( error, rat ) {
    var status

    if ( error ) {
      responseModel.errors = []
      responseModel.errors.push( error )
      status = 400

    } else {
      request.user.rat = rat
      responseModel.data = request.user
      status = 200
    }

    response.status( status )
    response.json( responseModel )
  })
}
<|endoftext|>


<commit_before>
var mongoose = require('mongoose');

var reviewSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  rating: {
    type: Number,
    min: 0,
    max: 5,
    required: true
  },
  review: {
    type: String,
    required: true
  },
  createdOn: {
    type: Date,
    "default": Date.new
  }
});

var roomSchema = new mongoose.Schema({
  type: String,
  number: Number,
  description: String,
  photos: [String],
  price: Number
});

var hotelSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  stars: {
    type: Number,
    min: 0,
    max: 5,
    "default": 0
  },
  services: [String],
  description: String,
  photos: [String],
  currency: String,
  reviews: [reviewSchema],
  rooms: [roomSchema]
});

mongoose.model('Hotel', hotelSchema, 'hotelCollection');
<commit_msg>added location and coordinates in schema<commit_after>
var mongoose = require('mongoose');

var reviewSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  rating: {
    type: Number,
    min: 0,
    max: 5,
    required: true
  },
  review: {
    type: String,
    required: true
  },
  createdOn: {
    type: Date,
    "default": Date.new
  }
});

var roomSchema = new mongoose.Schema({
  type: String,
  number: Number,
  description: String,
  photos: [String],
  price: Number
});

var hotelSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  stars: {
    type: Number,
    min: 0,
    max: 5,
    "default": 0
  },
  services: [String],
  description: String,
  photos: [String],
  currency: String,
  reviews: [reviewSchema],
  rooms: [roomSchema],
  location: {
    address: String,
    // longitude E/W first
    coordinates: {
      type: [Number],
      index: '2dsphere'
    }
  }
});

mongoose.model('Hotel', hotelSchema, 'hotelCollection');
<|endoftext|>


<commit_before>'use strict';

const SpecialRight = require('./specialright');

/**
 * Right for "reduction du temps de travail"
 *
 * @constructor
 * @augments specialright
 *
 *
 */
function Rtt(app) {
    SpecialRight.call(this, app);

    this.editQuantity = false;

    this.countries = ['FR'];
}

Rtt.prototype = Object.create(SpecialRight.prototype);
Rtt.prototype.constructor = Rtt;

Rtt.prototype.getName = function() {
    const gt = this.app.utility.gettext;
    return gt.gettext('RTT');
};

Rtt.prototype.getDescription = function() {
    const gt = this.app.utility.gettext;
    return gt.gettext('Working time reduction right, this right require an annual leave with same renewal period');
};

/**
 * Get initial quantity used by renewals
 * @param {RightRenewal} renewal
 * @return {Promise}
 */
Rtt.prototype.getQuantity = function(renewal, user) {

    return user.getAccount()
    .then(account => {

        return Promise.all([
        //    account.getWeekHours(renewal.start, renewal.finish),
            renewal.getPlannedWorkDayNumber(user), // without week-ends, annual leaves and non working days
            account.getCollection(renewal.start) // collection on period start
        ]);
    })
    .then(all => {

        // all[0] number of potential worked days in the renewal of the annual leave
        // all[1].workedDays agreement worked days

        if (undefined === all[1].workedDays) {
            throw new Error('missing workdays on collection');
        }

        return Math.abs(all[0] - all[1].workedDays);
    });

};

Rtt.prototype.getQuantityLabel = function() {
    const gt = this.app.utility.gettext;
    return gt.gettext('RTT is computed from the user time schedule on the renewal period');
};

exports = module.exports = Rtt;
<commit_msg>Message if no collection<commit_after>'use strict';

const SpecialRight = require('./specialright');

/**
 * Right for "reduction du temps de travail"
 *
 * @constructor
 * @augments specialright
 *
 *
 */
function Rtt(app) {
    SpecialRight.call(this, app);

    this.editQuantity = false;

    this.countries = ['FR'];
}

Rtt.prototype = Object.create(SpecialRight.prototype);
Rtt.prototype.constructor = Rtt;

Rtt.prototype.getName = function() {
    const gt = this.app.utility.gettext;
    return gt.gettext('RTT');
};

Rtt.prototype.getDescription = function() {
    const gt = this.app.utility.gettext;
    return gt.gettext('Working time reduction right, this right require an annual leave with same renewal period');
};

/**
 * Get initial quantity used by renewals
 * @param {RightRenewal} renewal
 * @return {Promise}
 */
Rtt.prototype.getQuantity = function(renewal, user) {

    return user.getAccount()
    .then(account => {

        return Promise.all([
        //    account.getWeekHours(renewal.start, renewal.finish),
            renewal.getPlannedWorkDayNumber(user), // without week-ends, annual leaves and non working days
            account.getCollection(renewal.start) // collection on period start
        ]);
    })
    .then(all => {

        if (null === all[1]) {
            throw new Error('No collection on the renewal start date '+renewal.start);
        }

        // all[0] number of potential worked days in the renewal of the annual leave
        // all[1].workedDays agreement worked days

        if (undefined === all[1].workedDays) {
            throw new Error('missing workdays on collection');
        }

        return Math.abs(all[0] - all[1].workedDays);
    });

};

Rtt.prototype.getQuantityLabel = function() {
    const gt = this.app.utility.gettext;
    return gt.gettext('RTT is computed from the user time schedule on the renewal period');
};

exports = module.exports = Rtt;
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.requireStylesheet('tracing.analysis.analyze_slices');

base.require('tracing.analysis.util');
base.require('ui');
base.requireRawScript('../third_party/jquery/jquery-latest.js');
base.requireRawScript('../third_party/jquery/jquery.tablesorter.min.js');
base.exportTo('tracing.analysis', function() {

  function analyzeSingleSlice(results, slice, type) {
    results.appendHeader('Selected ' + type + ':');
    var table = results.appendTable('analysis-slice-table', 2);

    results.appendInfoRow(table, 'Title', slice.title);

    if (slice.category)
      results.appendInfoRow(table, 'Category', slice.category);

    results.appendInfoRowTime(table, 'Start', slice.start);
    results.appendInfoRowTime(table, 'Duration', slice.duration);

    if (slice.threadTime)
      results.appendInfoRowTime(table, 'ThreadTime', slice.threadTime);

    if (slice.selfTime)
      results.appendInfoRowTime(table, 'SelfTime', slice.selfTime);

    if (slice.durationInUserTime) {
      results.appendInfoRowTime(table, 'Duration (U)',
                                slice.durationInUserTime);
    }

    var n = 0;
    for (var argName in slice.args) {
      n += 1;
    }
    if (n > 0) {
      results.appendInfoRow(table, 'Args');
      for (var argName in slice.args) {
        var argVal = slice.args[argName];
        // TODO(sleffler) use span instead?
        results.appendInfoRow(table, ' ' + argName, argVal);
      }
    }
  }

  function analyzeSingleTypeSlices_(results, sliceGroup, hasThreadTime) {
    results.appendInfo('Title: ', sliceGroup[0].title);
    results.appendInfo('Category: ', sliceGroup[0].category);

    var table = results.appendTable('analysis-slice-table', 4 + hasThreadTime);
    var row = results.appendHeadRow(table);
    results.appendTableCell(table, row, 'Start');
    results.appendTableCell(table, row, 'Duration (ms)');
    if (hasThreadTime)
      results.appendTableCell(table, row, 'ThreadTime (ms)');
    results.appendTableCell(table, row, 'SelfTime (ms)');
    results.appendTableCell(table, row, 'Args');

    base.iterItems(sliceGroup, function(title, slice) {
      results.appendDetailsRow(table, slice.start, slice.duration,
          slice.selfTime ? slice.selfTime : slice.duration, slice.args,
          function() {
            return new tracing.Selection([slice]);
          }, slice.threadTime);
    });
  }

  function analyzeMultipleSlices(results, slices, type) {
    var tsLo = slices.bounds.min;
    var tsHi = slices.bounds.max;

    var numTitles = 0;
    var slicesByTitle = {};
    var hasThreadTime = false;

    for (var i = 0; i < slices.length; i++) {
      var slice = slices[i];
      if (slicesByTitle[slice.title] === undefined) {
        slicesByTitle[slice.title] = [];
        numTitles++;
      }

      if (slice.threadTime)
        hasThreadTime = true;

      var sliceGroup = slicesByTitle[slice.title];
      sliceGroup.push(slices[i]);
    }

    results.appendHeader(type + ':');
    var table = results.appendTable('analysis-slice-table', 4 + hasThreadTime);
    var row = results.appendHeadRow(table);
    results.appendTableCell(table, row, 'Name');
    results.appendTableCell(table, row, 'Duration (ms)');
    if (hasThreadTime)
      results.appendTableCell(table, row, 'ThreadTime (ms)');
    results.appendTableCell(table, row, 'SelfTime (ms)');
    results.appendTableCell(table, row, 'Occurrences');

    var totalDuration = 0;
    var totalThreadTime = 0;
    var totalSelfTime = 0;
    base.iterItems(slicesByTitle, function(sliceGroupTitle, sliceGroup) {
      var duration = 0;
      var threadTime = 0;
      var selfTime = 0;
      var avg = 0;
      var startOfFirstOccurrence = Number.MAX_VALUE;
      var startOfLastOccurrence = -Number.MAX_VALUE;
      var min = Number.MAX_VALUE;
      var max = -Number.MAX_VALUE;
      for (var i = 0; i < sliceGroup.length; i++) {
        var slice = sliceGroup[i];
        duration += slice.duration;
        if (slice.threadTime)
          threadTime += slice.threadTime;
        selfTime += slice.selfTime ? slice.selfTime : slice.duration;
        startOfFirstOccurrence = Math.min(slice.start, startOfFirstOccurrence);
        startOfLastOccurrence = Math.max(slice.start, startOfLastOccurrence);
        min = Math.min(slice.duration, min);
        max = Math.max(slice.duration, max);
      }

      totalDuration += duration;
      totalThreadTime += threadTime;
      totalSelfTime += selfTime;

      if (sliceGroup.length == 0)
        avg = 0;
      avg = duration / sliceGroup.length;

      var statistics = {
        min: min,
        max: max,
        avg: avg,
        avg_stddev: undefined,
        frequency: undefined,
        frequency_stddev: undefined
      };

      // Compute the stddev of the slice durations.
      var sumOfSquaredDistancesToMean = 0;
      for (var i = 0; i < sliceGroup.length; i++) {
        var signedDistance = statistics.avg - sliceGroup[i].duration;
        sumOfSquaredDistancesToMean += signedDistance * signedDistance;
      }

      statistics.avg_stddev =
          Math.sqrt(sumOfSquaredDistancesToMean / (sliceGroup.length - 1));

      // We require at least 3 samples to compute the stddev.
      var elapsed = startOfLastOccurrence - startOfFirstOccurrence;
      if (sliceGroup.length > 2 && elapsed > 0) {
        var numDistances = sliceGroup.length - 1;
        statistics.frequency = (1000 * numDistances) / elapsed;

        // Compute the stddev.
        sumOfSquaredDistancesToMean = 0;
        for (var i = 1; i < sliceGroup.length; i++) {
          var currentFrequency =
              1000 / (sliceGroup[i].start - sliceGroup[i - 1].start);
          var signedDistance = statistics.frequency - currentFrequency;
          sumOfSquaredDistancesToMean += signedDistance * signedDistance;
        }

        statistics.frequency_stddev =
            Math.sqrt(sumOfSquaredDistancesToMean / (numDistances - 1));
      }
      results.appendDataRow(table, sliceGroupTitle, duration,
                            hasThreadTime ? (threadTime > 0 ?
                                threadTime : '') : null,
                            selfTime, sliceGroup.length, statistics,
                            function() {
                              return new tracing.Selection(sliceGroup);
                            });

      // The whole selection is a single type so list out the information
      // for each sub slice.
      if (numTitles === 1)
        analyzeSingleTypeSlices_(results, sliceGroup, hasThreadTime);
    });

    // Only one row so we already know the totals.
    if (numTitles !== 1) {
      results.appendDataRow(table, 'Totals', totalDuration,
                            hasThreadTime ? totalThreadTime : null,
                            totalSelfTime, slices.length, null, null, true);
      results.appendSpacingRow(table, true);
    }

    results.appendInfoRowTime(table, 'Selection start', tsLo, true);
    results.appendInfoRowTime(table, 'Selection extent', tsHi - tsLo, true);
  }

  return {
    analyzeSingleSlice: analyzeSingleSlice,
    analyzeMultipleSlices: analyzeMultipleSlices
  };
});
<commit_msg>Remove jquery unused deps<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.requireStylesheet('tracing.analysis.analyze_slices');

base.require('tracing.analysis.util');
base.require('ui');

base.exportTo('tracing.analysis', function() {

  function analyzeSingleSlice(results, slice, type) {
    results.appendHeader('Selected ' + type + ':');
    var table = results.appendTable('analysis-slice-table', 2);

    results.appendInfoRow(table, 'Title', slice.title);

    if (slice.category)
      results.appendInfoRow(table, 'Category', slice.category);

    results.appendInfoRowTime(table, 'Start', slice.start);
    results.appendInfoRowTime(table, 'Duration', slice.duration);

    if (slice.threadTime)
      results.appendInfoRowTime(table, 'ThreadTime', slice.threadTime);

    if (slice.selfTime)
      results.appendInfoRowTime(table, 'SelfTime', slice.selfTime);

    if (slice.durationInUserTime) {
      results.appendInfoRowTime(table, 'Duration (U)',
                                slice.durationInUserTime);
    }

    var n = 0;
    for (var argName in slice.args) {
      n += 1;
    }
    if (n > 0) {
      results.appendInfoRow(table, 'Args');
      for (var argName in slice.args) {
        var argVal = slice.args[argName];
        // TODO(sleffler) use span instead?
        results.appendInfoRow(table, ' ' + argName, argVal);
      }
    }
  }

  function analyzeSingleTypeSlices_(results, sliceGroup, hasThreadTime) {
    results.appendInfo('Title: ', sliceGroup[0].title);
    results.appendInfo('Category: ', sliceGroup[0].category);

    var table = results.appendTable('analysis-slice-table', 4 + hasThreadTime);
    var row = results.appendHeadRow(table);
    results.appendTableCell(table, row, 'Start');
    results.appendTableCell(table, row, 'Duration (ms)');
    if (hasThreadTime)
      results.appendTableCell(table, row, 'ThreadTime (ms)');
    results.appendTableCell(table, row, 'SelfTime (ms)');
    results.appendTableCell(table, row, 'Args');

    base.iterItems(sliceGroup, function(title, slice) {
      results.appendDetailsRow(table, slice.start, slice.duration,
          slice.selfTime ? slice.selfTime : slice.duration, slice.args,
          function() {
            return new tracing.Selection([slice]);
          }, slice.threadTime);
    });
  }

  function analyzeMultipleSlices(results, slices, type) {
    var tsLo = slices.bounds.min;
    var tsHi = slices.bounds.max;

    var numTitles = 0;
    var slicesByTitle = {};
    var hasThreadTime = false;

    for (var i = 0; i < slices.length; i++) {
      var slice = slices[i];
      if (slicesByTitle[slice.title] === undefined) {
        slicesByTitle[slice.title] = [];
        numTitles++;
      }

      if (slice.threadTime)
        hasThreadTime = true;

      var sliceGroup = slicesByTitle[slice.title];
      sliceGroup.push(slices[i]);
    }

    results.appendHeader(type + ':');
    var table = results.appendTable('analysis-slice-table', 4 + hasThreadTime);
    var row = results.appendHeadRow(table);
    results.appendTableCell(table, row, 'Name');
    results.appendTableCell(table, row, 'Duration (ms)');
    if (hasThreadTime)
      results.appendTableCell(table, row, 'ThreadTime (ms)');
    results.appendTableCell(table, row, 'SelfTime (ms)');
    results.appendTableCell(table, row, 'Occurrences');

    var totalDuration = 0;
    var totalThreadTime = 0;
    var totalSelfTime = 0;
    base.iterItems(slicesByTitle, function(sliceGroupTitle, sliceGroup) {
      var duration = 0;
      var threadTime = 0;
      var selfTime = 0;
      var avg = 0;
      var startOfFirstOccurrence = Number.MAX_VALUE;
      var startOfLastOccurrence = -Number.MAX_VALUE;
      var min = Number.MAX_VALUE;
      var max = -Number.MAX_VALUE;
      for (var i = 0; i < sliceGroup.length; i++) {
        var slice = sliceGroup[i];
        duration += slice.duration;
        if (slice.threadTime)
          threadTime += slice.threadTime;
        selfTime += slice.selfTime ? slice.selfTime : slice.duration;
        startOfFirstOccurrence = Math.min(slice.start, startOfFirstOccurrence);
        startOfLastOccurrence = Math.max(slice.start, startOfLastOccurrence);
        min = Math.min(slice.duration, min);
        max = Math.max(slice.duration, max);
      }

      totalDuration += duration;
      totalThreadTime += threadTime;
      totalSelfTime += selfTime;

      if (sliceGroup.length == 0)
        avg = 0;
      avg = duration / sliceGroup.length;

      var statistics = {
        min: min,
        max: max,
        avg: avg,
        avg_stddev: undefined,
        frequency: undefined,
        frequency_stddev: undefined
      };

      // Compute the stddev of the slice durations.
      var sumOfSquaredDistancesToMean = 0;
      for (var i = 0; i < sliceGroup.length; i++) {
        var signedDistance = statistics.avg - sliceGroup[i].duration;
        sumOfSquaredDistancesToMean += signedDistance * signedDistance;
      }

      statistics.avg_stddev =
          Math.sqrt(sumOfSquaredDistancesToMean / (sliceGroup.length - 1));

      // We require at least 3 samples to compute the stddev.
      var elapsed = startOfLastOccurrence - startOfFirstOccurrence;
      if (sliceGroup.length > 2 && elapsed > 0) {
        var numDistances = sliceGroup.length - 1;
        statistics.frequency = (1000 * numDistances) / elapsed;

        // Compute the stddev.
        sumOfSquaredDistancesToMean = 0;
        for (var i = 1; i < sliceGroup.length; i++) {
          var currentFrequency =
              1000 / (sliceGroup[i].start - sliceGroup[i - 1].start);
          var signedDistance = statistics.frequency - currentFrequency;
          sumOfSquaredDistancesToMean += signedDistance * signedDistance;
        }

        statistics.frequency_stddev =
            Math.sqrt(sumOfSquaredDistancesToMean / (numDistances - 1));
      }
      results.appendDataRow(table, sliceGroupTitle, duration,
                            hasThreadTime ? (threadTime > 0 ?
                                threadTime : '') : null,
                            selfTime, sliceGroup.length, statistics,
                            function() {
                              return new tracing.Selection(sliceGroup);
                            });

      // The whole selection is a single type so list out the information
      // for each sub slice.
      if (numTitles === 1)
        analyzeSingleTypeSlices_(results, sliceGroup, hasThreadTime);
    });

    // Only one row so we already know the totals.
    if (numTitles !== 1) {
      results.appendDataRow(table, 'Totals', totalDuration,
                            hasThreadTime ? totalThreadTime : null,
                            totalSelfTime, slices.length, null, null, true);
      results.appendSpacingRow(table, true);
    }

    results.appendInfoRowTime(table, 'Selection start', tsLo, true);
    results.appendInfoRowTime(table, 'Selection extent', tsHi - tsLo, true);
  }

  return {
    analyzeSingleSlice: analyzeSingleSlice,
    analyzeMultipleSlices: analyzeMultipleSlices
  };
});
<|endoftext|>


<commit_before>import debug from 'debug'
import { clone } from 'lodash/lang'

const log = debug('response')

function response (req) {
  log('calling response for req', req.xhr)
  const res = clone(req.xhr)

  res.body = res.responseText
  res.headers = req.xhr.getAllResponseHeaders()

  log(res.body)
  log(res.headers)

  return res
}

export default response
<commit_msg>fix(helper): add missing xhr field<commit_after>import debug from 'debug'
import { clone } from 'lodash/lang'

const log = debug('response')

function response (req) {
  log('calling response for req', req.xhr)
  const res = clone(req.xhr)

  res.body = res.responseText
  res.headers = req.xhr.getAllResponseHeaders()
  res.xhr = req.xhr

  return res
}

export default response
<|endoftext|>


<commit_before>var port = parseInt(process.argv[2]);

var io = require('socket.io').listen(port);
var stdin = process.openStdin();

stdin.setEncoding('utf8');

stdin.on('data', function(chunk) {
	process.stderr.write(chunk);
});

io.set('transports', [ process.argv[3] ]);

var main = io.of("/main").on('connection', function(socket) {
	socket.on('echo', function(data) {
		if(data)
			socket.emit('echo', data);
		else
			socket.emit('echo');
	});
	socket.on('echoSend', function(data) {
		if (typeof data == 'object') {
			socket.send(JSON.parse(JSON.stringify(data)));
		} else {
			socket.send(data);
		}
	});
	socket.on('echoAck', function(data, ack) {
		ack(data);
	});
	socket.on('requestAcknowledge', function(data) {
			socket.emit('requestAcknowledge', data, function(data) {
				process.stdout.write("__:ACKNOWLEDGE:" + data + "\n");
			});
	})
	socket.on('message', function(m) {
		process.stdout.write("__:MESSAGE:" + m + "\n");
	});
	socket.on('defaultns', function(m) {
		io.sockets.send(m);
	})
});

var ns1 = io.of('/ns1').on('connection', function(socket) {
	main.send("ns1");
	ns2.send("ns1");
});

var ns2 = io.of('/ns2').on('connection', function(socket) {
	main.send("ns2");
	ns1.send("ns2");
});

process.stdout.write("__:OK\n");
<commit_msg>CLOSED - task 2: Make pass all tests relaible. https://github.com/Gottox/socket.io-java-client/issues/issue/2<commit_after>var port = parseInt(process.argv[2]);

var io = require('socket.io').listen(port);
var stdin = process.openStdin();

stdin.setEncoding('utf8');

stdin.on('data', function(chunk) {
	process.stderr.write(chunk);
});

io.set('transports', [ process.argv[3] ]);

var main = io.of("/main").on('connection', function(socket) {
	socket.on('echo', function(data) {
		if(data)
			socket.emit('echo', data);
		else
			socket.emit('echo');
	});
	socket.on('echoSend', function(data) {
		if (typeof data == 'object') {
			socket.send(JSON.parse(JSON.stringify(data)));
		} else {
			socket.send(data);
		}
	});
	socket.on('echoAck', function(data, ack) {
		ack(data);
	});
	socket.on('requestAcknowledge', function(data) {
			socket.emit('requestAcknowledge', data, function(data) {
				process.stdout.write("__:ACKNOWLEDGE:" + data + "\n");
			});
	})
	socket.on('message', function(m) {
		process.stdout.write("__:MESSAGE:" + m + "\n");
	});
	socket.on('defaultns', function(m) {
		io.sockets.send(m);
	})
});

var ns1 = io.of('/ns1').on('connection', function(socket) {
	main.send("ns1");
	ns2.send("ns1");
});

var ns2 = io.of('/ns2').on('connection', function(socket) {
	setTimeout(function() {
		main.send("ns2");
		ns1.send("ns2");
	}, 200);
});

process.stdout.write("__:OK\n");
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.require('base.guid');
base.require('tracing.trace_model.event');

/**
 * @fileoverview Provides the TimedEvent class.
 */
base.exportTo('tracing.trace_model', function() {
  /**
   * A TimedEvent is the base type for any piece of data in the trace model with
   * a specific start and duration.
   *
   * @constructor
   */
  function TimedEvent(start) {
    tracing.trace_model.Event.call(this);
    this.guid_ = base.GUID.allocate();
    this.start = start;
    this.duration = 0;
  }

  TimedEvent.prototype = {
    __proto__: tracing.trace_model.Event.prototype,

    get end() {
      return this.start + this.duration;
    },

    addBoundsToRange: function(range) {
      range.addValue(this.start);
      range.addValue(this.end);
    }
  };

  return {
    TimedEvent: TimedEvent
  };
});
<commit_msg>Fix TimedEvent sets GUID twice<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.require('base.guid');
base.require('tracing.trace_model.event');

/**
 * @fileoverview Provides the TimedEvent class.
 */
base.exportTo('tracing.trace_model', function() {
  /**
   * A TimedEvent is the base type for any piece of data in the trace model with
   * a specific start and duration.
   *
   * @constructor
   */
  function TimedEvent(start) {
    tracing.trace_model.Event.call(this);
    this.start = start;
    this.duration = 0;
  }

  TimedEvent.prototype = {
    __proto__: tracing.trace_model.Event.prototype,

    get end() {
      return this.start + this.duration;
    },

    addBoundsToRange: function(range) {
      range.addValue(this.start);
      range.addValue(this.end);
    }
  };

  return {
    TimedEvent: TimedEvent
  };
});
<|endoftext|>


<commit_before>window.createRootPage = function () {
  'use strict';

  var PageObject = testmator.PageObject;

  var $root = $('
')
        .append($('<button id="openChild">'))
        .append($('

'))
        .append($(''))
        .on('click', 'li', function () {
          $root.find('#result').text(this.id);
        });

  var $child = $('
')
        .append($('<button id="toParent">'));

  var ChildPage = PageObject.extend({
    name: 'child',
    clickToParent: function () {
      this.click('#toParent');
      return this.switchParent();
    }
  });

  var RootPage = PageObject.extend({
    name: 'root',
    clickOpenChild: function () {
      this.click('#button1');
      return new ChildPage({el: $child, parent: this});
    },
    clickButton1: function () {
      console.log('WARNING');
      return this.clickOpenChild();
    },
    clickLi: function (label) {
      this.click('#li' + label);
    },
    getResult: function () {
      return this.$('#result').text();
    }
  });

  return new RootPage({el: $root});
};
<commit_msg>Fix build failed.<commit_after>window.createRootPage = function () {
  'use strict';

  var PageObject = testmator.PageObject;

  var $root = $('
')
        .append($('<button id="openChild">'))
        .append($('

'))
        .append($(''))
        .on('click', 'li', function () {
          $root.find('#result').text(this.id);
        });

  var $child = $('
')
        .append($('<button id="toParent">'));

  var ChildPage = PageObject.extend({
    name: 'child',
    clickToParent: function () {
      this.click('#toParent');
      return this.switchParent();
    }
  });

  var RootPage = PageObject.extend({
    name: 'root',
    clickOpenChild: function () {
      this.click('#button1');
      return new ChildPage({el: $child, parent: this});
    },
    clickButton1: function () {
      console.log('WARNING');
      return this.clickOpenChild();
    },
    clickLi: function (label) {
      this.click('#li' + label);
    },
    getResult: function () {
      return this.$('#result').text();
    }
  });

  return new RootPage({el: $root});
};
<|endoftext|>


<commit_before>describe("ilios_base", function() {

  it("should create a global ilios object", function() {
    expect(ilios).toBeDefined();
  });

  describe("ilios", function () {

    it("should have a namespace method", function () {
      expect(typeof ilios.namespace).toBe("function");
    });

    it("should have a lang namespace", function () {
      expect(typeof ilios.lang).toBe("object");
    });

    it("should have an alert namespace", function () {
      expect(typeof ilios.alert).toBe("object");
    });

    it("should have a global namespace", function () {
      expect(typeof ilios.global).toBe("object");
    });

    describe("namespace()", function () {
      it("should create the supplied namespace", function () {
        expect(typeof ilios.foo).toBe("undefined");
        ilios.namespace('foo');
        expect(typeof ilios.foo).toBe("object");
      });
    });
  });
});
<commit_msg>multi-level namespace creation<commit_after>describe("ilios_base", function() {

  it("should create a global ilios object", function() {
    expect(ilios).toBeDefined();
  });

  describe("ilios", function () {

    it("should have a namespace method", function () {
      expect(typeof ilios.namespace).toBe("function");
    });

    it("should have a lang namespace", function () {
      expect(typeof ilios.lang).toBe("object");
    });

    it("should have an alert namespace", function () {
      expect(typeof ilios.alert).toBe("object");
    });

    it("should have a global namespace", function () {
      expect(typeof ilios.global).toBe("object");
    });

    describe("namespace()", function () {
      it("should create the supplied namespace", function () {
        expect(typeof ilios.foo).toBe("undefined");
        ilios.namespace('foo');
        expect(typeof ilios.foo).toBe("object");
        // cleanup
        delete ilios.foo;
      });

      it("should create namespaces with depth > 1", function () {
        expect(typeof ilios.foo).toBe("undefined");
        ilios.namespace('foo.bar');
        expect(typeof ilios.foo).toBe("object");
        expect(typeof ilios.foo.bar).toBe("object");
        // cleanup
        delete ilios.foo;
      });
    });
  });
});
<|endoftext|>