<commit_before>/* -*- Mode: js2; tab-width: 4; indent-tabs-mode: nil; -*-
 * vim: set ts=4 sw=4 et tw=99 ft=js:
 */
var util = require("../../util/util"),
    fs = require("fs"),
    fse = require("fs-extra"),
    path = require("path"),
    child_process = require("child_process"),
    spawn = child_process.spawn,
    usage = require("../global/usage"),
    project = require("../../util/project"),
    parseArgs = require("minimist");

function generateInfoPlist(proj, config, contents_path, cb) {
    var info_plist_path = path.join(contents_path, "Info.plist");

    var bundleName = util.getBundleName(config);

    var plist_json_contents = {
        CFBundleDevelopmentRegion: 'en',
        CFBundlePackageType: 'AAPL',
        CFBundleGetInfoString: 'Created by Pirouette/EchoJS',
        CFBundleSignature: '????',
        CFBundleExecutable: config.projectName,
        CFBundleIdentifier: config.bundleIdentifier,
        CFBundleInfoDictionaryVersion: '6.0',
        CFBundleShortVersionString: '0.1',
        CFBundleVersion: '1',
        CFBundleName: bundleName,
        CFBundleDisplayName: bundleName,
        DTPlatformName: 'iphonesimulator',
        DTPlatformVersion: '9.1',
        UIDeviceFamily : [1, 2],
        UISupportedInterfaceOrientations : [
            "UIInterfaceOrientationPortrait",
            "UIInterfaceOrientationLandscapeLeft",
            "UIInterfaceOrientationLandscapeRight"
        ],
        "UISupportedInterfaceOrientations~ipad" : [
            "UIInterfaceOrientationPortrait",
            "UIInterfaceOrientationPortraitUpsideDown",
            "UIInterfaceOrientationLandscapeLeft",
            "UIInterfaceOrientationLandscapeRight"
        ]
    };

    if (config.launchStoryboard)
        plist_json_contents.UILaunchStoryboardName = path.basename(config.launchStoryboard, ".storyboard");

    if (config.mainStoryboard)
        plist_json_contents.UIMainStoryboardName = path.basename(config.mainStoryboard, ".storyboard");

    util.writePlist(plist_json_contents, info_plist_path, "binary1",
                    function (code, signal) {
                        if (code == null) {
                            console.error ('error running plutil ' + signal);
                            process.exit(-1);
                        }

                        console.log('done converting plist file at ' + info_plist_path);
                        cb();
                    });
}

function buildDestDir(proj, build_config) {

    var bundle_contents;

    var dir = util.ensureDir ('build');
    dir = util.ensureDir (proj.buildDir(build_config));
    dir = util.ensureDir (path.join (dir, proj.config.projectName + '.app'));

    bundle_contents = dir;

    util.ensureDir (path.join (bundle_contents, 'Base.lproj'));

    return bundle_contents;
}

function copyResources(proj, bundle_contents, build_config, cb) {
    var resource_list = proj.config.resources;
    if (!resource_list) {
        // no resources, easy.
        return cb();
    }

    var resources_dir = bundle_contents;

    var resource_srcs = Object.getOwnPropertyNames(resource_list);

    for (var i = 0, e = resource_srcs.length; i < e; i ++) {
        var src = resource_srcs[i];
        var dest = resource_list[src];

        fse.copySync(src, path.join(resources_dir, dest), {});
    }

    return cb();
}

function compileScripts(proj, build_config, bundle_contents, cb) {

    generateInfoPlist(proj, proj.config, bundle_contents, function (err) {
        var dest_exe = path.join(bundle_contents, proj.config.projectName);

        util.compileScripts(proj.config.projectType,
                            proj.config.files || [proj.config.projectName + '.js'],
                            path.relative(proj.root, dest_exe),
                            function (err) {
                                copyResources(proj, bundle_contents, build_config, cb);
                            });
    });
}

function buildIOS(proj, build_config, args, cb) {
    var bundle_contents = buildDestDir(proj, build_config);

    var boards = util.collectStoryboards(proj.config);
    if (boards.length > 0) {
        util.compileStoryboards(boards, bundle_contents,
                                util.getBundleName(proj.config),
                                function (code) {
                                    compileScripts(proj, build_config, bundle_contents, cb);
                                });
    }
    else {
        compileScripts(proj, build_config, bundle_contents, cb);
    }
}

function run(args, cb) {
    var build_config = project.Configuration.Debug;
    if (args.length > 0) {
        if (args[0] === 'release') {
            build_config = project.Configuration.Release;
        }
        else if (args[0] !== 'debug') {
            throw new Error("configuration must be 'release' or 'debug'");
        }
    }

    var proj = project.Project.findContaining ();
    if (!proj)
        throw new Error ("Couldn't find containing project.");

    var config = proj.config;
    return buildIOS(proj, build_config, args, cb);
}

var flags = {
    "--help": { usage: function(s) { return s; }, usageString: function(s) { return ": this output."; } }
};

function printUsage() {
    console.log (" $ pirouette build [options]");
    console.log ("where [options] can be:");
    for (var flag in flags) {
        console.log(usage.formatCommand(flag, flags[flag]));
    }
}

exports.command = {
    usage: function(s) { return s; },
    usageString: function(s) { return ': Builds the current project.'; },
    run: function(argv, cb) {
        var args = parseArgs(argv);

        if (args.help) {
            printUsage();
            cb();
        }
        else {
            run(args, cb);
        }
    }
};
<commit_msg>support 'deviceFamilies' in project.json and convert to UIDeviceFamily<commit_after>/* -*- Mode: js2; tab-width: 4; indent-tabs-mode: nil; -*-
 * vim: set ts=4 sw=4 et tw=99 ft=js:
 */
var util = require("../../util/util"),
    fs = require("fs"),
    fse = require("fs-extra"),
    path = require("path"),
    child_process = require("child_process"),
    spawn = child_process.spawn,
    usage = require("../global/usage"),
    project = require("../../util/project"),
    parseArgs = require("minimist");

function generateInfoPlist(proj, config, contents_path, cb) {
    var info_plist_path = path.join(contents_path, "Info.plist");

    var bundleName = util.getBundleName(config);

    var plist_json_contents = {
        CFBundleDevelopmentRegion: 'en',
        CFBundlePackageType: 'AAPL',
        CFBundleGetInfoString: 'Created by Pirouette/EchoJS',
        CFBundleSignature: '????',
        CFBundleExecutable: config.projectName,
        CFBundleIdentifier: config.bundleIdentifier,
        CFBundleInfoDictionaryVersion: '6.0',
        CFBundleShortVersionString: '0.1',
        CFBundleVersion: '1',
        CFBundleName: bundleName,
        CFBundleDisplayName: bundleName,
        DTPlatformName: 'iphonesimulator',
        DTPlatformVersion: '9.1',
        UISupportedInterfaceOrientations : [
            "UIInterfaceOrientationPortrait",
            "UIInterfaceOrientationLandscapeLeft",
            "UIInterfaceOrientationLandscapeRight"
        ],
        "UISupportedInterfaceOrientations~ipad" : [
            "UIInterfaceOrientationPortrait",
            "UIInterfaceOrientationPortraitUpsideDown",
            "UIInterfaceOrientationLandscapeLeft",
            "UIInterfaceOrientationLandscapeRight"
        ]
    };

    if (config.deviceFamilies) {
        var families = config.deviceFamilies;
        var plist_families = [];
        var iphone_seen = false, ipad_seen = false;
        for (var i = 0, e = families.length; i < e; i ++) {
            if (families[i] === 'iphone') {
                if (iphone_seen)
                    console.warn("duplicate deviceFamily 'iphone'");
                iphone_seen = true;
                plist_families.push(1);
            }
            else if (families[i] === 'ipad') {
                if (ipad_seen)
                    console.warn("duplicate deviceFamily 'ipad'");
                ipad_seen = true;
                plist_families.push(2);
            }
            else
                console.warn("unknown deviceFamily '" + families[i] + "' in project.json");
        }
        plist_json_contents.UIDeviceFamily = plist_families;
    }

    if (config.launchStoryboard)
        plist_json_contents.UILaunchStoryboardName = path.basename(config.launchStoryboard, ".storyboard");

    if (config.mainStoryboard)
        plist_json_contents.UIMainStoryboardName = path.basename(config.mainStoryboard, ".storyboard");

    util.writePlist(plist_json_contents, info_plist_path, "binary1",
                    function (code, signal) {
                        if (code == null) {
                            console.error ('error running plutil ' + signal);
                            process.exit(-1);
                        }

                        console.log('done converting plist file at ' + info_plist_path);
                        cb();
                    });
}

function buildDestDir(proj, build_config) {

    var bundle_contents;

    var dir = util.ensureDir ('build');
    dir = util.ensureDir (proj.buildDir(build_config));
    dir = util.ensureDir (path.join (dir, proj.config.projectName + '.app'));

    bundle_contents = dir;

    util.ensureDir (path.join (bundle_contents, 'Base.lproj'));

    return bundle_contents;
}

function copyResources(proj, bundle_contents, build_config, cb) {
    var resource_list = proj.config.resources;
    if (!resource_list) {
        // no resources, easy.
        return cb();
    }

    var resources_dir = bundle_contents;

    var resource_srcs = Object.getOwnPropertyNames(resource_list);

    for (var i = 0, e = resource_srcs.length; i < e; i ++) {
        var src = resource_srcs[i];
        var dest = resource_list[src];

        fse.copySync(src, path.join(resources_dir, dest), {});
    }

    return cb();
}

function compileScripts(proj, build_config, bundle_contents, cb) {

    generateInfoPlist(proj, proj.config, bundle_contents, function (err) {
        var dest_exe = path.join(bundle_contents, proj.config.projectName);

        util.compileScripts(proj.config.projectType,
                            proj.config.files || [proj.config.projectName + '.js'],
                            path.relative(proj.root, dest_exe),
                            function (err) {
                                copyResources(proj, bundle_contents, build_config, cb);
                            });
    });
}

function buildIOS(proj, build_config, args, cb) {
    var bundle_contents = buildDestDir(proj, build_config);

    var boards = util.collectStoryboards(proj.config);
    if (boards.length > 0) {
        util.compileStoryboards(boards, bundle_contents,
                                util.getBundleName(proj.config),
                                function (code) {
                                    compileScripts(proj, build_config, bundle_contents, cb);
                                });
    }
    else {
        compileScripts(proj, build_config, bundle_contents, cb);
    }
}

function run(args, cb) {
    var build_config = project.Configuration.Debug;
    if (args.length > 0) {
        if (args[0] === 'release') {
            build_config = project.Configuration.Release;
        }
        else if (args[0] !== 'debug') {
            throw new Error("configuration must be 'release' or 'debug'");
        }
    }

    var proj = project.Project.findContaining ();
    if (!proj)
        throw new Error ("Couldn't find containing project.");

    var config = proj.config;
    return buildIOS(proj, build_config, args, cb);
}

var flags = {
    "--help": { usage: function(s) { return s; }, usageString: function(s) { return ": this output."; } }
};

function printUsage() {
    console.log (" $ pirouette build [options]");
    console.log ("where [options] can be:");
    for (var flag in flags) {
        console.log(usage.formatCommand(flag, flags[flag]));
    }
}

exports.command = {
    usage: function(s) { return s; },
    usageString: function(s) { return ': Builds the current project.'; },
    run: function(argv, cb) {
        var args = parseArgs(argv);

        if (args.help) {
            printUsage();
            cb();
        }
        else {
            run(args, cb);
        }
    }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import classnames from 'classnames';
import _ from 'lodash';

export default class LinkTile extends Component {

  render() {
    const { props } = this;

    return (

            Links

    );
  }

}

window['link-server-hookTile'] = LinkTile;
<commit_msg>link fe: render unseen count in the launch tile<commit_after>import React, { Component } from 'react';
import classnames from 'classnames';
import _ from 'lodash';

export default class LinkTile extends Component {

  render() {
    const unseenCount = this.props.data.unseen || 0;

    let displayUnseen = unseenCount <= 0
      ? null
      :

          {unseenCount > 99 ? "99+" : unseenCount}

;

    return (

            Links

          {displayUnseen}

    );
  }

}

window['link-viewTile'] = LinkTile;
<|endoftext|>


<commit_before><commit_msg>Drill and expand using string variables, not the numeric counterparts of the string variables<commit_after><|endoftext|>


<commit_before>/* UMD.define */ (function (root, factory) {
	if (typeof customLoader === 'function'){ customLoader(factory, 'on'); }else if (typeof define === 'function' && define.amd){ define([], factory); }else if(typeof exports === 'object'){ module.exports = factory(); }else{ root.returnExports = factory(); window.on = factory(); }
}(this, function () {
	// `on` is a simple library for attaching events to nodes. Its primary feature
	// is it returns a handle, from which you can pause, resume and remove the
	// event. Handles are much easier to manipulate than using removeEventListener
	// and recreating (sometimes complex or recursive) function signatures.
	//
	// `on` is touch-friendly and will normalize touch events.
	//
	// `on` also supports a custom `clickoff` event, to detect if you've clicked
	// anywhere in the document other than the passed node
	//
	// USAGE
	//      var handle = on(node, 'clickoff', callback);
	//      //  callback fires if something other than node is clicked
	//
	// USAGE
	//      var handle = on(node, 'mousedown', onStart);
	//      handle.pause();
	//      handle.resume();
	//      handle.remove();
	//
	//  `on` also supports multiple event types at once. The following example is
	//  useful for handling both desktop mouseovers and tablet clicks:
	//
	// USAGE
	//      var handle = on(node, 'mouseover,click', onStart);
	//
	//
	// `on` has an optional context parameter. The fourth argument can be 'this'
	// (or some other object) to conveniently avoid the use of var `self = this;`
	//
	//  USAGE
	//      var handle = on(this.node, 'mousedown', 'onStart', this);
	//
	// `on.multi` allows for connecting multiple events to a node at the same
	// time. Note this requires a context (I think), so it is not applicable for
	// anonymous functions.
	//
	//  USAGE
	//      handle = on.multi(document, {
	//          "touchend":"onEnd",
	//          "touchcancel":"onEnd",
	//          "touchmove":this.method
	//      }, this);
	//
	// `on` supports an optional ID that can be used to track connections to be
	// disposed later.
	//
	// USAGE
	//      on(node, 'click', callback, 'uid-a');
	//      on(node, 'mouseover', callback, 'uid-a');
	//      on(otherNode, 'click', callback, 'uid-a');
	//      on(document, 'load', callback, 'uid-a');
	//      on.remove('uid-a');
	//
	// `on` supports selectors, seperated from the event by a space:
	//
	// USAGE
	//      on(node, 'click div.tab span', callback);
	//

	function hasWheel(){
		var
			isIE = navigator.userAgent.indexOf('Trident') > -1,
			div = document.createElement('div');
		return  "onwheel" in div || "wheel" in div ||
			(isIE && document.implementation.hasFeature("Events.wheel", "3.0")); // IE feature detection
	}

	function has(what){
		switch(what){
			case 'wheel': return hasWheel();
		}
		return false;
	}

	function populateRange(keys, fromChar, toChar){
		for(var i = fromChar.charCodeAt(0), n = toChar.charCodeAt(0); i <= n; ++i){
			keys[i] = String.fromCharCode(i);
		}
	}

	var
		isWin = navigator.userAgent.indexOf('Windows')>-1,
		FACTOR = isWin ? 10 : 0.1,
		XLR8 = 0,
		mouseWheelHandle,
		//numCalls = 0,
		keyCodes = [], // it will be a sparse array to keep alphanumeric ASCII characters
		registry = {};

	populateRange(keyCodes, '0', '9');
	populateRange(keyCodes, 'a', 'z');
	populateRange(keyCodes, 'A', 'Z');

	function normalizeKeyEvent (callback){
		// Add alphanumeric property (the letter typed) to the KeyEvent
		//
		return function(e){
			// 48-57 0-9
			// 65 - 90 a-z
			var value = keyCodes[e.keyCode];
			if(typeof value == 'string'){
				e.alphanumeric = value;
			}
			callback(e);
		};
	}

	function register(id, handle){
		if(!registry[id]){
			registry[id] = [];
		}
		registry[id].push(handle);
	}

	function makeMultiHandle (handles){
		return {
			remove: function(){
				handles.forEach(function(h){
					// allow for a simple function in the list
					if(h.remove) {
						h.remove();
					}else if(typeof h === 'function'){
						h();
					}
				});
				handles = [];
				this.remove = this.pause = this.resume = function(){};
			},
			pause: function(){
				handles.forEach(function(h){ if(h.pause){ h.pause(); }});
			},
			resume: function(){
				handles.forEach(function(h){ if(h.resume){ h.resume(); }});
			}
		};
	}

	function onClickoff (node, callback){
	        var
	            mHandle,
	            handle,
	            bHandle = on(document.body, 'click', function(event){
	                if(!node.contains(event.target)) {
	                    callback(event);
	                }

	            });

	        mHandle = makeMultiHandle([lHandle, eHandle, bHandle]);

	        handle = {
	            resume: function () {
	                setTimeout(function () {
	                    mHandle.resume();
	                }, 100);
	            },
	            pause: function () {
	                mHandle.pause();
	            },
	            remove: function () {
	                mHandle.remove();
	            }
	        };

	        handle.pause();

	        return handle;
	    }

	function getNode(str){
		if(typeof str !== 'string'){
			return str;
		}
		var node;
		if(/\#|\.|\s/.test(str)){
			node = document.body.querySelector(str);
		}else{
			node = document.getElementById(str);
		}
		if(!node){
			console.error('localLib/on Could not find:', str);
		}
		return node;
	}

	function normalizeWheelEvent (callback){
		// normalizes all browsers' events to a standard:
		// delta, wheelY, wheelX
		// also adds acceleration and deceleration to make
		// Mac and Windows behave similarly
		return function(e){
			XLR8 += FACTOR;
			var
				deltaY = Math.max(-1, Math.min(1, (e.wheelDeltaY || e.deltaY))),
				deltaX = Math.max(-10, Math.min(10, (e.wheelDeltaX || e.deltaX)));

			deltaY = deltaY <= 0 ? deltaY - XLR8 : deltaY + XLR8;

			e.delta = deltaY;
			e.wheelY = deltaY;
			e.wheelX = deltaX;

			clearTimeout(mouseWheelHandle);
			mouseWheelHandle = setTimeout(function(){
				XLR8 = 0;
			}, 300);
			callback(e);
		};
	}

	function on (node, eventType, callback, optionalContext, id){
		//  USAGE
		//      var handle = on(this.node, 'mousedown', this, 'onStart');
		//      handle.pause();
		//      handle.resume();
		//      handle.remove();
		//
		var
			handles,
			handle,
			targetCallback,
			childTarget = false;

		if(/,/.test(eventType)){
			// handle multiple event types, like:
			// on(node, 'mouseup, mousedown', callback);
			//
			handles = [];
			eventType.split(',').forEach(function(eStr){
				handles.push(on(node, eStr.trim(), callback, optionalContext, id));
			});
			return makeMultiHandle(handles);
		}

		if(typeof optionalContext === 'string'){
			// no context. Last argument is handle id
			id = optionalContext;
			optionalContext = null;
		}

		node = getNode(node);
		callback = !!optionalContext ? callback.bind(optionalContext) : callback;

		if(/\s/.test(eventType)){
			// handle child selectors, like:
			// on(node, 'click .tab span', callback);
			//
			childTarget = eventType.substring(eventType.indexOf(' ') + 1, eventType.length);
			eventType = eventType.substring(0, eventType.indexOf(' '));
			targetCallback = callback;
			callback = function(e){
				var i, nodes, parent = on.ancestor(e.target, childTarget);
				if(parent){
					e.selectorTarget = parent;
					targetCallback(e);
				}else{
					nodes = node.querySelectorAll(childTarget);
					for(i = 0; i < nodes.length; i ++){
						if(nodes[i] === e.target || on.isAncestor(nodes[i], e.target)){
							e.selectorTarget = nodes[i];
							targetCallback(e);
							break;
						}
					}
				}
			};

		}

		if(eventType === 'clickoff'){
			// custom - used for popups 'n stuff
			return onClickoff(node, callback);
		}

		if(eventType === 'wheel'){
			// mousewheel events, natch
			if(has('wheel')){
				// pass through, but first curry callback to wheel events
				callback = normalizeWheelEvent(callback);
			}else{
				// old Firefox, old IE, Chrome
				return on.multi(node, {
					DOMMouseScroll:normalizeWheelEvent(callback),
					mousewheel:normalizeWheelEvent(callback)
				}, optionalContext);
			}
		}

		if(eventType.indexOf('key') > -1){
			callback = normalizeKeyEvent(callback);
		}

		node.addEventListener(eventType, callback, false);

		handle = {
			remove: function() {
				node.removeEventListener(eventType, callback, false);
				node = callback = null;
				this.remove = this.pause = this.resume = function(){};
			},
			pause: function(){
				node.removeEventListener(eventType, callback, false);
			},
			resume: function(){
				node.addEventListener(eventType, callback, false);
			}
		};

		if(id){
			// If an ID has been passed, register it so it can be used to
			// remove multiple events by id
			register(id, handle);
		}

		return handle;
	}

	on.multi = function(node, map, context, id){
		//  USAGE
		//      handle = on.multi(document, {
		//          "touchend":"onEnd",
		//          "touchcancel":"onEnd",
		//          "touchmove":this.method
		//      }, this);
		//
		var eventType,
			handles = [];

		for( eventType in map ){
			if(map.hasOwnProperty(eventType)){
				handles.push(on(node, eventType, map[eventType], context, id));
			}
		}

		return makeMultiHandle(handles);
	};

	on.remove = function(handles){
		// convenience function;
		// removes one or more handles;
		// accepts one handle or an array of handles;
		// accepts different types of handles (dispose/remove/topic token)
		//
		var i, h, idHandles;
		if(typeof handles === 'string'){
			idHandles = registry[handles];
			if(idHandles){
				idHandles.forEach(function(h){
					h.remove();
				});
				idHandles = registry[handles] = null;
				delete registry[handles];
			}

			return [];
		}
		handles = Array.isArray(handles) ? handles : [handles];

		for( i = 0; i < handles.length; i++ ){
			h = handles[i];

			if(h){ // check for nulls / already removed handles
				if(h.remove){
					// on handle, or AOP
					h.remove();
				}
				else if(h.dispose){
					// knockout
					h.dispose();
				}
				else if(typeof h === 'function'){
					// custom clean up
					h();
				}
			}
		}
		return [];
	};

	on.ancestor = function(node, selector){
		// gets the ancestor of node based on selector criteria
		// useful for getting the target node when a child node is clicked upon
		//
		// USAGE
		//      on.selector(childNode, '.app.active');
		//      on.selector(childNode, '#thinger');
		//      on.selector(childNode, 'div');
		//	DOES NOT SUPPORT:
		//		combinations of above
		var
			test,
			parent = node;

		if(selector.indexOf('.') === 0){
			// className
			selector = selector.replace('.', ' ').trim();
			test = function(n){
				return n.classList.contains(selector);
			};
		}
		else if(selector.indexOf('#') === 0){
			// node id
			selector = selector.replace('#', '').trim();
			test = function(n){
				return n.id === selector;
			};
		}
		else if(selector.indexOf('[') > -1){
			// attribute
			console.error('attribute selectors are not yet supported');
		}
		else{
			// assuming node name
			selector = selector.toUpperCase();
			test = function(n){
				return n.nodeName === selector;
			};
		}

		while(parent){
			if(parent === document.body || parent === document){ return false; }
			if(test(parent)){ break; }
			parent = parent.parentNode;
		}

		return parent;
	};

	on.isAncestor = function(parent, child){
		// determines if parent is an ancestor of child
		// returns boolean
		//
		if(parent === child){ return false; } // do we always want the same node to be false?
		while(child){
			if(child === parent){
				return true;
			}
			child = child.parentNode;
		}
		return false;
	};

	on.once = function (node, eventType, callback, optionalContext){
		var h = on(node, eventType, function () {
			callback.apply(optionalContext, arguments);
			h.remove();
		});
	};

	on.makeMultiHandle = makeMultiHandle;

	return on;

}));
<commit_msg>Fix 'clickoff' event Syntax Error<commit_after>/* UMD.define */ (function (root, factory) {
	if (typeof customLoader === 'function'){ customLoader(factory, 'on'); }else if (typeof define === 'function' && define.amd){ define([], factory); }else if(typeof exports === 'object'){ module.exports = factory(); }else{ root.returnExports = factory(); window.on = factory(); }
}(this, function () {
	// `on` is a simple library for attaching events to nodes. Its primary feature
	// is it returns a handle, from which you can pause, resume and remove the
	// event. Handles are much easier to manipulate than using removeEventListener
	// and recreating (sometimes complex or recursive) function signatures.
	//
	// `on` is touch-friendly and will normalize touch events.
	//
	// `on` also supports a custom `clickoff` event, to detect if you've clicked
	// anywhere in the document other than the passed node
	//
	// USAGE
	//      var handle = on(node, 'clickoff', callback);
	//      //  callback fires if something other than node is clicked
	//
	// USAGE
	//      var handle = on(node, 'mousedown', onStart);
	//      handle.pause();
	//      handle.resume();
	//      handle.remove();
	//
	//  `on` also supports multiple event types at once. The following example is
	//  useful for handling both desktop mouseovers and tablet clicks:
	//
	// USAGE
	//      var handle = on(node, 'mouseover,click', onStart);
	//
	//
	// `on` has an optional context parameter. The fourth argument can be 'this'
	// (or some other object) to conveniently avoid the use of var `self = this;`
	//
	//  USAGE
	//      var handle = on(this.node, 'mousedown', 'onStart', this);
	//
	// `on.multi` allows for connecting multiple events to a node at the same
	// time. Note this requires a context (I think), so it is not applicable for
	// anonymous functions.
	//
	//  USAGE
	//      handle = on.multi(document, {
	//          "touchend":"onEnd",
	//          "touchcancel":"onEnd",
	//          "touchmove":this.method
	//      }, this);
	//
	// `on` supports an optional ID that can be used to track connections to be
	// disposed later.
	//
	// USAGE
	//      on(node, 'click', callback, 'uid-a');
	//      on(node, 'mouseover', callback, 'uid-a');
	//      on(otherNode, 'click', callback, 'uid-a');
	//      on(document, 'load', callback, 'uid-a');
	//      on.remove('uid-a');
	//
	// `on` supports selectors, seperated from the event by a space:
	//
	// USAGE
	//      on(node, 'click div.tab span', callback);
	//

	function hasWheel(){
		var
			isIE = navigator.userAgent.indexOf('Trident') > -1,
			div = document.createElement('div');
		return  "onwheel" in div || "wheel" in div ||
			(isIE && document.implementation.hasFeature("Events.wheel", "3.0")); // IE feature detection
	}

	function has(what){
		switch(what){
			case 'wheel': return hasWheel();
		}
		return false;
	}

	function populateRange(keys, fromChar, toChar){
		for(var i = fromChar.charCodeAt(0), n = toChar.charCodeAt(0); i <= n; ++i){
			keys[i] = String.fromCharCode(i);
		}
	}

	var
		isWin = navigator.userAgent.indexOf('Windows')>-1,
		FACTOR = isWin ? 10 : 0.1,
		XLR8 = 0,
		mouseWheelHandle,
		//numCalls = 0,
		keyCodes = [], // it will be a sparse array to keep alphanumeric ASCII characters
		registry = {};

	populateRange(keyCodes, '0', '9');
	populateRange(keyCodes, 'a', 'z');
	populateRange(keyCodes, 'A', 'Z');

	function normalizeKeyEvent (callback){
		// Add alphanumeric property (the letter typed) to the KeyEvent
		//
		return function(e){
			// 48-57 0-9
			// 65 - 90 a-z
			var value = keyCodes[e.keyCode];
			if(typeof value == 'string'){
				e.alphanumeric = value;
			}
			callback(e);
		};
	}

	function register(id, handle){
		if(!registry[id]){
			registry[id] = [];
		}
		registry[id].push(handle);
	}

	function makeMultiHandle (handles){
		return {
			remove: function(){
				handles.forEach(function(h){
					// allow for a simple function in the list
					if(h.remove) {
						h.remove();
					}else if(typeof h === 'function'){
						h();
					}
				});
				handles = [];
				this.remove = this.pause = this.resume = function(){};
			},
			pause: function(){
				handles.forEach(function(h){ if(h.pause){ h.pause(); }});
			},
			resume: function(){
				handles.forEach(function(h){ if(h.resume){ h.resume(); }});
			}
		};
	}

	function onClickoff (node, callback){
	        var
	            handle,
	            bHandle = on(document.body, 'click', function(event){
	                if(!node.contains(event.target)) {
	                    callback(event);
	                }

	            });

	        handle = {
	            resume: function () {
	                setTimeout(function () {
	                    bHandle.resume();
	                }, 100);
	            },
	            pause: function () {
	                bHandle.pause();
	            },
	            remove: function () {
	                bHandle.remove();
	            }
	        };

	        handle.pause();

	        return handle;
	    }

	function getNode(str){
		if(typeof str !== 'string'){
			return str;
		}
		var node;
		if(/\#|\.|\s/.test(str)){
			node = document.body.querySelector(str);
		}else{
			node = document.getElementById(str);
		}
		if(!node){
			console.error('localLib/on Could not find:', str);
		}
		return node;
	}

	function normalizeWheelEvent (callback){
		// normalizes all browsers' events to a standard:
		// delta, wheelY, wheelX
		// also adds acceleration and deceleration to make
		// Mac and Windows behave similarly
		return function(e){
			XLR8 += FACTOR;
			var
				deltaY = Math.max(-1, Math.min(1, (e.wheelDeltaY || e.deltaY))),
				deltaX = Math.max(-10, Math.min(10, (e.wheelDeltaX || e.deltaX)));

			deltaY = deltaY <= 0 ? deltaY - XLR8 : deltaY + XLR8;

			e.delta = deltaY;
			e.wheelY = deltaY;
			e.wheelX = deltaX;

			clearTimeout(mouseWheelHandle);
			mouseWheelHandle = setTimeout(function(){
				XLR8 = 0;
			}, 300);
			callback(e);
		};
	}

	function on (node, eventType, callback, optionalContext, id){
		//  USAGE
		//      var handle = on(this.node, 'mousedown', this, 'onStart');
		//      handle.pause();
		//      handle.resume();
		//      handle.remove();
		//
		var
			handles,
			handle,
			targetCallback,
			childTarget = false;

		if(/,/.test(eventType)){
			// handle multiple event types, like:
			// on(node, 'mouseup, mousedown', callback);
			//
			handles = [];
			eventType.split(',').forEach(function(eStr){
				handles.push(on(node, eStr.trim(), callback, optionalContext, id));
			});
			return makeMultiHandle(handles);
		}

		if(typeof optionalContext === 'string'){
			// no context. Last argument is handle id
			id = optionalContext;
			optionalContext = null;
		}

		node = getNode(node);
		callback = !!optionalContext ? callback.bind(optionalContext) : callback;

		if(/\s/.test(eventType)){
			// handle child selectors, like:
			// on(node, 'click .tab span', callback);
			//
			childTarget = eventType.substring(eventType.indexOf(' ') + 1, eventType.length);
			eventType = eventType.substring(0, eventType.indexOf(' '));
			targetCallback = callback;
			callback = function(e){
				var i, nodes, parent = on.ancestor(e.target, childTarget);
				if(parent){
					e.selectorTarget = parent;
					targetCallback(e);
				}else{
					nodes = node.querySelectorAll(childTarget);
					for(i = 0; i < nodes.length; i ++){
						if(nodes[i] === e.target || on.isAncestor(nodes[i], e.target)){
							e.selectorTarget = nodes[i];
							targetCallback(e);
							break;
						}
					}
				}
			};

		}

		if(eventType === 'clickoff'){
			// custom - used for popups 'n stuff
			return onClickoff(node, callback);
		}

		if(eventType === 'wheel'){
			// mousewheel events, natch
			if(has('wheel')){
				// pass through, but first curry callback to wheel events
				callback = normalizeWheelEvent(callback);
			}else{
				// old Firefox, old IE, Chrome
				return on.multi(node, {
					DOMMouseScroll:normalizeWheelEvent(callback),
					mousewheel:normalizeWheelEvent(callback)
				}, optionalContext);
			}
		}

		if(eventType.indexOf('key') > -1){
			callback = normalizeKeyEvent(callback);
		}

		node.addEventListener(eventType, callback, false);

		handle = {
			remove: function() {
				node.removeEventListener(eventType, callback, false);
				node = callback = null;
				this.remove = this.pause = this.resume = function(){};
			},
			pause: function(){
				node.removeEventListener(eventType, callback, false);
			},
			resume: function(){
				node.addEventListener(eventType, callback, false);
			}
		};

		if(id){
			// If an ID has been passed, register it so it can be used to
			// remove multiple events by id
			register(id, handle);
		}

		return handle;
	}

	on.multi = function(node, map, context, id){
		//  USAGE
		//      handle = on.multi(document, {
		//          "touchend":"onEnd",
		//          "touchcancel":"onEnd",
		//          "touchmove":this.method
		//      }, this);
		//
		var eventType,
			handles = [];

		for( eventType in map ){
			if(map.hasOwnProperty(eventType)){
				handles.push(on(node, eventType, map[eventType], context, id));
			}
		}

		return makeMultiHandle(handles);
	};

	on.remove = function(handles){
		// convenience function;
		// removes one or more handles;
		// accepts one handle or an array of handles;
		// accepts different types of handles (dispose/remove/topic token)
		//
		var i, h, idHandles;
		if(typeof handles === 'string'){
			idHandles = registry[handles];
			if(idHandles){
				idHandles.forEach(function(h){
					h.remove();
				});
				idHandles = registry[handles] = null;
				delete registry[handles];
			}

			return [];
		}
		handles = Array.isArray(handles) ? handles : [handles];

		for( i = 0; i < handles.length; i++ ){
			h = handles[i];

			if(h){ // check for nulls / already removed handles
				if(h.remove){
					// on handle, or AOP
					h.remove();
				}
				else if(h.dispose){
					// knockout
					h.dispose();
				}
				else if(typeof h === 'function'){
					// custom clean up
					h();
				}
			}
		}
		return [];
	};

	on.ancestor = function(node, selector){
		// gets the ancestor of node based on selector criteria
		// useful for getting the target node when a child node is clicked upon
		//
		// USAGE
		//      on.selector(childNode, '.app.active');
		//      on.selector(childNode, '#thinger');
		//      on.selector(childNode, 'div');
		//	DOES NOT SUPPORT:
		//		combinations of above
		var
			test,
			parent = node;

		if(selector.indexOf('.') === 0){
			// className
			selector = selector.replace('.', ' ').trim();
			test = function(n){
				return n.classList.contains(selector);
			};
		}
		else if(selector.indexOf('#') === 0){
			// node id
			selector = selector.replace('#', '').trim();
			test = function(n){
				return n.id === selector;
			};
		}
		else if(selector.indexOf('[') > -1){
			// attribute
			console.error('attribute selectors are not yet supported');
		}
		else{
			// assuming node name
			selector = selector.toUpperCase();
			test = function(n){
				return n.nodeName === selector;
			};
		}

		while(parent){
			if(parent === document.body || parent === document){ return false; }
			if(test(parent)){ break; }
			parent = parent.parentNode;
		}

		return parent;
	};

	on.isAncestor = function(parent, child){
		// determines if parent is an ancestor of child
		// returns boolean
		//
		if(parent === child){ return false; } // do we always want the same node to be false?
		while(child){
			if(child === parent){
				return true;
			}
			child = child.parentNode;
		}
		return false;
	};

	on.once = function (node, eventType, callback, optionalContext){
		var h = on(node, eventType, function () {
			callback.apply(optionalContext, arguments);
			h.remove();
		});
	};

	on.makeMultiHandle = makeMultiHandle;

	return on;

}));
<|endoftext|>


<commit_before>// @flow

import * as React from 'react';
import styled from 'styled-components';

import { getPackingSlipData } from 'api/slips';
import { descFromValue } from 'lib/constants/bike-size';

const Pages = styled.div`
  @page {
    size: 8.5in 11in;
    margin: 0in;
  }
  & * {
    font-size: inherit;
  }
  & table {
    border-collapse: collapse;
  }
  & table, & th, & td {
    border: 1px solid black;
  }
  & td {
    vertical-align: top;
    padding: 5px;
  }

  font-family: Sans-Serif;
  font-size: 10pt;
  padding: 0;
  margin: 0;
`;

const Page = styled.div`
  page-break-after: always;
  page-break-inside: avoid;
  padding: 0.6in;
  width: 7.3in;
`;

async function packingSlip (household_id) {
  const data = await getPackingSlipData(household_id);

  return <Pages>{
    data.households.map(household => {
      const { address } = household;

      let cmpd_division = 'x';
      let cmpd_response_area = 'x';

      if (address) {
        cmpd_division = address.cmpd_division;
        cmpd_response_area = address.cmpd_response_area;
      }

      const familyNumber = `${cmpd_division || 'x' }-${cmpd_response_area || 'x' }-${household.id}`;

      return (
        <Page key={household.id}>

            Family Summary Sheet

            Referred By: { household.nominator_name }

            Affiliation: { household.nominator && household.nominator.affiliation.name } ({ household.nominator && household.nominator.affiliation.type })

              Division: { household.address && household.address.cmpd_division ? household.address.cmpd_division : '__' }

            Response Area:
              { household.address && household.address.cmpd_response_area ? household.address.cmpd_response_area : '___' }

              { familyNumber }

            Bicycles requested: { household.children.filter(child => child.bike_want).length }

Bicycles assigned: ____

              Name (First, Last)
 { household.name_last }, { household.name_first }

                Address
                { household.address ?

 { household.address.street }
                    { household.address.street2 ?

 { household.address.street2 }
                      : null }

 { household.address.city },
                    { household.address.state },
                    { household.address.zip }

                : 'Not available' }

                Phone Numbers
                { household.phones.map(phone =>

 { phone.number } ({ phone.type }))
                }

                Contact the warehouse for assistance at:

Phone: { data.assistance.phone }

Radio: { data.assistance.radio }

RETURN THIS DOCUMENT TO THE WAREHOUSE

                I certify that I have made the delivery to this location:

                  Officer Making Delivery - Printed Name

                  Check the first column below when toys for the child have been entered into their box

Children Information

              Done
              Name
              Sex
              Age
              Bike Requested
              Notes

            { household.children.map(child =>

              { child.name_first }
              { child.gender }
              { child.age }

                { child.bike_want ? `${descFromValue(child.bike_size)}\n${child.bike_style}` : 'no' }

                  { !child.clothes_want ? null : `
                    Shirt size: ${ child.clothes_size_shirt },
                    Pants size: ${ child.clothes_size_pants },
                    Shoe size: ${ child.shoe_size }
                  `}
                  { !child.favourite_colour ? null :
                    ` Favorite color: ${ child.favourite_colour }`
                  }
                  { !child.interests ? null :
                    ` Interests: ${ child.interests }`
                  }
                  { !child.ideas ? null :
                    ` Ideas: ${ child.ideas }`
                  }

)
            }

            Instructions: Officers, although a bike may be requested,
            there are not enough bikes for all requests. Please note the box
            to determine the number of bikes that have bee nassigned to this
            family. In the Bike Requested area, if a bike has been assigned,
            it will be circled for the child it has bee nassigned to.

Volunteers: If you are filling the family box
            for the children on this list, please enter the number of gifts
            you have put into the box for each child in the DONE box to the
            left of each child"s name.

        </Page>);
    })
  }
  </Pages>;
};

async function bicycleSlip(household_id) {
  let data = await getPackingSlipData(household_id);

  data = data.households.filter((household) => {
    const children = household.children.filter((child) => {
      return child.bike_want;
    });
    return children.length > 0;
  });

  return <Pages>{
    data.map(household => {
      const { address } = household;

      let cmpd_division = 'x';
      let cmpd_response_area = 'x';

      if (address) {
        cmpd_division = address.cmpd_division;
        cmpd_response_area = address.cmpd_response_area;
      }

      const familyNumber = `${cmpd_division || 'x' }-${cmpd_response_area || 'x' }-${household.id}`;

      return household.children.map((child) => {
        return (
        <Page key={`bikeSlip-Child-${child.id}`}>

                  {familyNumber}-{child.id}

                Address
                { household.address ?

{' '}{ household.address.street }
                    { household.address.street2 ?

{' '}{ household.address.street2 }
                      : null }

{' '}{ household.address.city }, {' '}
                    { household.address.state }, {' '}
                    { household.address.zip }

                : 'Not available' }

                Child (Last, First):
                {' '}{child.name_last} {child.name_first}

                Family (Last, First):
                {' '}{ household.name_last }, { household.name_first }

                Bike Requested

              Size
              Style

              {child.bike_size}
              { child.bike_style }

          {/* Force a page break... by cheating... because rushing */}

        </Page>);
      });
    })}
  </Pages>;
};

export { packingSlip, bicycleSlip };<commit_msg>Update packing slip child id and child age<commit_after>// @flow

import * as React from 'react';
import styled from 'styled-components';

import { getPackingSlipData } from 'api/slips';
import { descFromValue } from 'lib/constants/bike-size';

const moment = require('moment');

const Pages = styled.div`
  @page {
    size: 8.5in 11in;
    margin: 0in;
  }
  & * {
    font-size: inherit;
  }
  & table {
    border-collapse: collapse;
  }
  & table, & th, & td {
    border: 1px solid black;
  }
  & td {
    vertical-align: top;
    padding: 5px;
  }

  font-family: Sans-Serif;
  font-size: 10pt;
  padding: 0;
  margin: 0;
`;

const Page = styled.div`
  page-break-after: always;
  page-break-inside: avoid;
  padding: 0.6in;
  width: 7.3in;
`;

async function packingSlip (household_id) {
  const data = await getPackingSlipData(household_id);

  return <Pages>{
    data.households.map(household => {
      const { address } = household;

      let cmpd_division = 'x';
      let cmpd_response_area = 'x';

      if (address) {
        cmpd_division = address.cmpd_division;
        cmpd_response_area = address.cmpd_response_area;
      }

      const familyNumber = `${cmpd_division || 'x' }-${cmpd_response_area || 'x' }-${household.id}`;

      return (
        <Page key={household.id}>

            Family Summary Sheet

            Referred By: { household.nominator_name }

            Affiliation: { household.nominator && household.nominator.affiliation.name } ({ household.nominator && household.nominator.affiliation.type })

              Division: { household.address && household.address.cmpd_division ? household.address.cmpd_division : '__' }

            Response Area:
              { household.address && household.address.cmpd_response_area ? household.address.cmpd_response_area : '___' }

              { familyNumber }

            Bicycles requested: { household.children.filter(child => child.bike_want).length }

Bicycles assigned: ____

              Name (First, Last)
 { household.name_last }, { household.name_first }

                Address
                { household.address ?

 { household.address.street }
                    { household.address.street2 ?

 { household.address.street2 }
                      : null }

 { household.address.city },
                    { household.address.state },
                    { household.address.zip }

                : 'Not available' }

                Phone Numbers
                { household.phones.map(phone =>

 { phone.number } ({ phone.type }))
                }

                Contact the warehouse for assistance at:

Phone: { data.assistance.phone }

Radio: { data.assistance.radio }

RETURN THIS DOCUMENT TO THE WAREHOUSE

                I certify that I have made the delivery to this location:

                  Officer Making Delivery - Printed Name

                  Check the first column below when toys for the child have been entered into their box

Children Information

              ID
              Name
              Sex
              Age
              Bike Requested
              Notes

            { household.children.map(child =>

              { child.id }
              { child.name_first }
              { child.gender }
              {/* //TODO Not sure why Virtual field child.age is not working in model. Copied this logic from Nomination Report view.*/}
              { moment().diff(moment(child.dob).format('LL'), 'years') }

                { child.bike_want ? `${descFromValue(child.bike_size)}\n${child.bike_style}` : 'no' }

                  { !child.clothes_want ? null : `
                    Shirt size: ${ child.clothes_size_shirt },
                    Pants size: ${ child.clothes_size_pants },
                    Shoe size: ${ child.shoe_size }
                  `}
                  { !child.favourite_colour ? null :
                    ` Favorite color: ${ child.favourite_colour }`
                  }
                  { !child.interests ? null :
                    ` Interests: ${ child.interests }`
                  }
                  { !child.ideas ? null :
                    ` Ideas: ${ child.ideas }`
                  }

)
            }

            Instructions: Officers, although a bike may be requested,
            there are not enough bikes for all requests. Please note the box
            to determine the number of bikes that have bee nassigned to this
            family. In the Bike Requested area, if a bike has been assigned,
            it will be circled for the child it has bee nassigned to.

Volunteers: If you are filling the family box
            for the children on this list, please enter the number of gifts
            you have put into the box for each child in the DONE box to the
            left of each child"s name.

        </Page>);
    })
  }
  </Pages>;
};

async function bicycleSlip(household_id) {
  let data = await getPackingSlipData(household_id);

  data = data.households.filter((household) => {
    const children = household.children.filter((child) => {
      return child.bike_want;
    });
    return children.length > 0;
  });

  return <Pages>{
    data.map(household => {
      const { address } = household;

      let cmpd_division = 'x';
      let cmpd_response_area = 'x';

      if (address) {
        cmpd_division = address.cmpd_division;
        cmpd_response_area = address.cmpd_response_area;
      }

      const familyNumber = `${cmpd_division || 'x' }-${cmpd_response_area || 'x' }-${household.id}`;

      return household.children.map((child) => {
        return (
        <Page key={`bikeSlip-Child-${child.id}`}>

                  {familyNumber}-{child.id}

                Address
                { household.address ?

{' '}{ household.address.street }
                    { household.address.street2 ?

{' '}{ household.address.street2 }
                      : null }

{' '}{ household.address.city }, {' '}
                    { household.address.state }, {' '}
                    { household.address.zip }

                : 'Not available' }

                Child (Last, First):
                {' '}{child.name_last} {child.name_first}

                Family (Last, First):
                {' '}{ household.name_last }, { household.name_first }

                Bike Requested

              Size
              Style

              {child.bike_size}
              { child.bike_style }

          {/* Force a page break... by cheating... because rushing */}

        </Page>);
      });
    })}
  </Pages>;
};

export { packingSlip, bicycleSlip };
<|endoftext|>


<commit_before>var debug = require('debug')('p3api-server:FieldSelection');
var url = require("url");

module.exports = function(req, res, next) {
	if ((req.call_method !="query") && (req.call_method != "stream")){ return next(); }

	req.call_params[0] = req.call_params[0] || "&q=*:*";

	var parsed = url.parse("?"+req.call_params[0],true);
	if (parsed && parsed.query && parsed.query.fl){
		req.fieldSelection = parsed.query.fl.split(",");
	}else{

		switch(req.call_collection){
			case "genome_feature":
				req.fieldSelection = ["genome_name", "accession", "patric_id", "refseq_locus_tag", "alt_locus_tag", "feature_id",
						"annotation", "feature_type", "start", "end", "na_length", "strand", "protein_id", "aa_length", "gene", "product"
				];
				break;
			case "genome":
				req.fieldSelection = [
					"genome_id", "genome_name", "organism_name", "taxon_id", "genome_status",
					"strain", "serovar", "biovar", "pathovar", "mlst", "other_typing",
					"culture_collection", "type_strain","completion_date", "publication",
					"bioproject_accession", "biosample_accession", "assembly_accession", "genbank_accessions",
					"refseq_accessions","sequencing_centers", "sequencing_status", "sequencing_platform",
					"sequencing_depth", "assembly_method","chromosomes", "plasmids", "contigs", "sequences",
					"genome_length", "gc_content","patric_cds", "brc1_cds", "refseq_cds",
					"isolation_site", "isolation_source", "isolation_comments", "collection_date",
					"isolation_country", "geographic_location", "latitude", "longitude", "altitude", "depth", "other_environmental",
					"host_name", "host_gender", "host_age", "host_health", "body_sample_site", "body_sample_subsite", "other_clinical",
					"antimicrobial_resistance", "antimicrobial_resistance_evidence","gram_stain", "cell_shape", "motility",
					"sporulation", "temperature_range", "optimal_temperature", "salinity", "oxygen_requirement","habitat",
					"disease", "comments", "additional_metadata"
				]
				break;
		}
	}

	next();
}
<commit_msg>add more cases<commit_after>var debug = require('debug')('p3api-server:FieldSelection');
var url = require("url");

module.exports = function(req, res, next){
	if((req.call_method != "query") && (req.call_method != "stream")){
		return next();
	}

	req.call_params[0] = req.call_params[0] || "&q=*:*";

	const parsed = url.parse("?" + req.call_params[0], true);
	if(parsed && parsed.query && parsed.query.fl){
		req.fieldSelection = parsed.query.fl.split(",");
	}else{

		switch(req.call_collection){
			case "genome_feature":
				req.fieldHeader = [
					"Genome", "Genome ID", "Accession", "PATRIC ID", "RefSeq Locus Tag", "Alt Locus Tag",
					"Feature ID", "Annotation", "Feature Type", "Start", "End", "Length", "Strand", "FIGfam ID",
					"PATRIC genus-specific families (PLfams)", "PATRIC cross-genus families (PGfams)", "Protein ID",
					"AA Length", "Gene Symbol", "Product"
				];
				req.fieldSelection = [
					"genome_name", "genome_id", "accession", "patric_id", "refseq_locus_tag", "alt_locus_tag",
					"feature_id", "annotation", "feature_type", "start", "end", "na_length", "strand", "figfam_id",
					"plfam_id", "pgfam_id",
					"protein_id", "aa_length", "gene", "product"
				];
				break;
			case "genome":
				req.fieldHeader = [
					"Genome ID", "Genome Name", "Organism Name", "NCBI Taxon ID", "Genome Status",
					"Strain", "Serovar", "Biovar", "Pathovar", "MLST", "Other Typing",
					"Culture Collection", "Type Strain",
					"Completion Date", "Publication",
					"BioProject Accession", "BioSample Accession", "Assembly Accession", "GenBank Accessions",
					"RefSeq Accessions",
					"Sequencing Centers", "Sequencing Status", "Sequencing Platform", "Sequencing Depth", "Assembly Method",
					"Chromosomes", "Plasmids", "Contigs", "Sequences", "Genome Length", "GC Content",
					"PATRIC CDS", "BRC1 CDS", "RefSeq CDS",
					"Isolation Site", "Isolation Source", "Isolation Comments", "Collection Date",
					"Isolation Country", "Geographic Location", "Latitude", "Longitude", "Altitude", "Depth", "Other Environmental",
					"Host Name", "Host Gender", "Host Age", "Host Health", "Body Sample Site", "Body Sample Subsite", "Other Clinical",
					"AntiMicrobial Resistance", "AntiMicrobial Resistance Evidence",
					"Gram Stain", "Cell Shape", "Motility", "Sporulation", "Temperature Range", "Optimal Temperature", "Salinity", "Oxygen Requirement",
					"Habitat",
					"Disease", "Comments", "Additional Metadata", "Date Inserted", "Date Modified"
				];
				req.fieldSelection = [
					"genome_id", "genome_name", "organism_name", "taxon_id", "genome_status",
					"strain", "serovar", "biovar", "pathovar", "mlst", "other_typing",
					"culture_collection", "type_strain",
					"completion_date", "publication",
					"bioproject_accession", "biosample_accession", "assembly_accession", "genbank_accessions",
					"refseq_accessions",
					"sequencing_centers", "sequencing_status", "sequencing_platform", "sequencing_depth", "assembly_method",
					"chromosomes", "plasmids", "contigs", "sequences", "genome_length", "gc_content",
					"patric_cds", "brc1_cds", "refseq_cds",
					"isolation_site", "isolation_source", "isolation_comments", "collection_date",
					"isolation_country", "geographic_location", "latitude", "longitude", "altitude", "depth", "other_environmental",
					"host_name", "host_gender", "host_age", "host_health", "body_sample_site", "body_sample_subsite", "other_clinical",
					"antimicrobial_resistance", "antimicrobial_resistance_evidence",
					"gram_stain", "cell_shape", "motility", "sporulation", "temperature_range", "optimal_temperature", "salinity", "oxygen_requirement",
					"habitat",
					"disease", "comments", "additional_metadata", "date_inserted", "date_modified"
				];
				break;
			case "genome_sequence":
				req.fieldHeader = [
					"Genome ID", "Genome Name", "Sequence ID", "GI", "Accession", "Sequence Type", "Topology", "Description",
					"GC Content", "Length (bp)", "Release Date", "Version"
				];
				req.fieldSelection = [
					"genome_id", "genome_name", "sequence_id", "gi", "accession", "sequence_type", "topology", "description",
					"gc_content", "length", "release_date", "version"
				];
				break;
			case "sp_gene":
				req.fieldHeader = [
					"Evidence", "Property", "Source", "Genome Name", "PATRIC ID", "RefSeq Locus Tag", "Alt Locus Tag", "Source ID",
					"Source Organism", "Gene", "Product", "Function", "Classification", "PubMed", "Subject Coverage", "Query Coverage",
					"Identity", "E-value"
				];
				req.fieldSelection = [
					"evidence", "property", "source", "genome_name", "patric_id", "refseq_locus_tag", "alt_locus_tag", "source_id",
					"organism", "gene", "product", "function", "classification", "pmid", "subject_coverage", "query_coverage", "identity",
					"e_value"
				];
				break;
			case "sp_gene_ref":
				req.fieldHeader = [
					"Property", "Source", "Source ID", "Gene", "Organism", "Locus Tag", "Gene ID", "GI", "Product",
					"Function", "Classification", "PubMed"
				];
				req.fieldSelection = [
					"property", "source", "source_id", "gene_name", "organism", "locus_tag", "gene_id", "gi", "product",
					"function", "classification", "pmid"
				];
				break;
			case "transcriptomics_experiment":
				req.fieldHeader = [
					"Experiment ID", "Title", "Comparisons", "Genes", "PubMed", "Accession", "Organism", "Strain",
					"Gene Modification", "Experimental Condition", "Time Series", "Release Date", "Author", "PI", "Institution"
				];
				req.fieldSelection = [
					"eid", "title", "samples", "genes", "pmid", "accession", "organism", "strain", "mutant",
					"condition", "timeseries", "release_date", "author", "pi", "institution"
				];
				break;
			case "transcriptomics_comparison":
				req.fieldHeader = [
					"Experiment ID", "Comparison ID", "Title", "Genes", "Significant genes(Log Ratio)",
					"Significant genes(Z Score)", "PubMed", "Accession", "Organism", "Strain", "Gene Modification", "Experiment Condition",
					"Time Point", "Release Date"
				];
				req.fieldSelection = [
					"eid", "pid", "expname", "genes", "sig_log_ratio", "sig_z_score", "pmid", "accession",
					"organism", "strain", "mutant", "condition", "timepoint", "release_date"
				];
				break;
			default:
				break;
		}
	}

	next();
};
<|endoftext|>


<commit_before>
exports.up = function(knex, Promise) {
    return Promise.all([

        // Create the object table:
        knex.schema.createTable('page_object', function (table) {
            table.bigIncrements('id').primary().unsigned();
            table.string('name',128);
        }),

        // Create the data table:
        knex.schema.createTable('page_data', function (table) {
            table.bigIncrements('id').primary().unsigned();
            table.bigInteger('object_id').unsigned().index().references('id').inTable('object');
            table.string('value',64);
        }),

        // Create the history table:
        knex.schema.createTable('page_history', function (table) {
            table.bigIncrements('id').primary().unsigned();
            table.bigInteger('object_id').unsigned().index().references('id').inTable('object');
            table.bigInteger('data_id').unsigned().index().references('id').inTable('data');

            table.timestamp('created_at').defaultTo(knex.raw('now()'));
            table.timestamp('updated_at').defaultTo(knex.raw('now()'));
            table.timestamp('applicable_at').defaultTo(knex.raw('now()'));
        }),

    ]);
};

exports.down = function(knex, Promise) {
    return Promise.all([
        // Remove the object table:
        knex.schema.dropTable('page_history'),
        knex.schema.dropTable('page_data'),
        knex.schema.dropTable('page_object'),
    ]);
};
<commit_msg>Updating the migration page<commit_after>
exports.up = function(knex, Promise) {
    return Promise.all([

        // Create the object table:
        knex.schema.createTable('page_object', function (table) {
            table.bigIncrements('id').primary().unsigned();
            table.string('name',128);
        }),

        // Create the data table:
        knex.schema.createTable('page_data', function (table) {
            table.bigIncrements('id').primary().unsigned();
            table.bigInteger('object_id').unsigned().index().references('id').inTable('page_object');
            table.string('value',64);
        }),

        // Create the history table:
        knex.schema.createTable('page_history', function (table) {
            table.bigIncrements('id').primary().unsigned();
            table.bigInteger('object_id').unsigned().index().references('id').inTable('page_object');
            table.bigInteger('data_id').unsigned().index().references('id').inTable('page_data');

            table.timestamp('created_at').defaultTo(knex.raw('now()'));
            table.timestamp('updated_at').defaultTo(knex.raw('now()'));
            table.timestamp('applicable_at').defaultTo(knex.raw('now()'));
        }),

    ]);
};

exports.down = function(knex, Promise) {
    return Promise.all([
        // Remove the object table:
        knex.schema.dropTable('page_history'),
        knex.schema.dropTable('page_data'),
        knex.schema.dropTable('page_object'),
    ]);
};
<|endoftext|>


<commit_before>/* Copyright 2016 Streampunk Media Ltd.

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

var redioactive = require('../../../util/Redioactive.js');
var util = require('util');
var Promise = require('promise');
var macadam = require('macadam');
var Grain = require('../../../model/Grain.js');

module.exports = function (RED) {
  function SDIOut (config) {
    RED.nodes.createNode(this, config);
    redioactive.Spout.call(this, config);

    this.srcFlow = null;
    var count = 0;
    var playback = null;
    var node = this;

    this.each(function (x, next) {
      if (!Grain.isGrain(x)) {
        node.warn('Received non-Grain payload.');
        return next();
      }
      var nextJob = (node.srcFlow) ?
        Promise.resolve(x) :
        (Promise.denodeify(node.getNMOSFlow, 1))(x)
        .then(function (f) {
          node.srcFlow = f;
          if (f.tags.format[0] !== 'video') {
            return node.preFlightError('Only video sources supported for SDI out.');
          }
          var bmMode = macadam.bmdModeHD1080i50;
          var bmFormat = macadam.bmdFormat8BitYUV;
          // switch (+f.tags.height[0]) {
          //   case 2160:
          //   case 1080:
          //     switch (x.getDuration()[0]) {
          //       case
          //     }
          //     break;
          //   case 720:
          //   case 576:
          //   case 486:
          //   default:
          //     node.preFlightError('Could not establish Blackmagic mode.');
          // }
          console.log('***', bmMode, bmFormat);
          playback = new macadam.Playback(config.deviceIndex,
            bmMode, bmFormat);
          playback.on('error', function (e) {
            node.warn(`Received playback error from Blackmagic card: ${e}`);
            next();
          });
          return x;
        });
      nextJob.then(function (g) {
        if (count < config.frameCache) {
          playback.frame(g.buffers[0]);
          next();
        } else {
          playback.once('playback', function () {
            playback.frame(g.buffers[0]);
            next();
          });
        };
      })
      .catch(function (err) {
        node.error(`Failed to play video on device '${config.deviceIndex}': ${err}`);
      });
    });

    node.errors(function (e, next) {
      node.warn(`Received unhandled error: ${e.message}.`);
      setImmediate(next);
    });
    node.done(function () {
      node.log('No more to see here!');
      playback.stop();
    });
    node.close(function () {
      node.log('Closing the speaker - too loud!');
      playback.stop();
    });
  }
  util.inherits(SDIOut, redioactive.Spout);
  RED.nodes.registerType("sdi-out", SDIOut);
}
<commit_msg>Ensuring tests don't fail on linux with Macadam included.<commit_after>/* Copyright 2016 Streampunk Media Ltd.

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

var redioactive = require('../../../util/Redioactive.js');
var util = require('util');
var Promise = require('promise');
var macadam;
try { macadam = require('macadam'); } catch(err) { console.log('SDI-Out: ' + err); }
var Grain = require('../../../model/Grain.js');

module.exports = function (RED) {
  function SDIOut (config) {
    RED.nodes.createNode(this, config);
    redioactive.Spout.call(this, config);

    this.srcFlow = null;
    var count = 0;
    var playback = null;
    var node = this;

    this.each(function (x, next) {
      if (!Grain.isGrain(x)) {
        node.warn('Received non-Grain payload.');
        return next();
      }
      var nextJob = (node.srcFlow) ?
        Promise.resolve(x) :
        (Promise.denodeify(node.getNMOSFlow, 1))(x)
        .then(function (f) {
          node.srcFlow = f;
          if (f.tags.format[0] !== 'video') {
            return node.preFlightError('Only video sources supported for SDI out.');
          }
          var bmMode = macadam.bmdModeHD1080i50;
          var bmFormat = macadam.bmdFormat8BitYUV;
          // switch (+f.tags.height[0]) {
          //   case 2160:
          //   case 1080:
          //     switch (x.getDuration()[0]) {
          //       case
          //     }
          //     break;
          //   case 720:
          //   case 576:
          //   case 486:
          //   default:
          //     node.preFlightError('Could not establish Blackmagic mode.');
          // }
          console.log('***', bmMode, bmFormat);
          playback = new macadam.Playback(config.deviceIndex,
            bmMode, bmFormat);
          playback.on('error', function (e) {
            node.warn(`Received playback error from Blackmagic card: ${e}`);
            next();
          });
          return x;
        });
      nextJob.then(function (g) {
        if (count < config.frameCache) {
          playback.frame(g.buffers[0]);
          next();
        } else {
          playback.once('playback', function () {
            playback.frame(g.buffers[0]);
            next();
          });
        };
      })
      .catch(function (err) {
        node.error(`Failed to play video on device '${config.deviceIndex}': ${err}`);
      });
    });

    node.errors(function (e, next) {
      node.warn(`Received unhandled error: ${e.message}.`);
      setImmediate(next);
    });
    node.done(function () {
      node.log('No more to see here!');
      playback.stop();
    });
    node.close(function () {
      node.log('Closing the speaker - too loud!');
      playback.stop();
    });
  }
  util.inherits(SDIOut, redioactive.Spout);
  RED.nodes.registerType("sdi-out", SDIOut);
}
<|endoftext|>


<commit_before>define(['readline',
'colors'],
function (readline, colors) {

  // return singleton
  var instance;
  return (function () {
    if (!instance) {
      // instance = readline.createInterface({
      //   input: process.stdin,
      //   output: process.stdout
      // });
      process.stdin.setEncoding('utf8');
      instance = {};
      instance.ask = function (query, cb) {
        process.stdin.write(query.grey);
        process.stdin.on('readable', function() {
          var chunk = process.stdin.read();
          if (chunk !== null) {
            chunk = chunk.slice(0, chunk.length - 1);
            cb(chunk);
          }
        });
      };
      instance.close = function () {
        process.stdin.end();
      };
    }
    return instance;
  })();
});
<commit_msg>fix rl<commit_after>define(['readline',
'colors'],
function (readline, colors) {

  // return singleton
  var instance;
  return (function () {
    if (!instance) {
      // instance = readline.createInterface({
      //   input: process.stdin,
      //   output: process.stdout
      // });
      // instance.ask = function (query, cb) {
      //   instance.question(query, cb);
      // }

      process.stdin.setEncoding('utf8');
      instance = {};
      process.stdin.on('readable', function() {
        var chunk = process.stdin.read();
        if (chunk !== null) {
          chunk = chunk.slice(0, chunk.length - 1);
          if (instance.toCb)
          instance.toCb(chunk);
        }
      });
      instance.ask = function (query, cb) {
        process.stdout.write(query.grey);
        instance.toCb = cb;
      };
      instance.close = function () {
        process.stdin.end();
      };
    }
    return instance;
  })();
});
<|endoftext|>


<commit_before>/*

_____                                                   ______           _   _
|  __ \                                                 |  ____|         | | | |
| |  | | ___ _ __ ___   ___   ___ _ __ __ _  ___ _   _  | |__   __ _ _ __| |_| |__
| |  | |/ _ \ '_ ` _ \ / _ \ / __| '__/ _` |/ __| | | | |  __| / _` | '__| __| '_ \
| |__| |  __/ | | | | | (_) | (__| | | (_| | (__| |_| |_| |___| (_| | |  | |_| | | |
|_____/ \___|_| |_| |_|\___/ \___|_|  \__,_|\___|\__, (_)______\__,_|_|   \__|_| |_/
                                                  __/ |
                                                 |___/

"You never change things by fighting the existing reality. To change something
build a new model that makes the existing model obsolete."
Buckminster Fuller, Great San Francisco Architect.

A Roma, <3

*/
import { Meteor } from 'meteor/meteor';
import { Collectives } from '../../api/collectives/Collectives';

// This script runs the first time Democracy Earth gets implemented on a server.
console.log(Meteor.settings.public.app.name + ' version: ' + Meteor.settings.public.app.version + ' codename: ' + Meteor.settings.public.app.codename );

function setupCollectiveInApp(collective) {
  Meteor.settings.public.Collective._id = collective._id;
  console.log('This server is being run by collective ' + collective.name);
  console.log('The collective can be reached with id ' + collective._id);
}

Meteor.startup(() => {
  // App Cache
  /* appcache issue with browser test: infinite loop
  console.log('[startup] app cache: ' + Meteor.settings.public.app.config.appCache)
  Meteor.AppCache.config({
    chrome: Meteor.settings.public.app.config.appCache,
    firefox: Meteor.settings.public.app.config.appCache,
    safari: Meteor.settings.public.app.config.appCache
  });
  */
  console.log('Verifiying main Collective in server...');
  const dbCollective = Collectives.findOne({ domain: Meteor.settings.public.Collective.domain });
  if (dbCollective) {
    setupCollectiveInApp(dbCollective);
  } else {
    // Organization has no Collective in db yet
    console.log('Installing democracy in server...');
    if (Meteor.settings.public.Collective === undefined) {
      console.log('-- MISSING SETTING: Collective was not found. Please setup settings.json on config/development')
    } else {
      console.log('Setting up main Collective in database...');
      Collectives.insert(Meteor.settings.public.Collective, function(error, result) {
        if (error) console.log ( "-- ERROR: Could not add main collective to database. " + error );
        if (result) {
          console.log ( "SUCCESS: Main collective set up with id " + result );
          setupCollectiveInApp(Collectives.findOne({ domain: Meteor.settings.public.Collective.domain }));
        }
      });
    }
  }
});
<commit_msg>key config validation<commit_after>/*

_____                                                   ______           _   _
|  __ \                                                 |  ____|         | | | |
| |  | | ___ _ __ ___   ___   ___ _ __ __ _  ___ _   _  | |__   __ _ _ __| |_| |__
| |  | |/ _ \ '_ ` _ \ / _ \ / __| '__/ _` |/ __| | | | |  __| / _` | '__| __| '_ \
| |__| |  __/ | | | | | (_) | (__| | | (_| | (__| |_| |_| |___| (_| | |  | |_| | | |
|_____/ \___|_| |_| |_|\___/ \___|_|  \__,_|\___|\__, (_)______\__,_|_|   \__|_| |_/
                                                  __/ |
                                                 |___/

"You never change things by fighting the existing reality. To change something
build a new model that makes the existing model obsolete."
Buckminster Fuller, Great San Francisco Architect.

A Roma, <3

*/
import { Meteor } from 'meteor/meteor';
import { Collectives } from '../../api/collectives/Collectives';

// This script runs the first time Democracy Earth gets implemented on a server.
console.log(Meteor.settings.public.app.name + ' version: ' + Meteor.settings.public.app.version + ' codename: ' + Meteor.settings.public.app.codename );

function setupCollectiveInApp(collective) {
  Meteor.settings.public.Collective._id = collective._id;
  console.log('This server is being run by collective ' + collective.name);
  console.log('The collective can be reached with id ' + collective._id);
}

Meteor.startup(() => {
  // App Cache
  /* appcache issue with browser test: infinite loop
  console.log('[startup] app cache: ' + Meteor.settings.public.app.config.appCache)
  Meteor.AppCache.config({
    chrome: Meteor.settings.public.app.config.appCache,
    firefox: Meteor.settings.public.app.config.appCache,
    safari: Meteor.settings.public.app.config.appCache
  });
  */
  console.log('Verifiying main Collective in server...');
  const dbCollective = Collectives.findOne({ domain: Meteor.settings.public.Collective.domain });
  if (dbCollective) {
    setupCollectiveInApp(dbCollective);
  } else {
    // Organization has no Collective in db yet
    console.log('Installing democracy in server...');
    if (Meteor.settings.public.Collective === undefined) {
      console.log('-- MISSING SETTING: Collective was not found. Please setup settings.json on config/development')
    } else {
      console.log('Setting up main Collective in database...');
      Collectives.insert(Meteor.settings.public.Collective, function(error, result) {
        if (error) console.log ( "-- ERROR: Could not add main collective to database. " + error );
        if (result) {
          console.log ( "SUCCESS: Main collective set up with id " + result );
          setupCollectiveInApp(Collectives.findOne({ domain: Meteor.settings.public.Collective.domain }));
        }
      });
    }
  }

  console.log('Verifying key configuration for this instance...');

  //AWS
  if (Meteor.settings.AWSAccessKeyId == undefined || Meteor.settings.AWSAccessKeyId == "") {
    console.log('-- MISSING SETTING: Amazon Web Services for resource storage keys not configured.');
    console.log('-- FIX: Configure `AWSAccessKeyId`, `AWSSecretAccessKey` and `public.AWSHostingURL` on settings.json.');
  } else {
    console.log('Amazon Web Services for resource storage in cloud... OK');
  }

  //smtpServer
  if (Meteor.settings.smtpServer == undefined || Meteor.settings.smtpServer == "") {
    console.log('-- MISSING SETTING: Mailgun SMTP server keys not configured.');
    console.log('-- FIX: Configure `smtpServer` on settings.json.');
  } else {
    console.log('Mailgun SMTP server for e-mail notificiations... OK');
  }

  //Facebook
  if (Meteor.settings.private.API.facebook.appId == undefined || Meteor.settings.private.API.facebook.appId == "") {
    console.log('-- MISSING SETTING: Facebook API keys not configured.');
    console.log('-- FIX: Configure `private.API.facebook.appId` and `private.API.facebook.appSecret` on settings.json.');
  } else {
    console.log('Facebook API key for identity login... OK');
  }

  //Twitter
  if (Meteor.settings.private.API.twitter.APIKey == undefined || Meteor.settings.private.API.twitter.APIKey == "") {
    console.log('-- MISSING SETTING: Twitter API keys not configured.');
    console.log('-- FIX: Configure `private.API.twitter.APIKey` and `private.API.twitter.APISecret` on settings.json.');
  } else {
    console.log('Twitter API key for identity login... OK');
  }

  //Google Analytics
  if (Meteor.settings.public.analyticsSettings["Google Analytics"].trackingId == undefined || Meteor.settings.public.analyticsSettings["Google Analytics"].trackingId == "") {
    console.log('-- MISSING SETTING: Google Analytics tracking ID not configured.');
    console.log('-- FIX: Configure `public.analyticsSettings["Google Analytics"].trackingId` on settings.json.');
  } else {
    console.log('Google Analytics tracking ID... OK');
  }

  //Kadira
  if (Meteor.settings.kadira.appId == undefined || Meteor.settings.kadira.appId == "") {
    console.log('-- MISSING SETTING: Kadira keys for performance app testing not configured.');
    console.log('-- FIX: Configure `kadira.appId` and `kadira.appSecret` on settings.json.');
  } else {
    console.log('Kadira keys for performance app testing... OK');
  }
});
<|endoftext|>


<commit_before>
var KrempelAirApp = angular.module('KrempelAirApp', []);
var uri = "/api"
KrempelAirApp.controller('AirFlowController', function AirFlowController($scope, $http, $timeout) {

    $scope.Refresh = function(){
        $http.get(uri+"/").then(function (response) {
            $scope.status = response.data;
        });
        $http.get(uri+"/stoerung").then(function (response) {
            $scope.stoerung = response.data;
        });
        $timeout(function(){
         $scope.Refresh();
        },800);
    }
    $scope.Klick = function(Klick){
        $http.get(uri+"/lueftung/stufe/"+Klick);
        $scope.Refresh();
    }

    $scope.Refresh();

});
<commit_msg>added /lueftung/temperatur<commit_after>
var KrempelAirApp = angular.module('KrempelAirApp', []);
var uri = "/api"
KrempelAirApp.controller('AirFlowController', function AirFlowController($scope, $http, $timeout) {

    $scope.Refresh = function(){
        $http.get(uri+"/").then(function (response) {
            $scope.status = response.data;
        });
        $http.get(uri+"/stoerung").then(function (response) {
            $scope.stoerung = response.data;
        });
        $http.get(uri+"/lueftung/temperatur").then(function (response) {
            $scope.temperatur = response.data;
        });
        $timeout(function(){
         $scope.Refresh();
        },800);
    }
    $scope.Klick = function(Klick){
        $http.get(uri+"/lueftung/stufe/"+Klick);
        $scope.Refresh();
    }

    $scope.Refresh();

});
<|endoftext|>


<commit_before>/* eslint-disable no-console, no-use-before-define */

import path from 'path'
import Express from 'express'
import qs from 'qs'

import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from '../webpack.config'

import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'

import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
import { fetchCounter } from '../common/api/counter'

const app = new Express()
const port = 3000

// Use this middleware to set up hot module reloading via webpack.
const compiler = webpack(webpackConfig)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }))
app.use(webpackHotMiddleware(compiler))

// This is fired every time the server side receives a request
app.use(handleRender)

function handleRender(req, res) {
  // Query our mock API asynchronously
  fetchCounter(apiResult => {
    // Read the counter from the request, if provided
    const params = qs.parse(req.query)
    const counter = parseInt(params.counter, 10) || apiResult || 0

    // Compile an initial state
    const preloadedState = { counter }

    // Create a new Redux store instance
    const store = configureStore(preloadedState)

    // Render the component to a string
    const html = renderToString(
      <Provider store={store}>
        <App />
      </Provider>
    )

    // Grab the initial state from our Redux store
    const finalState = store.getState()

    // Send the rendered page back to the client
    res.send(renderFullPage(html, finalState))
  })
}

function renderFullPage(html, preloadedState) {
  return `
    <!doctype html>

        <title>Redux Universal Example</title>

${html}

    `
}

app.listen(port, (error) => {
  if (error) {
    console.error(error)
  } else {
    console.info(`==> 🌎  Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`)
  }
})
<commit_msg>fixes xss vulnerability in universal example, #1855 (#1856)<commit_after>/* eslint-disable no-console, no-use-before-define */

import path from 'path'
import Express from 'express'
import qs from 'qs'

import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from '../webpack.config'

import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'

import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
import { fetchCounter } from '../common/api/counter'

const app = new Express()
const port = 3000

// Use this middleware to set up hot module reloading via webpack.
const compiler = webpack(webpackConfig)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }))
app.use(webpackHotMiddleware(compiler))

// This is fired every time the server side receives a request
app.use(handleRender)

function handleRender(req, res) {
  // Query our mock API asynchronously
  fetchCounter(apiResult => {
    // Read the counter from the request, if provided
    const params = qs.parse(req.query)
    const counter = parseInt(params.counter, 10) || apiResult || 0

    // Compile an initial state
    const preloadedState = { counter }

    // Create a new Redux store instance
    const store = configureStore(preloadedState)

    // Render the component to a string
    const html = renderToString(
      <Provider store={store}>
        <App />
      </Provider>
    )

    // Grab the initial state from our Redux store
    const finalState = store.getState()

    // Send the rendered page back to the client
    res.send(renderFullPage(html, finalState))
  })
}

function renderFullPage(html, preloadedState) {
  return `
    <!doctype html>

        <title>Redux Universal Example</title>

${html}

    `
}

app.listen(port, (error) => {
  if (error) {
    console.error(error)
  } else {
    console.info(`==> 🌎  Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`)
  }
})
<|endoftext|>


<commit_before>/**
 * @fileOverview Middleware for serving static resources.
 */

var {Response} = require("ringo/webapp/response");
var {mimeType} = require("ringo/webapp/mime");

/**
 * Middleware for serving static resources.
 *
 * #### Configuration properties
 *
 *  The `config` object may contain the following properties:
 *  - `base`: the base resource directory (required)
 *  - `index`: the name of a file to serve if the path matches a directory (e.g.
 *    "index.html")
 *
 * @param {Object} config configuration properties
 * @returns {Function} a function that can be used to wrap a JSGI app
 */
exports.middleware = function(config) {
    var resourceBase = config.base || config;
    if (typeof resourceBase === "string") {
        resourceBase = getRepository(resourceBase);
    }
    resourceBase.setRoot();
    var index = config.index;
    return function(app) {
        return function(request) {
            var path = request.pathInfo;
            if (index && path.charAt(path.length-1) === "/") {
                path += index;
            }
            if (path.length > 1) {
                var resource = resourceBase.getResource(path);
                if (resource && resource.exists()) {
                    return Response.static(resource, mimeType(path, "text/plain"));
                }
            }
            return app(request);
        }
    }
};
<commit_msg>Stricter checking for base arg.<commit_after>/**
 * @fileOverview Middleware for serving static resources.
 */

var {Response} = require("ringo/webapp/response");
var {mimeType} = require("ringo/webapp/mime");

/**
 * Middleware for serving static resources.
 *
 * #### Configuration properties
 *
 *  The `config` object may contain the following properties:
 *  - `base`: the base resource directory (required)
 *  - `index`: the name of a file to serve if the path matches a directory (e.g.
 *    "index.html")
 *
 * @param {Object} config configuration properties
 * @returns {Function} a function that can be used to wrap a JSGI app
 */
exports.middleware = function(config) {
    var index, base;
    if (typeof config === "string" || config instanceof org.ringojs.repository.Repository) {
        base = config;
    } else {
        base = config.base;
        index = config.index;
    }
    if (typeof base === "string") {
        base = getRepository(base);
    }
    base.setRoot();
    return function(app) {
        return function(request) {
            var path = request.pathInfo;
            if (index && path.charAt(path.length-1) === "/") {
                path += index;
            }
            if (path.length > 1) {
                var resource = base.getResource(path);
                if (resource && resource.exists()) {
                    return Response.static(resource, mimeType(path, "text/plain"));
                }
            }
            return app(request);
        }
    }
};
<|endoftext|>


<commit_before>var gamepads = {};
var haveEvents = 'GamepadEvent' in window;
var haveWebkitEvents = 'WebKitGamepadEvent' in window;
var socket = io();
var command;
var scan;
//handles connection and disconnection of gamepads
function gamepadHandler(event, connecting) {
  var gamepad = event.gamepad;
  // Note:
  // gamepad === navigator.getGamepads()[gamepad.index]

  if (connecting) {
    gamepads[gamepad.index] = gamepad;
    console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
      gamepad.index, gamepad.id,
      gamepad.buttons.length, gamepad.axes.length);
    console.log(gamepads[gamepad.index])
    socket.emit("gamepad", "connected")
    commandLoop();
  } else {
    delete gamepads[gamepad.index];
    console.log("Gamepad disconnected from index %d: %s",
      gamepad.index, gamepad.id);
    socket.emit("gamepad","disconnected")
  }
}

//function keeps getting values from first gamepad checking axis 0 and 1 for x y values respectively.
//maps values to left right motors and again maps that to axis 2, throttle.
function commandLoop () {
  scangamepads();
  var gamepadconnected = false;
  var j;
  for (j in gamepads) {
    var gamepad = gamepads[j];
    if (gamepadconnected) {
    }
    else if (gamepad) {
      if (gamepad.connected) {
        gamepadconnected = true;
        var axis = gamepad.axes;
        var data = {valueL: 0, valueR: 0}
        //when switched to mode Orange with button 24, tank drive active
        // axis 2 (throttle) is left and joystick is right.
        if(gamepad.buttons[25].pressed){
          data.valueL=0;
          data.valueR=0;
        }
        else if (gamepad.buttons[24].pressed) {
          var right = -axis[1];
          var left = -axis[2];
          data.valueL = left;
          data.valueR = right;
        } else {
          var drivePower = deadspace(-axis[1]);
          var turnPower = deadspace(axis[0]);
          var throttle = (-axis[2]+1)/2;
          console.log("throttle = " + throttle)
          console.log("turnPower = " + turnPower)
          console.log("drivePower = " + drivePower)
          data.valueL = (drivePower + turnPower)*throttle;
          data.valueR = (drivePower - turnPower)*throttle;
          data = limit(data)
        }
        //data should be values between -1 and 1
        socket.emit("serialOut", data);
        console.log(data)

        var pan = {x:0, y:0}
        pan.x = gamepad.buttons[20].value-gamepad.buttons[22].value
        pan.y = gamepad.buttons[19].value-gamepad.buttons[21].value
        socket.emit("pipan",pan)
        if(pan.x === 1) {
            //camera right
            servo_right()
        }
        else if(pan.x === -1) {
            //camera left
            servo_left()
        }
        if(pan.y === 1) {
            //camera up
            servo_up()
        }
        else if(pan.y === -1) {
            //camera down
            servo_down()
        }
      }
    }
  }
  if (gamepadconnected) {
    setTimeout(commandLoop,100)
  }
}

//removes deadspace by translating such space to be 0.
function deadspace(value) {
  if(Math.abs(value)<0.03) {
    value = 0;
  }
  return value;
}

//limits power to -1 and 1
function limit( data ) {
  if (Math.abs(data.valueL)>1) {
    data.valueR = data.valueR/Math.abs(data.valueL);
    data.valueL = data.valueL/Math.abs(data.valueL);
  }

  if (Math.abs(data.valueR)>1) {
    data.valueL = data.valueL/Math.abs(data.valueR);
    data.valueR = data.valueR/Math.abs(data.valueR);
  }

  if(Math.abs(data.valueL) === 0 && Math.abs(data.valueR) !== 0) {
    data.valueL = 0.1;
  }

  if(Math.abs(data.valueR) === 0 && Math.abs(data.valueL) !== 0) {
    data.valueR = 0.1;
  }
  return data;
}

//scans for gamepads in chrome based browsers
function scangamepads() {
  var gamepad = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  for (var i = 0; i < gamepad.length; i++) {
    if (gamepad[i]) {
      if (!(gamepad[i].index in gamepads)) {
        gamepadHandler(gamepad[i], true);
      } else {
        gamepads[gamepad[i].index] = gamepad[i];
      }
    }
  }
  clearInterval(scan);
}

if (JSON.stringify(gamepads) !== JSON.stringify({})) {
  console.log(gamepads)
  commandLoop();
}
//determine which event listener is best
if (haveEvents) {
  window.addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false);
  window.addEventListener("gamepaddisconnected", function(e) { gamepadHandler(e, false); }, false);
  console.log("haveEvents: "+ haveEvents)
} else if (haveWebkitEvents) {
  window.addEventListener("webkitgamepadconnected", function(e) { gamepadHandler(e, true); }, false);
  window.addEventListener("webkitgamepaddisconnected", function(e) { gamepadHandler(e, false); }, false);
  console.log("haveWebkitEvents: "+ haveWebkitEvents)
} else {
  scan = setInterval(scangamepads, 500);
  console.log("scanning for gamepad")
}
<commit_msg>Increased time between gamepad sampling<commit_after>var gamepads = {};
var haveEvents = 'GamepadEvent' in window;
var haveWebkitEvents = 'WebKitGamepadEvent' in window;
var socket = io();
var command;
var scan;
//handles connection and disconnection of gamepads
function gamepadHandler(event, connecting) {
  var gamepad = event.gamepad;
  // Note:
  // gamepad === navigator.getGamepads()[gamepad.index]

  if (connecting) {
    gamepads[gamepad.index] = gamepad;
    console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
      gamepad.index, gamepad.id,
      gamepad.buttons.length, gamepad.axes.length);
    console.log(gamepads[gamepad.index])
    socket.emit("gamepad", "connected")
    commandLoop();
  } else {
    delete gamepads[gamepad.index];
    console.log("Gamepad disconnected from index %d: %s",
      gamepad.index, gamepad.id);
    socket.emit("gamepad","disconnected")
  }
}

//function keeps getting values from first gamepad checking axis 0 and 1 for x y values respectively.
//maps values to left right motors and again maps that to axis 2, throttle.
function commandLoop () {
  scangamepads();
  var gamepadconnected = false;
  var j;
  for (j in gamepads) {
    var gamepad = gamepads[j];
    if (gamepadconnected) {
    }
    else if (gamepad) {
      if (gamepad.connected) {
        gamepadconnected = true;
        var axis = gamepad.axes;
        var data = {valueL: 0, valueR: 0}
        //when switched to mode Orange with button 24, tank drive active
        // axis 2 (throttle) is left and joystick is right.
        if(gamepad.buttons[25].pressed){
          data.valueL=0;
          data.valueR=0;
        }
        else if (gamepad.buttons[24].pressed) {
          var right = -axis[1];
          var left = -axis[2];
          data.valueL = left;
          data.valueR = right;
        } else {
          var drivePower = deadspace(-axis[1]);
          var turnPower = deadspace(axis[0]);
          var throttle = (-axis[2]+1)/2;
          console.log("throttle = " + throttle)
          console.log("turnPower = " + turnPower)
          console.log("drivePower = " + drivePower)
          data.valueL = (drivePower + turnPower)*throttle;
          data.valueR = (drivePower - turnPower)*throttle;
          data = limit(data)
        }
        //data should be values between -1 and 1
        socket.emit("serialOut", data);
        console.log(data)

        var pan = {x:0, y:0}
        pan.x = gamepad.buttons[20].value-gamepad.buttons[22].value
        pan.y = gamepad.buttons[19].value-gamepad.buttons[21].value
        socket.emit("pipan",pan)
        if(pan.x === 1) {
            //camera right
            servo_right()
        }
        else if(pan.x === -1) {
            //camera left
            servo_left()
        }
        if(pan.y === 1) {
            //camera up
            servo_up()
        }
        else if(pan.y === -1) {
            //camera down
            servo_down()
        }
      }
    }
  }
  if (gamepadconnected) {
    setTimeout(commandLoop,200)
  }
}

//removes deadspace by translating such space to be 0.
function deadspace(value) {
  if(Math.abs(value)<0.03) {
    value = 0;
  }
  return value;
}

//limits power to -1 and 1
function limit( data ) {
  if (Math.abs(data.valueL)>1) {
    data.valueR = data.valueR/Math.abs(data.valueL);
    data.valueL = data.valueL/Math.abs(data.valueL);
  }

  if (Math.abs(data.valueR)>1) {
    data.valueL = data.valueL/Math.abs(data.valueR);
    data.valueR = data.valueR/Math.abs(data.valueR);
  }

  if(Math.abs(data.valueL) === 0 && Math.abs(data.valueR) !== 0) {
    data.valueL = 0.1;
  }

  if(Math.abs(data.valueR) === 0 && Math.abs(data.valueL) !== 0) {
    data.valueR = 0.1;
  }
  return data;
}

//scans for gamepads in chrome based browsers
function scangamepads() {
  var gamepad = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  for (var i = 0; i < gamepad.length; i++) {
    if (gamepad[i]) {
      if (!(gamepad[i].index in gamepads)) {
        gamepadHandler(gamepad[i], true);
      } else {
        gamepads[gamepad[i].index] = gamepad[i];
      }
    }
  }
  clearInterval(scan);
}

if (JSON.stringify(gamepads) !== JSON.stringify({})) {
  console.log(gamepads)
  commandLoop();
}
//determine which event listener is best
if (haveEvents) {
  window.addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false);
  window.addEventListener("gamepaddisconnected", function(e) { gamepadHandler(e, false); }, false);
  console.log("haveEvents: "+ haveEvents)
} else if (haveWebkitEvents) {
  window.addEventListener("webkitgamepadconnected", function(e) { gamepadHandler(e, true); }, false);
  window.addEventListener("webkitgamepaddisconnected", function(e) { gamepadHandler(e, false); }, false);
  console.log("haveWebkitEvents: "+ haveWebkitEvents)
} else {
  scan = setInterval(scangamepads, 500);
  console.log("scanning for gamepad")
}
<|endoftext|>