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

var socket = new net.Socket();

var dataToSend = '{"playerId": 1, "actions": [{ "botId": 23, "type": "MOVE", "direction": "NORTH" }, { "botId": 23, "type": "MOVE", "direction": "NORTH" }]}';

socket.connect('9000', 'localhost', function() {
    socket.write(dataToSend.toString(), 'utf8', function() {
        console.log('<--- %j', dataToSend.toString());
    });
    socket.end();
});
<commit_msg>Improved test script<commit_after>var net = require('net');

var socket = new net.Socket();

var dataToSend = '{"playerId": 1, "actions": [{ "botId": 23, "type": "MOVE", "direction": "NORTH" }, { "botId": 23, "type": "MOVE", "direction": "NORTH" }]}';

socket.connect('9000', 'localhost', function() {
    socket.on('data', function(data) {
        console.log('\n---> ' + data);
        socket.end();
    });

    socket.write(dataToSend.toString(), 'utf8', function() {
        console.log('<--- ' + dataToSend.toString());
    });
});
<|endoftext|>


<commit_before>elation.component.add('engine.things.planet', function() {
  this.postinit = function() {
    this.defineProperties({
      'radius': { type: 'float', default: 1000 },
      'render.texture': { type: 'texture' },
      'render.normalmap': { type: 'texture' },
      'render.bumpmap': { type: 'texture' },
      'render.heightmap': { type: 'texture' },
    });
  }
  this.createObject3D = function() {
    var geo = new THREE.SphereGeometry(this.properties.radius, 32, 16);
    var matargs = {};
    if (this.properties.radius.texture) matargs.map = this.properties.radius.texture;
    if (this.properties.radius.normalmap) matargs.normalMap = this.properties.radius.normalmap;
    if (this.properties.radius.bumpmap) matargs.bumpMap = this.properties.radius.bumpMap;

    var mat = new THREE.MeshPhongMaterial(matargs);
    return new THREE.Mesh(geo, mat);
  }
}, elation.engine.things.generic);
<commit_msg>cosmetic planet placeholder tweaks<commit_after>elation.component.add('engine.things.planet', function() {
  this.postinit = function() {
    this.defineProperties({
      'radius': { type: 'float', default: 1 },
      'render.texture': { type: 'texture' },
      'render.normalmap': { type: 'texture' },
      'render.bumpmap': { type: 'texture' },
      'render.heightmap': { type: 'texture' },
    });
  }
  this.createObject3D = function() {
    var geo = new THREE.SphereGeometry(this.properties.radius, 32, 16);
    var matargs = {};
    if (this.properties.radius.texture) matargs.map = this.properties.radius.texture;
    if (this.properties.radius.normalmap) matargs.normalMap = this.properties.radius.normalmap;
    if (this.properties.radius.bumpmap) matargs.bumpMap = this.properties.radius.bumpMap;

    matargs.shininess = 1;
    matargs.specular = 0xffffff;

    var mat = new THREE.MeshPhongMaterial(matargs);
    return new THREE.Mesh(geo, mat);
  }
}, elation.engine.things.generic);
<|endoftext|>


<commit_before>const fs = require('fs-extra-promise')
const Builder = require('systemjs-builder');
const toFileURL = require('systemjs-builder/lib/utils').toFileURL;
const Configurator = require('systemjs-configurator');

let builder = new Builder('', {
  transpiler: 'plugin-babel',
  map: {
    'plugin-babel': 'node_modules/systemjs-plugin-babel/plugin-babel.js',
    'systemjs-babel-build': 'node_modules/systemjs-plugin-babel/systemjs-babel-node.js'
  },
  babelOptions: {
    plugins: [
      '@node/babel-plugin-transform-decorators-legacy'
    ]
  }
});

let bundleOptions = {
  minify: false,
  sourceMaps: true
};

function configure() {
  console.log("build SystemJS config ...");
  let config = Configurator.buildConfig({ outfile: 'systemjs.config.js' });
  builder.config(config);
};

function clean() {
  console.log("clean...");
  fs.emptyDir('dist');
}

function reset() {
  builder.reset();
};

function invalidate(filename) {
  builder.invalidate(toFileURL(filename));
  builder.invalidate(`${toFileURL(filename)}!*`);
};

function bundle() {
  console.log("bundle files ...");
  return Promise.all([
    builder.bundle('[src/**/*.js] + src/**/*.html!text + src/**/*.css!text', 'dist/app-bundle.js', bundleOptions),
    builder.bundle('text + src/**/*.js - [src/**/*.js]', 'dist/vendor-bundle.js', bundleOptions)
  ])
  .then(() => {
    console.log("bundle complete.")
  })
  .catch((error) => {
    console.error(error.stack);
  });
};

function build() {
  reset();
  configure();
  return bundle();
};

module.exports = {
  build: build,
  bundle: bundle,
  clean: clean,
  configure: configure,
  invalidate: invalidate,
  reset: reset
};
<commit_msg>run clean when building<commit_after>const fs = require('fs-extra-promise')
const Builder = require('systemjs-builder');
const toFileURL = require('systemjs-builder/lib/utils').toFileURL;
const Configurator = require('systemjs-configurator');

let builder = new Builder('', {
  transpiler: 'plugin-babel',
  map: {
    'plugin-babel': 'node_modules/systemjs-plugin-babel/plugin-babel.js',
    'systemjs-babel-build': 'node_modules/systemjs-plugin-babel/systemjs-babel-node.js'
  },
  babelOptions: {
    plugins: [
      '@node/babel-plugin-transform-decorators-legacy'
    ]
  }
});

let bundleOptions = {
  minify: false,
  sourceMaps: true
};

function configure() {
  console.log("build SystemJS config ...");
  let config = Configurator.buildConfig({ outfile: 'systemjs.config.js' });
  builder.config(config);
};

function clean() {
  console.log("clean...");
  fs.emptyDir('dist');
}

function reset() {
  builder.reset();
};

function invalidate(filename) {
  builder.invalidate(toFileURL(filename));
  builder.invalidate(`${toFileURL(filename)}!*`);
};

function bundle() {
  console.log("bundle files ...");
  return Promise.all([
    builder.bundle('[src/**/*.js] + src/**/*.html!text + src/**/*.css!text', 'dist/app-bundle.js', bundleOptions),
    builder.bundle('text + src/**/*.js - [src/**/*.js]', 'dist/vendor-bundle.js', bundleOptions)
  ])
  .then(() => {
    console.log("bundle complete.")
  })
  .catch((error) => {
    console.error(error.stack);
  });
};

function build() {
  clean();
  reset();
  configure();
  return bundle();
};

module.exports = {
  build: build,
  bundle: bundle,
  clean: clean,
  configure: configure,
  invalidate: invalidate,
  reset: reset
};
<|endoftext|>


<commit_before>// Case insensitive compare

'use strict';

var toLowerCase = String.prototype.toLowerCase;

module.exports = function (other) {
	return toLowerCase.call(this).localeCompare(toLowerCase.call(other));
};
<commit_msg>'other' may be nulll or undefined in string compare<commit_after>// Case insensitive compare

'use strict';

var toLowerCase = String.prototype.toLowerCase;

module.exports = function (other) {
	return toLowerCase.call(this).localeCompare(toLowerCase.call(String(other)));
};
<|endoftext|>


<commit_before>"use strict";

const utils = require("./utils");

const testDir = utils.prepareJetpackTestDir();
let timer;
let jetpackTime;
let nativeTime;

const test = testConfig => {
  const dirJet = testDir.dir("some-tree");

  console.log("");

  return utils
    .prepareFiles(dirJet, testConfig)
    .then(utils.waitAWhile)
    .then(() => {
      timer = utils.startTimer("jetpack.inspectTree()");
      const tree = dirJet.inspectTree(".", { checksum: "md5" });
      timer();
      console.log("md5", tree.md5);
    })
    .then(utils.waitAWhile)
    .then(() => {
      timer = utils.startTimer("jetpack.inspectTreeAsync()");
      return dirJet.inspectTreeAsync(".", { checksum: "md5" });
    })
    .then(tree => {
      timer();
      console.log("md5", tree.md5);
      return utils.cleanAfterTest();
    })
    .catch(err => {
      console.log(err);
    });
};

const testConfigs = [
  {
    files: 10000,
    size: 1000
  },
  {
    files: 10000,
    size: 100000
  }
];

const runNext = () => {
  if (testConfigs.length > 0) {
    test(testConfigs.pop()).then(runNext);
  }
};

runNext();
<commit_msg>Update inspect_tree.js<commit_after>"use strict";

const utils = require("./utils");

const testDir = utils.prepareJetpackTestDir();
let timer;
let jetpackTime;
let nativeTime;

const test = testConfig => {
  const dirJet = testDir.dir("some-tree");

  console.log("");

  return utils
    .prepareFiles(dirJet, testConfig)
    .then(utils.waitAWhile)
    .then(() => {
      timer = utils.startTimer("jetpack.inspectTree()");
      const tree = dirJet.inspectTree(".", { checksum: "md5" });
      timer();
      console.log("md5", tree.md5);
    })
    .then(utils.waitAWhile)
    .then(() => {
      timer = utils.startTimer("jetpack.inspectTreeAsync()");
      return dirJet.inspectTreeAsync(".", { checksum: "md5" });
    })
    .then(tree => {
      timer();
      console.log("md5", tree.md5);
      return utils.cleanAfterTest();
    })
    .catch(err => {
      console.log(err);
    });
};

const testConfigs = [
  {
    files: 10000,
    size: 1000
  },
  {
    files: 1000,
    size: 10000000
  }
];

const runNext = () => {
  if (testConfigs.length > 0) {
    test(testConfigs.pop()).then(runNext);
  }
};

runNext();
<|endoftext|>


<commit_before>//= require ./singleton
//= require ./array

"use strict";
var Singleton;

// Object: javascript literal object
(function ($) {

    if (!Object.deleteSingleton) {
        $.defineProperty($.prototype, "deleteSingleton", {
            value: function () {
                var
                    self = this;

                Singleton.destroy.apply(self, arguments.flatten());

                return Singleton.instances();
            }
        });
    }

    if (!Object.isEquivalent) {
        $.defineProperty($.prototype, "isEquivalent", {
            value: function () {
                var
                    self = this,
                    primitiveTypes =
                        /(number|string|boolean|null|undefined|symbol)/,
                    i;

                if ((arguments[0]).constructor === self.constructor) {
                    if (self instanceof Object && !(self instanceof Function)) {
                        for (i in self) {
                            if (self.hasOwnProperty(i)) {
                                // se o tipo for function a comparação será desprezada
                                if (typeof self[i] !== "function") {
                                    if ((self[i]).constructor ===
                                        (arguments[0][i]).constructor) {
                                        if (self[i].constructor === Object) {
                                            if (self[i]
                                                .isEquivalent(arguments[0][i])=== false) {
                                                return false;
                                            }
                                        } else {
                                            if (self[i] !== arguments[0][i]) {
                                                return false;
                                            }
                                        }
                                    } else {
                                        return false;
                                    }
                                }
                            }
                        }
                    } else {
                        if (primitiveTypes.test(typeof self)) {
                            if (self !== arguments[0]) {
                                return false;
                            }
                        }
                    }
                } else {
                    return false;
                }

                return true;
            }
        });
    }

    if (!Object.flatten) {
        $.defineProperty($.prototype, "flatten", {
            value: function () {
                var
                    flat = [],
                    self = this,
                    i,
                    type;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        type = Object.prototype.toString.call(self[i])
                            .split(" ").pop().split("]").shift().toLowerCase();
                        if (type) {
                            flat = flat
                                .concat(/^(array|arguments|collection)$/
                                    .test(type) ? self.flatten
                                        .call(self[i]) : self[i]);
                        }
                    }
                }

                return flat;
            }
        });
    }

    if (!Object.eachNodes) {
        $.defineProperty($.prototype, "eachNodes", {
            value: function (callback, trail) {
                trail = trail || [];

                var
                    self = this,
                    value;

                //for (var key in self) {
                Object.getOwnPropertyNames(self).forEach(function (key) {
                // Object.keys(self).forEach(function (key) {
                    value = self[key];

                    if (Object.getPrototypeOf(value) === Object.prototype) {
                        // chamar uma função recursivamente não substitui os valores do atual loop, nem o interrompe (salvo quando a instrução return é chamada), apenas define um novo loop com um novo valor para ser executado
                        // eachNodes(callback, trail.concat(key));
                        value.eachNodes(callback, trail.concat(key));
                    } else {
                        callback({name: key, value: value, trail: trail});
                    }
                });
                // }
            }
        });
    }

    if (!Object.merge) {
        $.defineProperty($.prototype, "merge", {
            value: function () {
                var
                    self = this,
                    merged = {},
                    i,
                    arg;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        merged[i] = self[i];
                    }
                }

                for (arg in arguments) {
                    if (arguments.hasOwnProperty(arg)) {
                        if (arguments[arg] instanceof Object) {
                            for (i in arguments[arg]) {
                                if (arguments[arg].hasOwnProperty(i)) {
                                    merged[i] = arguments[arg][i];
                                }
                            }
                        }
                    }
                }

                return merged;
            }
        });
    }

    if (!Object.indexOfConstructor) {
        $.defineProperty($.prototype, "indexOfConstructor", {
            value: function () {
                var
                    self = this,
                    calleeArgs = self.callee.arguments,
                    arg = arguments[0],
                    i;

                for(i in calleeArgs) {
                    if (calleeArgs[i].constructor === arg) {
                        return parseFloat(i);
                    }
                }

                return false;
            }
        });
    }

    if (!Object.eachAttrs) {
        $.defineProperty($.prototype, "eachAttrs", {
            value: function () {
                var
                    self = this,
                    attrs = Object.getOwnPropertyNames(self),
                    attr,
                    callback = arguments[0];

                // o for...in é para se usar break;
                for (attr in attrs) {
                    if (!isNaN(parseInt(attrs[attr], 10))) {
                        callback(self[attr], attr);
                    } else {
                        break;
                    }
                }
            }
        });
    }

}(Object));
<commit_msg>ajusta ifs de object<commit_after>//= require ./singleton
//= require ./array

"use strict";
var Singleton;

// Object: javascript literal object
(function ($) {

    // if (!Object.deleteSingleton) {

    if (!Object.prototype.deleteSingleton) {
        $.defineProperty($.prototype, "deleteSingleton", {
            value: function () {
                var
                    self = this;

                Singleton.destroy.apply(self, arguments.flatten());

                return Singleton.instances();
            }
        });
    }

    if (!Object.prototype.isEquivalent) {
        $.defineProperty($.prototype, "isEquivalent", {
            value: function () {
                var
                    self = this,
                    primitiveTypes =
                        /(number|string|boolean|null|undefined|symbol)/,
                    i;

                if ((arguments[0]).constructor === self.constructor) {
                    if (self instanceof Object && !(self instanceof Function)) {
                        for (i in self) {
                            if (self.hasOwnProperty(i)) {
                                // se o tipo for function a comparação será desprezada
                                if (typeof self[i] !== "function") {
                                    if ((self[i]).constructor ===
                                        (arguments[0][i]).constructor) {
                                        if (self[i].constructor === Object) {
                                            if (self[i]
                                                .isEquivalent(arguments[0][i])=== false) {
                                                return false;
                                            }
                                        } else {
                                            if (self[i] !== arguments[0][i]) {
                                                return false;
                                            }
                                        }
                                    } else {
                                        return false;
                                    }
                                }
                            }
                        }
                    } else {
                        if (primitiveTypes.test(typeof self)) {
                            if (self !== arguments[0]) {
                                return false;
                            }
                        }
                    }
                } else {
                    return false;
                }

                return true;
            }
        });
    }

    if (!Object.prototype.flatten) {
        $.defineProperty($.prototype, "flatten", {
            value: function () {
                var
                    flat = [],
                    self = this,
                    i,
                    type;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        type = Object.prototype.toString.call(self[i])
                            .split(" ").pop().split("]").shift().toLowerCase();
                        if (type) {
                            flat = flat
                                .concat(/^(array|arguments|collection)$/
                                    .test(type) ? self.flatten
                                        .call(self[i]) : self[i]);
                        }
                    }
                }

                return flat;
            }
        });
    }

    if (!Object.prototype.eachNodes) {
        $.defineProperty($.prototype, "eachNodes", {
            value: function (callback, trail) {
                trail = trail || [];

                var
                    self = this,
                    value;

                //for (var key in self) {
                Object.getOwnPropertyNames(self).forEach(function (key) {
                // Object.keys(self).forEach(function (key) {
                    value = self[key];

                    if (Object.getPrototypeOf(value) === Object.prototype) {
                        // chamar uma função recursivamente não substitui os valores do atual loop, nem o interrompe (salvo quando a instrução return é chamada), apenas define um novo loop com um novo valor para ser executado
                        // eachNodes(callback, trail.concat(key));
                        value.eachNodes(callback, trail.concat(key));
                    } else {
                        callback({name: key, value: value, trail: trail});
                    }
                });
                // }
            }
        });
    }

    if (!Object.prototype.merge) {
        $.defineProperty($.prototype, "merge", {
            value: function () {
                var
                    self = this,
                    merged = {},
                    i,
                    arg;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        merged[i] = self[i];
                    }
                }

                for (arg in arguments) {
                    if (arguments.hasOwnProperty(arg)) {
                        if (arguments[arg] instanceof Object) {
                            for (i in arguments[arg]) {
                                if (arguments[arg].hasOwnProperty(i)) {
                                    merged[i] = arguments[arg][i];
                                }
                            }
                        }
                    }
                }

                return merged;
            }
        });
    }

    if (!Object.prototype.eachAttrs) {
        $.defineProperty($.prototype, "eachAttrs", {
            value: function () {
                var
                    self = this,
                    attrs = Object.getOwnPropertyNames(self),
                    attr,
                    callback = arguments[0];

                // o for...in é para se usar break;
                for (attr in attrs) {
                    if (!isNaN(parseInt(attrs[attr], 10))) {
                        callback(self[attr], attr);
                    } else {
                        break;
                    }
                }
            }
        });
    }

    // if (!Object.prototype.indexOfConstructor) {
    //     $.defineProperty($.prototype, "indexOfConstructor", {
    //         value: function () {
    //             var
    //                 self = this,
    //                 calleeArgs = self.callee.arguments,
    //                 arg = arguments[0],
    //                 i;

    //             for(i in calleeArgs) {
    //                 if (calleeArgs[i].constructor === arg) {
    //                     return parseFloat(i);
    //                 }
    //             }

    //             return false;
    //         }
    //     });
    // }

}(Object));
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var fs      = require('fs');
var plist   = require('plist');
var libxml  = require('libxmljs');

function ucfirst(s) {
    return s.charAt(0).toUpperCase() + s.substring(1);
}

function ConfigMap(config) {
// iOS
// https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/UserDefaults/Preferences/Preferences.html
/*

mkdir Settings.bundle
cd Settings.bundle
touch Root.plist
mkdir en.lproj
cd en.lproj
touch Root.strings

Identifier

PSGroupSpecifier
Type
Title
FooterText

PSToggleSwitchSpecifier
Title
Key
DefaultValue

PSSliderSpecifier
Key
DefaultValue
MinimumValue
MaximumValue

PSTitleValueSpecifier
Title
Key
DefaultValue

PSTextFieldSpecifier
Title
Key
DefaultValue
IsSecure
KeyboardType (Alphabet , NumbersAndPunctuation , NumberPad , URL , EmailAddress)
AutocapitalizationType
AutocorrectionType

PSMultiValueSpecifier
Title
Key
DefaultValue
Values
Titles

PSRadioGroupSpecifier
Title
FooterText???
Key
DefaultValue
Values
Titles

*/

    if (config.type) {

        if (config.type == 'group') {
            config.type = 'PSGroupSpecifier';
        }
        else {
            config.DefaultValue = config['default'];
            delete config['default'];

            config.Key = config.name;
            delete config['name'];

            switch (config.type) {

                case 'textfield':
                    config.type = 'PSTextFieldSpecifier';
                    break;

                case 'switch':
                    config.type = 'PSToggleSwitchSpecifier';
                    break;

                case 'combo':
                    config.type = 'PSMultiValueSpecifier';

                    config.titles = [];
                    config.values = [];
                    config.items.forEach(function(a) {
                        config.values.push(a.id || a.value);
                        config.titles.push(a.title || a.name);
                    });
                    delete config.items;
                    break;
            }
        }
    }

	Object.keys(config).forEach(function(k) {
		var uc = ucfirst(k);
		config[uc] = config[k];
		if (uc != k)
			delete config[k];
	})

	return config;
}

fs.readFile('app-settings.json', function(err, data) {
	if (err) {
		throw err;
    }

	var iosData = JSON.parse(data);
	var aData = iosData;

	// build iOS settings bundle

	var items = [];
	while (iosData.length) {
		var src = iosData.shift();
		if (src.type == 'group') {
			src.items.reverse().forEach(function(s) {
				iosData.unshift(s);
			});
			delete src['items'];
		}
		items.push(ConfigMap(src));
	}

	var plistXml = plist.build({ PreferenceSpecifiers: items });
	fs.exists('platforms/ios', function(exists) {
		if (!exists) {
			console.error('platform ios not found');
            return;
        }

		fs.mkdir('platforms/ios/Settings.bundle', function(e) {
			if (e && e.code != 'EEXIST') {
				throw e;
            }

			// Write settings plist
			fs.writeFile('platforms/ios/Settings.bundle/Root.plist', plistXml, function(err) {
				if (err) {
					throw err;
                }
				console.log('ios settings bundle was successfully generated');
			});

			// Write localization resource file
			fs.mkdir('platforms/ios/Settings.bundle/en.lproj', function(e) {
				if (e && e.code != 'EEXIST') {
					throw e;
                }
				fs.writeFile('platforms/ios/Settings.bundle/en.lproj/Root.strings', '/* */', function(err) {
					if (err) {
						throw err;
                    }
				});
			});
		});
	});

	// build Android settings XML

	var doc = new libxml.Document();
	var strings = [];
	var n = doc
		.node('PreferenceScreen')
		.attr({'xmlns:android': 'http://schemas.android.com/apk/res/android'});

	var addSettings = function(parent, config) {
		if (config.type == 'group') {
			var g = parent
				.node('PreferenceCategory')
				.attr({'android:title': config.name || config.title});

			config.items.forEach(function(item) {
				addSettings(g, item);
			});

		} else {

			var attr = {
				'android:title': config.title,
				'android:key': config.name,
				'android:defaultValue': config['default']
			}

			switch (config.type) {
				case 'combo':
					// Generate resource file
					var d = new libxml.Document();
					var res = d.node('resources');
					var titles = res.node('string-array').attr({name: config.name}),
					    values = res.node('string-array').attr({name: config.name + 'Values'});

					config.items.forEach(function(item) {
						titles.node('item', item.name || item.title);
						values.node('item', item.id || item.value);
					});

					strings.push({
						name: config.name,
						xml: d.toString()
					});

					attr['android:entries'] = '@array/' + config.name;
					attr['android:entryValues'] = '@array/' + config.name + 'Values';

					parent
						.node('ListPreference')
						.attr(attr)
				break;
			}
		}
	}
	aData.forEach(function(item) {
		addSettings(n, item);
	});

	fs.exists('platforms/android', function(exists) {
		if (!exists) {
			console.error('platform android not found');
            return;
        }

		fs.mkdir('platforms/android/res/xml', function(e) {
			if (e && e.code != 'EEXIST') {
				throw e;
            }

			// Write settings plist
			fs.writeFile('platforms/android/res/xml/preference.xml', doc.toString(), function(err) {
				if (err) {
					throw err;
                }
				console.log('android preferences file was successfully generated');
			});

			// Write localization resource file
			fs.mkdir('platforms/android/res/values', function(e) {
				if (e && e.code != 'EEXIST') {
					throw e;
                }
				strings.forEach(function(file) {
					fs.writeFile('platforms/android/res/values/' + file.name + '.xml', file.xml, function(err) {
						if (err) {
							throw err;
                        }
					});
				});
			});
		});
	});

});
<commit_msg>fixed android preferences generation #22<commit_after>#!/usr/bin/env node

'use strict';

var fs      = require('fs');
var plist   = require('plist');
var libxml  = require('libxmljs');

function ucfirst(s) {
    return s.charAt(0).toUpperCase() + s.substring(1);
}

function ConfigMap(config) {
// iOS
// https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/UserDefaults/Preferences/Preferences.html
/*

mkdir Settings.bundle
cd Settings.bundle
touch Root.plist
mkdir en.lproj
cd en.lproj
touch Root.strings

Identifier

PSGroupSpecifier
Type
Title
FooterText

PSToggleSwitchSpecifier
Title
Key
DefaultValue

PSSliderSpecifier
Key
DefaultValue
MinimumValue
MaximumValue

PSTitleValueSpecifier
Title
Key
DefaultValue

PSTextFieldSpecifier
Title
Key
DefaultValue
IsSecure
KeyboardType (Alphabet , NumbersAndPunctuation , NumberPad , URL , EmailAddress)
AutocapitalizationType
AutocorrectionType

PSMultiValueSpecifier
Title
Key
DefaultValue
Values
Titles

PSRadioGroupSpecifier
Title
FooterText???
Key
DefaultValue
Values
Titles

*/

    if (config.type) {

        if (config.type == 'group') {
            config.type = 'PSGroupSpecifier';
        }
        else {
            config.DefaultValue = config['default'];
            delete config['default'];

            config.Key = config.name;
            delete config['name'];

            switch (config.type) {

                case 'textfield':
                    config.type = 'PSTextFieldSpecifier';
                    break;

                case 'switch':
                    config.type = 'PSToggleSwitchSpecifier';
                    break;

                case 'combo':
                    config.type = 'PSMultiValueSpecifier';

                    config.titles = [];
                    config.values = [];
                    config.items.forEach(function(a) {
                        config.values.push(a.id || a.value);
                        config.titles.push(a.title || a.name);
                    });
                    delete config.items;
                    break;
            }
        }
    }

	Object.keys(config).forEach(function(k) {
		var uc = ucfirst(k);
		config[uc] = config[k];
		if (uc != k)
			delete config[k];
	})

	return config;
}

fs.readFile('app-settings.json', function(err, data) {
	if (err) {
		throw err;
    }

	var iosData = JSON.parse (data);
	var aData   = JSON.parse (data);

	// build iOS settings bundle

	var items = [];
	while (iosData.length) {
		var src = iosData.shift();
		if (src.type == 'group') {
			src.items.reverse().forEach(function(s) {
				iosData.unshift(s);
			});
			delete src['items'];
		}
		items.push(ConfigMap(src));
	}

	var plistXml = plist.build({ PreferenceSpecifiers: items });
	fs.exists('platforms/ios', function(exists) {
		if (!exists) {
			console.error('platform ios not found');
            return;
        }

		fs.mkdir('platforms/ios/Settings.bundle', function(e) {
			if (e && e.code != 'EEXIST') {
				throw e;
            }

			// Write settings plist
			fs.writeFile('platforms/ios/Settings.bundle/Root.plist', plistXml, function(err) {
				if (err) {
					throw err;
                }
				console.log('ios settings bundle was successfully generated');
			});

			// Write localization resource file
			fs.mkdir('platforms/ios/Settings.bundle/en.lproj', function(e) {
				if (e && e.code != 'EEXIST') {
					throw e;
                }
				fs.writeFile('platforms/ios/Settings.bundle/en.lproj/Root.strings', '/* */', function(err) {
					if (err) {
						throw err;
                    }
				});
			});
		});
	});

	// build Android settings XML

	var doc = new libxml.Document();
	var strings = [];
	var n = doc
		.node('PreferenceScreen')
		.attr({'xmlns:android': 'http://schemas.android.com/apk/res/android'});

	var addSettings = function(parent, config) {
		if (config.type == 'group') {
			var g = parent
				.node('PreferenceCategory')
				.attr({'android:title': config.name || config.title});

			config.items.forEach(function(item) {
				addSettings(g, item);
			});

		} else {

			var attr = {
				'android:title': config.title,
				'android:key': config.name,
				'android:defaultValue': config['default']
			}

			switch (config.type) {
				case 'combo':
					// Generate resource file
					var d = new libxml.Document();
					var res = d.node('resources');
					var titles = res.node('string-array').attr({name: config.name}),
					    values = res.node('string-array').attr({name: config.name + 'Values'});

					config.items.forEach(function(item) {
						titles.node('item', item.name || item.title);
						values.node('item', item.id || item.value);
					});

					strings.push({
						name: config.name,
						xml: d.toString()
					});

					attr['android:entries'] = '@array/' + config.name;
					attr['android:entryValues'] = '@array/' + config.name + 'Values';

					parent
						.node('ListPreference')
						.attr(attr)
				break;
			}
		}
	}
	aData.forEach(function(item) {
		addSettings(n, item);
	});

	fs.exists('platforms/android', function(exists) {
		if (!exists) {
			console.error('platform android not found');
            return;
        }

		fs.mkdir('platforms/android/res/xml', function(e) {
			if (e && e.code != 'EEXIST') {
				throw e;
            }

			// Write settings plist
			fs.writeFile('platforms/android/res/xml/preference.xml', doc.toString(), function(err) {
				if (err) {
					throw err;
                }
				console.log('android preferences file was successfully generated');
			});

			// Write localization resource file
			fs.mkdir('platforms/android/res/values', function(e) {
				if (e && e.code != 'EEXIST') {
					throw e;
                }
				strings.forEach(function(file) {
					fs.writeFile('platforms/android/res/values/' + file.name + '.xml', file.xml, function(err) {
						if (err) {
							throw err;
                        }
					});
				});
			});
		});
	});

});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');

const promisify = require('lagden-promisify');
const yargs = require('yargs');

const mustachePrestatic = require('../src/index.js');
const writeFile = promisify(fs.writeFile);

const argv = yargs
  .usage(`\nUsage: $0 templateFiles [options]
Compile pages of static HTML from mustache templates, data and partials.`)
  .demand(1, 'Missing required templateFiles argument.')
  .showHelpOnFail(false)

  .option('help', {
    alias: 'h',
    type: 'boolean'
  }).help('help', 'Show help text.')

  .option('version', {
    alias: 'v',
    type: 'boolean'
  }).version()

  .option('data', {
    alias: 'd',
    describe: 'Input mustache template data files.',
    type: 'array'
  })

  .option('partials', {
    alias: 'p',
    describe: 'Input mustache partial files.',
    type: 'array'
  })

  .option('output', {
    alias: 'o',
    default: '.',
    describe: 'Output directory, defaults to current directory.',
    type: 'string'
  })

  .option('verbose', {
    describe: 'Log extra information about the process to stdout.',
    type: 'boolean'
  })
  .argv;

const transform = function (templateFiles) {
  const log = require('./verbose-log')(argv.verbose);

  log('templateFiles', templateFiles);
  log('data', argv.data);
  log('partials', argv.partials, '\n');

  mustachePrestatic(templateFiles, argv.data, argv.partials)
    .then(function (htmlResults) {
      return templateFiles.forEach(function (filePath, index) {
        let outputFileName = path.parse(filePath).name;
        let outputPath = path.join(argv.output, outputFileName) + '.html';

        writeFile(outputPath, htmlResults[index], 'utf8')
          .catch(console.error);
      });
    });
};

transform(argv._);

process.title = 'mustache-prestatic';
<commit_msg>Remove old Yargs version and help argument parsing<commit_after>#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');

const promisify = require('lagden-promisify');
const yargs = require('yargs');

const mustachePrestatic = require('../src/index.js');
const writeFile = promisify(fs.writeFile);

const argv = yargs
  .usage(`\nUsage: $0 templateFiles [options]
Compile pages of static HTML from mustache templates, data and partials.`)
  .demand(1, 'Missing required templateFiles argument.')
  .showHelpOnFail(false)

  .option('help', {
    alias: 'h',
    type: 'boolean'
  })

  .option('version', {
    alias: 'v',
    type: 'boolean'
  })

  .option('data', {
    alias: 'd',
    describe: 'Input mustache template data files.',
    type: 'array'
  })

  .option('partials', {
    alias: 'p',
    describe: 'Input mustache partial files.',
    type: 'array'
  })

  .option('output', {
    alias: 'o',
    default: '.',
    describe: 'Output directory, defaults to current directory.',
    type: 'string'
  })

  .option('verbose', {
    describe: 'Log extra information about the process to stdout.',
    type: 'boolean'
  })
  .argv;

const transform = function (templateFiles) {
  const log = require('./verbose-log')(argv.verbose);

  log('templateFiles', templateFiles);
  log('data', argv.data);
  log('partials', argv.partials, '\n');

  mustachePrestatic(templateFiles, argv.data, argv.partials)
    .then(function (htmlResults) {
      return templateFiles.forEach(function (filePath, index) {
        let outputFileName = path.parse(filePath).name;
        let outputPath = path.join(argv.output, outputFileName) + '.html';

        writeFile(outputPath, htmlResults[index], 'utf8')
          .catch(console.error);
      });
    });
};

transform(argv._);

process.title = 'mustache-prestatic';
<|endoftext|>


<commit_before>const Task             = require('../../../tasks/-task');
const Promise          = require('rsvp').Promise;
const chalk            = require('chalk');
const logger           = require('../../../utils/logger');

const MUST_SPECIFY_HASH =
  chalk.red('* config/environment.js: Cordova applications require:') +
  chalk.grey('\n`ENV.locationType = \'hash\'; \n');

module.exports = Task.extend({
  config: undefined,
  force: false,

  run() {
    let config = this.config;
    let locationType    = config.locationType;
    let isValidLocation  = locationType === 'hash' || locationType === 'none';

    if (!isValidLocation) {
      if (this.force === false) {
        return Promise.reject(MUST_SPECIFY_HASH);
      } else {
        var msg = MUST_SPECIFY_HASH;
        msg += 'You have passed the --force flag, so continuing';
        logger.warn(msg);
      }
    }

    return Promise.resolve();
  }
});
<commit_msg>feat(location-type-validator): only force when explicitly force=true<commit_after>const Task             = require('../../../tasks/-task');
const Promise          = require('rsvp').Promise;
const chalk            = require('chalk');
const logger           = require('../../../utils/logger');

const MUST_SPECIFY_HASH =
  chalk.red('* config/environment.js: Cordova applications require:') +
  chalk.grey('\n`ENV.locationType = \'hash\'; \n');

module.exports = Task.extend({
  config: undefined,
  force: false,

  run() {
    let config = this.config;
    let locationType    = config.locationType;
    let isValidLocation  = locationType === 'hash' || locationType === 'none';

    if (!isValidLocation) {
      if (this.force === true) {
        var msg = MUST_SPECIFY_HASH;
        msg += 'You have passed the --force flag, so continuing';
        logger.warn(msg);
      } else {
        return Promise.reject(MUST_SPECIFY_HASH);
      }
    }

    return Promise.resolve();
  }
});
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace utils
*/
var utils = {};

/**
* @name incrspace
* @memberof utils
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/utils/incrspace}
*/
setReadOnly( utils, 'incrspace', require( '@stdlib/math/utils/incrspace' ) );

/**
* @name linspace
* @memberof utils
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/utils/linspace}
*/
setReadOnly( utils, 'linspace', require( '@stdlib/math/utils/linspace' ) );

/**
* @name logspace
* @memberof utils
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/utils/logspace}
*/
setReadOnly( utils, 'logspace', require( '@stdlib/math/utils/logspace' ) );

// EXPORTS //

module.exports = utils;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace utils
*/
var utils = {};

/**
* @name incrspace
* @memberof utils
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/utils/incrspace}
*/
setReadOnly( utils, 'incrspace', require( '@stdlib/math/utils/incrspace' ) );

/**
* @name linspace
* @memberof utils
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/utils/linspace}
*/
setReadOnly( utils, 'linspace', require( '@stdlib/math/utils/linspace' ) );

/**
* @name logspace
* @memberof utils
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/utils/logspace}
*/
setReadOnly( utils, 'logspace', require( '@stdlib/math/utils/logspace' ) );

/**
* @name typemax
* @memberof utils
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/utils/typemax}
*/
setReadOnly( utils, 'typemax', require( '@stdlib/math/utils/typemax' ) );

// EXPORTS //

module.exports = utils;
<|endoftext|>


<commit_before>#!/usr/bin/env node
var client = require('redis').createClient();
client.select(1, function(err) {
  if (err) throw err;
  require('readline').createInterface({
    input: process.stdin,
    terminal: false
  }).on('line', function (line) { // one JSON object per line
    var obj = JSON.parse(line);
    client.hgetall(obj._id, function (err, homologs) {
      if (err) throw err;
      if (!obj.hasOwnProperty('homology')) {
        obj.homology = {};
      }
      for (var gene in homologs) {
        var k = homologs[gene];
        if (!obj.homology.hasOwnProperty(k)) {
          obj.homology[k] = [];
        }
        obj.homology[k].push(gene);
      }
      console.log(JSON.stringify(obj));
    });
  }).on('close', function() {
    client.quit();
  });
});
<commit_msg>pause and resume the readline to prevent clogging up the pipes<commit_after>#!/usr/bin/env node
var client = require('redis').createClient();

client.select(1, function(err) {
  if (err) throw err;
  var rl = require('readline').createInterface({
    input: process.stdin,
    terminal: false
  });

  rl.on('line', function (line) { // one JSON object per line
    rl.pause();
    var obj = JSON.parse(line);
    client.hgetall(obj._id, function (err, homologs) {
      if (err) throw err;
      if (!obj.hasOwnProperty('homology')) {
        obj.homology = {};
      }
      for (var gene in homologs) {
        var k = homologs[gene];
        if (!obj.homology.hasOwnProperty(k)) {
          obj.homology[k] = [];
        }
        obj.homology[k].push(gene);
      }
      console.log(JSON.stringify(obj));
      rl.resume();
    });
  }).on('close', function() {
    client.quit();
  });
});
<|endoftext|>


<commit_before>var quickSwitcher = function(filters, SelectedResult, sorters) {
  var $ = jQuery;

  var ResultHandler = {
    filters: filters,
    sorters: sorters,
  };

  var callbackOrValue = function(value) {
    return (typeof value === 'function') ? value() : value;
  };

  var QuickSwitcher = {
    init: function($parentDom, options) {
      this.$parentDom = null;
      this.$liCollection = null;
      this.valueObjects = null;
      this.selectedIndex = null;
      this.$results = null;
      this.$noSearchTerms = null;
      this.$noResults = null;
      this.$loading = null;
      this.$breadcrumb = null;
      this.$search = null;
      this.searchText = '';
      this.searchDelayTimeout = null;
      this.searchId = 0;

      this.modifierKey = 'ctrlKey';
      if (navigator.platform.toLowerCase().indexOf('mac') != -1) {
        this.modifierKey = 'metaKey';
      }

      options = $.extend({
        searchCallback: function() {},
        selectCallback: function() {},
        selectChildSearchCallback: function() {},
        searchDelay: 1000,
        hotKey: 'K',
      }, options);

      this.hotKey = options.hotKey.toUpperCase();

      this.setOptions({
        searchCallback: options.searchCallback,
        selectCallback: options.selectCallback,
        selectChildSearchCallback: options.selectChildSearchCallback,
        searchDelay: options.searchDelay,
      });

      this.initDomElement($parentDom);

      this.callbackStack = [];
      this.abortSearchCallback = null;
    },

    initDomElement: function($parentDom) {
      var qSwitcher = this;

      this.$parentDom = $parentDom;
      this.$domElement = $(
        '
' +
        '
' +
        '
' +
        '  <form class="lstr-qswitcher-popup">' +
        '
' +
        '
' +
        '
' +
        '
' +
        '
↕ to navigate
' +
        '
↵ to select
' +
        '
⌫ to clear
' +
        '
esc to dismiss
' +
        '
' +
        '
' +
        '    ×' +
        '
<input type="text" class="lstr-qswitcher-search form-control" />
' +
        '
Loading...
' +
        '

' +
        '
No results found
' +
        '
' +
        '      Oops! Something went wrong while trying to load your results.' +
        '
' +
        '

' +
        '  </form>' +
        '
'
      );

      $parentDom.append(this.$domElement);

      this.$breadcrumb = this.$domElement.find('.lstr-qswitcher-breadcrumb');
      this.$close = this.$domElement.find('.lstr-qswitcher-close');
      this.$search = this.$domElement.find('.lstr-qswitcher-search');
      this.$loading = this.$domElement.find('.lstr-qswitcher-loading');
      this.$results = this.$domElement.find('.lstr-qswitcher-results');
      this.$noSearchTerms = this.$domElement.find('.lstr-qswitcher-no-terms');
      this.$noResults = this.$domElement.find('.lstr-qswitcher-no-results');
      this.$oopsResults = this.$domElement.find('.lstr-qswitcher-oops-results');

      var $domElement = this.$domElement;

      $domElement.find('.lstr-qswitcher-popup').on('submit', function(event) {
        event.preventDefault();
      });
      $parentDom.find('.lstr-qswitcher-overlay').on('click', function(event) {
        qSwitcher.closeSwitcher();
        event.preventDefault();
      });
      $parentDom.on('keydown', function(event) {
        var keyPressed = String.fromCharCode(event.which);
        if (event[qSwitcher.modifierKey] && keyPressed === qSwitcher.hotKey) {
          qSwitcher.toggleSwitcher();
          event.preventDefault();
        }
      });
      $('html').on('keydown', '.lstr-qswitcher-noscroll', function(event) {
        if (event.which === 38) { // up arrow key
          qSwitcher.selectIndex(qSwitcher.selectedIndex - 1);
          qSwitcher.scrollToSelectedItem();
          event.preventDefault();
        } else if (event.which === 40) { // down arrow key
          qSwitcher.selectIndex(qSwitcher.selectedIndex + 1);
          qSwitcher.scrollToSelectedItem();
          event.preventDefault();
        } else if (event.which === 27) { // escape key
          qSwitcher.toggleSwitcher();
          event.preventDefault();
        } else if (13 === event.keyCode) {
          qSwitcher.triggerSelect(qSwitcher.selectedIndex, event);
          event.preventDefault();
        }
      });
      this.$close.on('click', function(event) {
        qSwitcher.closeSwitcher();
      });
      this.$search.on('keyup', function(event) {
        var searchText = qSwitcher.$search.val();

        if (qSwitcher.searchDelayTimeout) {
          clearTimeout(qSwitcher.searchDelayTimeout);
          qSwitcher.searchDelayTimeout = null;
        }

        if (searchText !== qSwitcher.searchText) {
          qSwitcher.searchDelayTimeout = setTimeout(function() {
            qSwitcher.selectIndex(null);
            qSwitcher.searchText = searchText;
            qSwitcher.renderList();
          }, qSwitcher.searchDelay);
        } else if (event.which === 8 && '' === searchText) {
          // backspace with text box blank
          qSwitcher.popCallback();
          qSwitcher.renderList();
        }
      });
      $domElement.on('mouseover', '.lstr-qswitcher-results li', function() {
        var $li = $(this);
        qSwitcher.selectIndex($li.data('lstr-qswitcher').index);
      });
      $domElement.on('click', '.lstr-qswitcher-results li', function(event) {
        var $li = $(this);
        qSwitcher.triggerSelect($li.data('lstr-qswitcher').index, event);
      });
    },

    renderList: function() {
      if (this.abortSearchCallback) {
        this.abortSearchCallback();
        this.abortSearchCallback = null;
      }

      this.renderBreadcrumb();

      this.usePane(this.$loading);

      var resultHandler = Object.create(ResultHandler);
      ++this.searchId;
      resultHandler.setResults = this.setResults.bind(this, this.searchId);
      resultHandler.setError = this.setError.bind(this, this.searchId);
      this.abortSearchCallback = this.searchCallback(
        this.searchText,
        resultHandler
      );
    },

    setResults: function(searchId, items) {
      // if the search ID provided to setResults is not the current searchId,
      // ignore the results
      if (searchId !== this.searchId) {
        return;
      }

      var qSwitcher = this;

      qSwitcher.valueObjects = [];

      if (items.length == 0) {
        this.$results.html('');
        this.usePane(this.searchText ? this.$noResults : this.$noSearchTerms);
        return;
      }

      var $ul = $('
');

      items.forEach(function(value, index) {
        var $li = $('
');
        var $container = $('
');
        $ul.append($li);
        $li.append($container);
        qSwitcher.setListText($container, value);

        if (value.description) {
          var $description = $(
            ''
          );
          qSwitcher.setListText($description, value.description);
          $li.prepend($description);
        }

        $li.data('lstr-qswitcher', {'index': index});
        $container.addClass('lstr-qswitcher-result-container');

        if (value.searchCallback) {
          $li.addClass('lstr-qswitcher-result-category');
        }

        qSwitcher.valueObjects[index] = {
          'index': index,
          'value': value,
          '$li': $li,
        };
      });

      this.$results.html($ul);
      this.usePane(this.$results);

      qSwitcher.selectIndex(0);
      qSwitcher.scrollToSelectedItem();
      if (window.requestAnimationFrame) {
        window.requestAnimationFrame(function() {
          qSwitcher.scrollToSelectedItem();
        });
      }
    },

    setError: function(searchId) {
      if (searchId !== this.searchId) {
        return;
      }

      this.usePane(this.$oopsResults);
    },

    renderBreadcrumb: function() {
      if (this.callbackStack.length == 0) {
        this.$domElement.removeClass('lstr-qswitcher-subsearch');
        this.$breadcrumb.html('');
        return;
      }

      var $ul = $('
');

      this.callbackStack.forEach(function(value, index) {
        var $li = $('
');
        $li.text(value.text);
        $ul.append($li);
      });

      this.$domElement.addClass('lstr-qswitcher-subsearch');
      this.$breadcrumb.html($ul);
    },

    setListText: function($element, value) {
      if (value.html) {
        $element.html(callbackOrValue(value.html));
        return;
      }

      if (value.text) {
        $element.html(callbackOrValue(value.text));
        return;
      }

      $element.text(value);
    },

    selectIndex: function(selectedIndex) {
      if (this.selectedIndex !== null
        && this.valueObjects[this.selectedIndex]
      ) {
        this.valueObjects[this.selectedIndex]
          .$li.removeClass('lstr-qswitcher-result-selected');
      }

      if (null === selectedIndex || 0 === this.valueObjects.length) {
        this.selectedIndex = null;
        return;
      }

      this.selectedIndex = selectedIndex % this.valueObjects.length;

      if (this.selectedIndex < 0) {
        this.selectedIndex = this.valueObjects.length - 1;
      }

      this.valueObjects[this.selectedIndex]
        .$li.addClass('lstr-qswitcher-result-selected');
    },

    scrollToSelectedItem: function() {
      var $results = this.$results;

      if (!this.selectedIndex) {
        $results.scrollTop(0);
        return;
      }

      var $li = this.valueObjects[this.selectedIndex].$li;

      var topOfLi = $li.offset().top - $li.parent().offset().top;
      var bottomOfLi = topOfLi + $li.outerHeight(true);
      var scrollTop = $results.scrollTop();
      var scrollBottom = scrollTop + $results.outerHeight(true);

      if (bottomOfLi > scrollBottom || topOfLi < scrollTop) {
        $results.scrollTop(topOfLi);
      }
    },

    toggleSwitcher: function() {
      if (this.$parentDom.hasClass('lstr-qswitcher-noscroll')) {
        this.closeSwitcher();
        return;
      }

      return this.openSwitcher();
    },

    openSwitcher: function() {
      this.useRootCallback();
      this.$search.val('');
      this.searchText = '';
      this.renderList();

      this.$parentDom.toggleClass('lstr-qswitcher-noscroll');
      this.$search.focus();
    },

    closeSwitcher: function() {
      this.$parentDom.removeClass('lstr-qswitcher-noscroll');
    },

    triggerSelect: function(index, event) {
      if (null === index) {
        return;
      }

      var selectedValue = this.valueObjects[index].value;
      var selectedResult = Object.create(SelectedResult);
      selectedResult.init(selectedValue, this.searchText, event);

      if (selectedValue.searchCallback) {
        if (false === this.selectChildSearchCallback(selectedResult)) {
          return;
        }

        this.callbackStack.push({
          'text': selectedValue.breadcrumbText,
          'parent': this.options,
        });

        this.options = selectedValue;
        this.searchCallback = selectedValue.searchCallback;
        if (selectedValue.searchDelay) {
          this.searchDelay = selectedValue.searchDelay;
        }
        if (selectedValue.selectCallback) {
          this.selectCallback = selectedValue.selectCallback;
        }
        if (selectedValue.selectChildSearchCallback) {
          this.selectChildSearchCallback
            = selectedValue.selectChildSearchCallback;
        }

        this.valueObjects = [];
        this.selectIndex(null);
        this.$search.val('');
        this.searchText = '';
        this.renderList();

        return;
      }

      if (false !== this.selectCallback(selectedResult)) {
        this.closeSwitcher();
      }
    },

    popCallback: function() {
      var callbacks = this.callbackStack.pop();
      if (!callbacks) {
        return false;
      }

      this.setOptions(callbacks.parent);

      return true;
    },

    useRootCallback: function() {
      while (this.callbackStack.length > 0) {
        this.popCallback();
      }
    },

    usePane: function($paneToUse) {
      this.$results.hide();
      this.$noSearchTerms.hide();
      this.$noResults.hide();
      this.$oopsResults.hide();
      this.$loading.hide();

      $paneToUse.show();
    },

    setOptions: function(options) {
      this.options = options;

      this.searchCallback = options.searchCallback;
      this.searchDelay = options.searchDelay;
      this.selectCallback = options.selectCallback;
      this.selectChildSearchCallback = options.selectChildSearchCallback;
    },
  };

  var lstrQuickSwitcher = function(options) {
    var $parentDom = $('body');

    var quickSwitcher = Object.create(QuickSwitcher);
    quickSwitcher.init($parentDom, options);

    return {
      open: quickSwitcher.openSwitcher.bind(quickSwitcher),
    };
  };

  return lstrQuickSwitcher;
};

define(
  'quick-switcher',
  ['filters', 'selected-result', 'sorters'],
  quickSwitcher
);
<commit_msg>Highlight items on tap start<commit_after>var quickSwitcher = function(filters, SelectedResult, sorters) {
  var $ = jQuery;

  var ResultHandler = {
    filters: filters,
    sorters: sorters,
  };

  var callbackOrValue = function(value) {
    return (typeof value === 'function') ? value() : value;
  };

  var QuickSwitcher = {
    init: function($parentDom, options) {
      this.$parentDom = null;
      this.$liCollection = null;
      this.valueObjects = null;
      this.selectedIndex = null;
      this.$results = null;
      this.$noSearchTerms = null;
      this.$noResults = null;
      this.$loading = null;
      this.$breadcrumb = null;
      this.$search = null;
      this.searchText = '';
      this.searchDelayTimeout = null;
      this.searchId = 0;

      this.modifierKey = 'ctrlKey';
      if (navigator.platform.toLowerCase().indexOf('mac') != -1) {
        this.modifierKey = 'metaKey';
      }

      options = $.extend({
        searchCallback: function() {},
        selectCallback: function() {},
        selectChildSearchCallback: function() {},
        searchDelay: 1000,
        hotKey: 'K',
      }, options);

      this.hotKey = options.hotKey.toUpperCase();

      this.setOptions({
        searchCallback: options.searchCallback,
        selectCallback: options.selectCallback,
        selectChildSearchCallback: options.selectChildSearchCallback,
        searchDelay: options.searchDelay,
      });

      this.initDomElement($parentDom);

      this.callbackStack = [];
      this.abortSearchCallback = null;
    },

    initDomElement: function($parentDom) {
      var qSwitcher = this;

      this.$parentDom = $parentDom;
      this.$domElement = $(
        '
' +
        '
' +
        '
' +
        '  <form class="lstr-qswitcher-popup">' +
        '
' +
        '
' +
        '
' +
        '
' +
        '
↕ to navigate
' +
        '
↵ to select
' +
        '
⌫ to clear
' +
        '
esc to dismiss
' +
        '
' +
        '
' +
        '    ×' +
        '
<input type="text" class="lstr-qswitcher-search form-control" />
' +
        '
Loading...
' +
        '

' +
        '
No results found
' +
        '
' +
        '      Oops! Something went wrong while trying to load your results.' +
        '
' +
        '

' +
        '  </form>' +
        '
'
      );

      $parentDom.append(this.$domElement);

      this.$breadcrumb = this.$domElement.find('.lstr-qswitcher-breadcrumb');
      this.$close = this.$domElement.find('.lstr-qswitcher-close');
      this.$search = this.$domElement.find('.lstr-qswitcher-search');
      this.$loading = this.$domElement.find('.lstr-qswitcher-loading');
      this.$results = this.$domElement.find('.lstr-qswitcher-results');
      this.$noSearchTerms = this.$domElement.find('.lstr-qswitcher-no-terms');
      this.$noResults = this.$domElement.find('.lstr-qswitcher-no-results');
      this.$oopsResults = this.$domElement.find('.lstr-qswitcher-oops-results');

      var $domElement = this.$domElement;

      $domElement.find('.lstr-qswitcher-popup').on('submit', function(event) {
        event.preventDefault();
      });
      $parentDom.find('.lstr-qswitcher-overlay').on('click', function(event) {
        qSwitcher.closeSwitcher();
        event.preventDefault();
      });
      $parentDom.on('keydown', function(event) {
        var keyPressed = String.fromCharCode(event.which);
        if (event[qSwitcher.modifierKey] && keyPressed === qSwitcher.hotKey) {
          qSwitcher.toggleSwitcher();
          event.preventDefault();
        }
      });
      $('html').on('keydown', '.lstr-qswitcher-noscroll', function(event) {
        if (event.which === 38) { // up arrow key
          qSwitcher.selectIndex(qSwitcher.selectedIndex - 1);
          qSwitcher.scrollToSelectedItem();
          event.preventDefault();
        } else if (event.which === 40) { // down arrow key
          qSwitcher.selectIndex(qSwitcher.selectedIndex + 1);
          qSwitcher.scrollToSelectedItem();
          event.preventDefault();
        } else if (event.which === 27) { // escape key
          qSwitcher.toggleSwitcher();
          event.preventDefault();
        } else if (13 === event.keyCode) {
          qSwitcher.triggerSelect(qSwitcher.selectedIndex, event);
          event.preventDefault();
        }
      });
      this.$close.on('click', function(event) {
        qSwitcher.closeSwitcher();
      });
      this.$search.on('keyup', function(event) {
        var searchText = qSwitcher.$search.val();

        if (qSwitcher.searchDelayTimeout) {
          clearTimeout(qSwitcher.searchDelayTimeout);
          qSwitcher.searchDelayTimeout = null;
        }

        if (searchText !== qSwitcher.searchText) {
          qSwitcher.searchDelayTimeout = setTimeout(function() {
            qSwitcher.selectIndex(null);
            qSwitcher.searchText = searchText;
            qSwitcher.renderList();
          }, qSwitcher.searchDelay);
        } else if (event.which === 8 && '' === searchText) {
          // backspace with text box blank
          qSwitcher.popCallback();
          qSwitcher.renderList();
        }
      });
      $domElement.on('mouseover', '.lstr-qswitcher-results li', function() {
        var $li = $(this);
        qSwitcher.selectIndex($li.data('lstr-qswitcher').index);
      });
      $domElement.on('touchstart', '.lstr-qswitcher-results li', function() {
        var $li = $(this);
        qSwitcher.selectIndex($li.data('lstr-qswitcher').index);
      });
      $domElement.on('click', '.lstr-qswitcher-results li', function(event) {
        var $li = $(this);
        qSwitcher.triggerSelect($li.data('lstr-qswitcher').index, event);
      });
    },

    renderList: function() {
      if (this.abortSearchCallback) {
        this.abortSearchCallback();
        this.abortSearchCallback = null;
      }

      this.renderBreadcrumb();

      this.usePane(this.$loading);

      var resultHandler = Object.create(ResultHandler);
      ++this.searchId;
      resultHandler.setResults = this.setResults.bind(this, this.searchId);
      resultHandler.setError = this.setError.bind(this, this.searchId);
      this.abortSearchCallback = this.searchCallback(
        this.searchText,
        resultHandler
      );
    },

    setResults: function(searchId, items) {
      // if the search ID provided to setResults is not the current searchId,
      // ignore the results
      if (searchId !== this.searchId) {
        return;
      }

      var qSwitcher = this;

      qSwitcher.valueObjects = [];

      if (items.length == 0) {
        this.$results.html('');
        this.usePane(this.searchText ? this.$noResults : this.$noSearchTerms);
        return;
      }

      var $ul = $('
');

      items.forEach(function(value, index) {
        var $li = $('
');
        var $container = $('
');
        $ul.append($li);
        $li.append($container);
        qSwitcher.setListText($container, value);

        if (value.description) {
          var $description = $(
            ''
          );
          qSwitcher.setListText($description, value.description);
          $li.prepend($description);
        }

        $li.data('lstr-qswitcher', {'index': index});
        $container.addClass('lstr-qswitcher-result-container');

        if (value.searchCallback) {
          $li.addClass('lstr-qswitcher-result-category');
        }

        qSwitcher.valueObjects[index] = {
          'index': index,
          'value': value,
          '$li': $li,
        };
      });

      this.$results.html($ul);
      this.usePane(this.$results);

      qSwitcher.selectIndex(0);
      qSwitcher.scrollToSelectedItem();
      if (window.requestAnimationFrame) {
        window.requestAnimationFrame(function() {
          qSwitcher.scrollToSelectedItem();
        });
      }
    },

    setError: function(searchId) {
      if (searchId !== this.searchId) {
        return;
      }

      this.usePane(this.$oopsResults);
    },

    renderBreadcrumb: function() {
      if (this.callbackStack.length == 0) {
        this.$domElement.removeClass('lstr-qswitcher-subsearch');
        this.$breadcrumb.html('');
        return;
      }

      var $ul = $('
');

      this.callbackStack.forEach(function(value, index) {
        var $li = $('
');
        $li.text(value.text);
        $ul.append($li);
      });

      this.$domElement.addClass('lstr-qswitcher-subsearch');
      this.$breadcrumb.html($ul);
    },

    setListText: function($element, value) {
      if (value.html) {
        $element.html(callbackOrValue(value.html));
        return;
      }

      if (value.text) {
        $element.html(callbackOrValue(value.text));
        return;
      }

      $element.text(value);
    },

    selectIndex: function(selectedIndex) {
      if (this.selectedIndex !== null
        && this.valueObjects[this.selectedIndex]
      ) {
        this.valueObjects[this.selectedIndex]
          .$li.removeClass('lstr-qswitcher-result-selected');
      }

      if (null === selectedIndex || 0 === this.valueObjects.length) {
        this.selectedIndex = null;
        return;
      }

      this.selectedIndex = selectedIndex % this.valueObjects.length;

      if (this.selectedIndex < 0) {
        this.selectedIndex = this.valueObjects.length - 1;
      }

      this.valueObjects[this.selectedIndex]
        .$li.addClass('lstr-qswitcher-result-selected');
    },

    scrollToSelectedItem: function() {
      var $results = this.$results;

      if (!this.selectedIndex) {
        $results.scrollTop(0);
        return;
      }

      var $li = this.valueObjects[this.selectedIndex].$li;

      var topOfLi = $li.offset().top - $li.parent().offset().top;
      var bottomOfLi = topOfLi + $li.outerHeight(true);
      var scrollTop = $results.scrollTop();
      var scrollBottom = scrollTop + $results.outerHeight(true);

      if (bottomOfLi > scrollBottom || topOfLi < scrollTop) {
        $results.scrollTop(topOfLi);
      }
    },

    toggleSwitcher: function() {
      if (this.$parentDom.hasClass('lstr-qswitcher-noscroll')) {
        this.closeSwitcher();
        return;
      }

      return this.openSwitcher();
    },

    openSwitcher: function() {
      this.useRootCallback();
      this.$search.val('');
      this.searchText = '';
      this.renderList();

      this.$parentDom.toggleClass('lstr-qswitcher-noscroll');
      this.$search.focus();
    },

    closeSwitcher: function() {
      this.$parentDom.removeClass('lstr-qswitcher-noscroll');
    },

    triggerSelect: function(index, event) {
      if (null === index) {
        return;
      }

      var selectedValue = this.valueObjects[index].value;
      var selectedResult = Object.create(SelectedResult);
      selectedResult.init(selectedValue, this.searchText, event);

      if (selectedValue.searchCallback) {
        if (false === this.selectChildSearchCallback(selectedResult)) {
          return;
        }

        this.callbackStack.push({
          'text': selectedValue.breadcrumbText,
          'parent': this.options,
        });

        this.options = selectedValue;
        this.searchCallback = selectedValue.searchCallback;
        if (selectedValue.searchDelay) {
          this.searchDelay = selectedValue.searchDelay;
        }
        if (selectedValue.selectCallback) {
          this.selectCallback = selectedValue.selectCallback;
        }
        if (selectedValue.selectChildSearchCallback) {
          this.selectChildSearchCallback
            = selectedValue.selectChildSearchCallback;
        }

        this.valueObjects = [];
        this.selectIndex(null);
        this.$search.val('');
        this.searchText = '';
        this.renderList();

        return;
      }

      if (false !== this.selectCallback(selectedResult)) {
        this.closeSwitcher();
      }
    },

    popCallback: function() {
      var callbacks = this.callbackStack.pop();
      if (!callbacks) {
        return false;
      }

      this.setOptions(callbacks.parent);

      return true;
    },

    useRootCallback: function() {
      while (this.callbackStack.length > 0) {
        this.popCallback();
      }
    },

    usePane: function($paneToUse) {
      this.$results.hide();
      this.$noSearchTerms.hide();
      this.$noResults.hide();
      this.$oopsResults.hide();
      this.$loading.hide();

      $paneToUse.show();
    },

    setOptions: function(options) {
      this.options = options;

      this.searchCallback = options.searchCallback;
      this.searchDelay = options.searchDelay;
      this.selectCallback = options.selectCallback;
      this.selectChildSearchCallback = options.selectChildSearchCallback;
    },
  };

  var lstrQuickSwitcher = function(options) {
    var $parentDom = $('body');

    var quickSwitcher = Object.create(QuickSwitcher);
    quickSwitcher.init($parentDom, options);

    return {
      open: quickSwitcher.openSwitcher.bind(quickSwitcher),
    };
  };

  return lstrQuickSwitcher;
};

define(
  'quick-switcher',
  ['filters', 'selected-result', 'sorters'],
  quickSwitcher
);
<|endoftext|>


<commit_before>'use strict';

var vc;

module.exports = function(v4) {
    v4.version = 4;
    vc = v4.constants;
    convertConstants(vc);
    rmTileSize(v4.sources);
    v4.layers.forEach(convertLayer);
    return v4;
};

function rmTileSize(sources) {
    for (var source in sources) {
        if (sources[source]['type'] != 'raster' && sources[source]['tileSize']) delete sources[source]['tileSize'];
    }
}

function convertLayer(layer) {
    // convert linear/exponential functions to stop functions
    // decrement zoom level of functions by 1 for map tileSize (512) change
    for (var classname in layer) {
        if (layer[classname]['text-max-angle']) {
            layer[classname]['text-max-angle'] = Number((layer[classname]['text-max-angle'] * 180 / Math.PI).toFixed(2));
        }
        if (classname.indexOf('style') === -1) continue;
        var style = layer[classname];
        for (var propname in style) {
            if (Array.isArray(style[propname])) {
                for (var prop in style[propname]) {
                    if (!style[propname][prop].fn) continue;
                    style[propname][prop] = fnBucket(style[propname][prop])
                }
            };
            if (!style[propname].fn) continue;
            style[propname] = fnBucket(style[propname]);
        }
    }

    if (layer.layers) layer.layers.forEach(convertLayer);

}

function convertConstants(constants) {
    for (var constant in constants) {
        if (constants[constant].fn) {
            constants[constant] = fnBucket(constants[constant]);
        };

        if (Array.isArray(constants[constant])) {
            for (var item in constants[constant]) {
                if (constants[constant][item].fn) {
                    constants[constant][item] = fnBucket(constants[constant][item]);
                };
            }
        };
    }
}

function fnBucket(oldfn) {
    var newfn;
    if (oldfn.fn === 'stops') {
        newfn = { stops: oldfn.stops };
    } else if (oldfn.fn === 'linear' || oldfn.fn === 'exponential') {
        newfn = migrateFn(oldfn);
    }
    // Decrement zoom levels by 1.
    newfn.stops = newfn.stops.map(deczoom);
    return newfn;
}

function deczoom(pair) {
    return [Math.max(0, pair[0] - 1), pair[1]];
}

function migrateFn(params) {
    var newparams = {};
    var minZoom = 0;
    var maxZoom = 20;
    var fn;
    if (params.fn === 'exponential') {
        fn = exponential(params);
        if (params.base) newparams.base = params.base;
        if (params.min !== undefined) minZoom = reverseExponential(params, Math.max(params.min, params.val));
        if (params.max !== undefined) maxZoom = reverseExponential(params, params.max);
        newparams.stops = [
            [minZoom, fn(minZoom)],
            [maxZoom, fn(maxZoom)]
        ];
    } else if (params.fn === 'linear') {
        fn = linear(params);
        newparams.base = 1.01;
        if (params.min !== undefined) minZoom = reverseLinear(params, params.min);
        if (params.max !== undefined) maxZoom = reverseLinear(params, params.max);
        newparams.stops = [
            [minZoom, fn(minZoom)],
            [maxZoom, fn(maxZoom)]
        ];
    }

    return newparams;
}

function reverseExponential(params, value) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0,
        base = +params.base || 1.75;
    return Math.log(((value - val) || 0.01) / slope) / Math.log(base) + z_base;
}

function reverseLinear(params, value) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0;
    return (value - val) / slope + z_base;
}

function linear(params) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0,
        min = +params.min || 0,
        max = +params.max || Infinity;
    return function(z) {
        return Math.min(Math.max(min, val + (z - z_base) * slope), max);
    };
}

function exponential(params) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0,
        min = +params.min || 0,
        max = +params.max || Infinity,
        base = +params.base || 1.75;
    return function(z) {
        return Math.min(Math.max(min, val + Math.pow(base, (z - z_base)) * slope), max);
    };
}
<commit_msg>jshint<commit_after>'use strict';

var vc;

module.exports = function(v4) {
    v4.version = 4;
    vc = v4.constants;
    convertConstants(vc);
    rmTileSize(v4.sources);
    v4.layers.forEach(convertLayer);
    return v4;
};

function rmTileSize(sources) {
    for (var source in sources) {
        if (sources[source].type != 'raster' && sources[source].tileSize) delete sources[source].tileSize;
    }
}

function convertLayer(layer) {
    // convert linear/exponential functions to stop functions
    // decrement zoom level of functions by 1 for map tileSize (512) change
    for (var classname in layer) {
        if (layer[classname]['text-max-angle']) {
            layer[classname]['text-max-angle'] = Number((layer[classname]['text-max-angle'] * 180 / Math.PI).toFixed(2));
        }
        if (classname.indexOf('style') === -1) continue;
        var style = layer[classname];
        for (var propname in style) {
            if (Array.isArray(style[propname])) {
                for (var prop in style[propname]) {
                    if (!style[propname][prop].fn) continue;
                    style[propname][prop] = fnBucket(style[propname][prop]);
                }
            }
            if (!style[propname].fn) continue;
            style[propname] = fnBucket(style[propname]);
        }
    }

    if (layer.layers) layer.layers.forEach(convertLayer);

}

function convertConstants(constants) {
    for (var constant in constants) {
        if (constants[constant].fn) {
            constants[constant] = fnBucket(constants[constant]);
        }

        if (Array.isArray(constants[constant])) {
            for (var item in constants[constant]) {
                if (constants[constant][item].fn) {
                    constants[constant][item] = fnBucket(constants[constant][item]);
                }
            }
        }
    }
}

function fnBucket(oldfn) {
    var newfn;
    if (oldfn.fn === 'stops') {
        newfn = { stops: oldfn.stops };
    } else if (oldfn.fn === 'linear' || oldfn.fn === 'exponential') {
        newfn = migrateFn(oldfn);
    }
    // Decrement zoom levels by 1.
    newfn.stops = newfn.stops.map(deczoom);
    return newfn;
}

function deczoom(pair) {
    return [Math.max(0, pair[0] - 1), pair[1]];
}

function migrateFn(params) {
    var newparams = {};
    var minZoom = 0;
    var maxZoom = 20;
    var fn;
    if (params.fn === 'exponential') {
        fn = exponential(params);
        if (params.base) newparams.base = params.base;
        if (params.min !== undefined) minZoom = reverseExponential(params, Math.max(params.min, params.val));
        if (params.max !== undefined) maxZoom = reverseExponential(params, params.max);
        newparams.stops = [
            [minZoom, fn(minZoom)],
            [maxZoom, fn(maxZoom)]
        ];
    } else if (params.fn === 'linear') {
        fn = linear(params);
        newparams.base = 1.01;
        if (params.min !== undefined) minZoom = reverseLinear(params, params.min);
        if (params.max !== undefined) maxZoom = reverseLinear(params, params.max);
        newparams.stops = [
            [minZoom, fn(minZoom)],
            [maxZoom, fn(maxZoom)]
        ];
    }

    return newparams;
}

function reverseExponential(params, value) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0,
        base = +params.base || 1.75;
    return Math.log(((value - val) || 0.01) / slope) / Math.log(base) + z_base;
}

function reverseLinear(params, value) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0;
    return (value - val) / slope + z_base;
}

function linear(params) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0,
        min = +params.min || 0,
        max = +params.max || Infinity;
    return function(z) {
        return Math.min(Math.max(min, val + (z - z_base) * slope), max);
    };
}

function exponential(params) {
    var z_base = +params.z || 0,
        val = +params.val || 0,
        slope = +params.slope || 0,
        min = +params.min || 0,
        max = +params.max || Infinity,
        base = +params.base || 1.75;
    return function(z) {
        return Math.min(Math.max(min, val + Math.pow(base, (z - z_base)) * slope), max);
    };
}
<|endoftext|>


<commit_before>var Db = require('./Db');

var DbManager = function(){
    this.dbs = {};
};

DbManager.prototype.getConnection = function(done) {
    var key = 'database';
    if(!this.dbs[key]) {
        this.dbs[key] = new Db(key);
    }
    done(null, this.dbs[key]);
};

module.exports = DbManager;<commit_msg>Deleted obsolete DbManager.js<commit_after><|endoftext|>


<commit_before>/*
 * Framework	: SANBREEZE Resposive Web JS
 * Version	: 1.0.0
 * Filename	: sb-rwjs.js
 * Copyright    : © 2014, Mario Briesemeister
 *
 *
 * Documentation:
 *	Please visit https://github.com/SANBREEZE/RWJS/ for more information
 *	about to integrate this framework to your site and for downloading
 *	this framework.
 *
 *
 * Requirements	:
 *	jQuery 1.11.x or higher
 *
 *
 * Notes	:
 *	Do not use jQuery 2.x - we have not test this framework version.
 *
 *
 * Rights	:
 *	The MIT License (MIT)
 *
 *	Copyright (c) 2014, SANBREEZE GmbH
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in all
 *	copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *	SOFTWARE.
 *
*/

(function($, fw){
	$.fn[fw] = function(fn) {
		var defs = {
			body : "body"
		},opt;

		var SB_RWJS = function() {
			var v = ["1.11.0", "1.11.1"];
			if (v.indexOf($.fn.jquery) == -1) {
				o = "jQuery between version " + v[0] + " - " + v[v.length-1] + " is required!";
				console.log(o);
				document.write(o);
				return false;
			} else {
				$.fn.contextPopup = function() {
					this.bind("contextmenu", function(e) {
						return false;
					});
					return this;
				};
				$(function() {
					$(opt.body).contextPopup();
				});
			}
		}();

		return {
			setup : function(o) {
				opt = $.extend(defs, o);
			}
		}
	}
})(jQuery, "SB_RWJS");
<commit_msg>Update sb-rwjs.js<commit_after>/*
 * Framework	: SANBREEZE Resposive Web JS
 * Version	: 1.0.0
 * Filename	: sb-rwjs.js
 * Copyright    : 2014, Mario Briesemeister
 *
 *
 * Documentation:
 *	Please visit https://github.com/SANBREEZE/RWJS/ for more information
 *	about to integrate this framework to your site and for downloading
 *	this framework.
 *
 *
 * Requirements	:
 *	jQuery 1.11.x or higher
 *
 *
 * Notes	:
 *	Do not use jQuery 2.x - we have not test this framework version.
 *
 *
 * Rights	:
 *	The MIT License (MIT)
 *
 *	Copyright (c) 2014, SANBREEZE GmbH
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in all
 *	copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *	SOFTWARE.
 *
*/

(function($, fw){
	$.fn[fw] = function(fn) {
		var defs = {
			body : "body"
		},opt;

		var SB_RWJS = function() {
			var v = ["1.11.0", "1.11.1"];
			if (v.indexOf($.fn.jquery) == -1) {
				o = "jQuery between version " + v[0] + " - " + v[v.length-1] + " is required!";
				console.log(o);
				document.write(o);
				return false;
			} else {
				$.fn.contextPopup = function() {
					this.bind("contextmenu", function(e) {
						return false;
					});
					return this;
				};
				$(function() {
					$(opt.body).contextPopup();
				});
			}
		}();

		return {
			setup : function(o) {
				opt = $.extend(defs, o);
			}
		}
	}
})(jQuery, "SB_RWJS");
<|endoftext|>


<commit_before>$(function() {
  var mobilenav = $('#mobile-nav');

  $('html').click(function(){
    mobilenav.find('.on').each(function(){
      $(this).removeClass('on').next().hide();
    });
  });

  mobilenav.on('click', '.menu .button', function(e){
    if (!$(this).hasClass('on')) {
      var width = $(this).width() + 42;
      $(this).addClass('on').next().css({width: width}).show();
    } else {
      $(this).removeClass('on').next().hide();
    }
  }).on('click', '.search .button', function(e){
    if (!$(this).hasClass('on')){
      var width = mobilenav.width() - 51;
      mobilenav.children('.menu').children().eq(0).removeClass('on').next().hide();
      $(this).addClass('on').next().show().css({width: width}).children().children().eq(0).focus();
    } else {
      $(this).removeClass('on').next().hide().children().children().eq(0).val('');
    }
  }).click(function(e){
    e.stopPropagation();
  });

  var $nav = $('#main-nav .main');
  var $search = $('.desk_search');

  var hideSearch = function() {
    $nav.removeClass('searching');
    $search.hide();
  };

  var showSearch = function() {
    $nav.addClass('searching');
    $search.show().find('input[type="text"]').focus();
  };

  $('#search_btn').click(function() {
    if ($nav.hasClass('searching')) {
      hideSearch();
    } else {
      showSearch();
    }
  });

  $('.desk_search input[type="text"]').keyup(function(e) {
    if (e.keyCode == 27) {
      hideSearch();
    }
  })

  window.refresh = function () {
    // header links
    $('.entry-content').find('h1, h2, h3, h4, h5').each(function() {
      var $id = $(this).attr('id');
      var $text = $(this).text();

      $(this).html('').prepend('#')
             .append('' + $text + '');
    });

    $('.collapse').not(function() {
      return "#" + $(this).attr('id') == window.location.hash;
    }).next('.collapsible').hide();

    $('.collapse').click(function(e) {
      e.preventDefault();
      $(this).next('.collapsible').slideToggle('fast');
    });

    $('a[href^="#fnref"]').html('');
  };

  window.refresh();
});
<commit_msg>add tooltip to footnote return links<commit_after>$(function() {
  var mobilenav = $('#mobile-nav');

  $('html').click(function(){
    mobilenav.find('.on').each(function(){
      $(this).removeClass('on').next().hide();
    });
  });

  mobilenav.on('click', '.menu .button', function(e){
    if (!$(this).hasClass('on')) {
      var width = $(this).width() + 42;
      $(this).addClass('on').next().css({width: width}).show();
    } else {
      $(this).removeClass('on').next().hide();
    }
  }).on('click', '.search .button', function(e){
    if (!$(this).hasClass('on')){
      var width = mobilenav.width() - 51;
      mobilenav.children('.menu').children().eq(0).removeClass('on').next().hide();
      $(this).addClass('on').next().show().css({width: width}).children().children().eq(0).focus();
    } else {
      $(this).removeClass('on').next().hide().children().children().eq(0).val('');
    }
  }).click(function(e){
    e.stopPropagation();
  });

  var $nav = $('#main-nav .main');
  var $search = $('.desk_search');

  var hideSearch = function() {
    $nav.removeClass('searching');
    $search.hide();
  };

  var showSearch = function() {
    $nav.addClass('searching');
    $search.show().find('input[type="text"]').focus();
  };

  $('#search_btn').click(function() {
    if ($nav.hasClass('searching')) {
      hideSearch();
    } else {
      showSearch();
    }
  });

  $('.desk_search input[type="text"]').keyup(function(e) {
    if (e.keyCode == 27) {
      hideSearch();
    }
  })

  window.refresh = function () {
    // header links
    $('.entry-content').find('h1, h2, h3, h4, h5').each(function() {
      var $id = $(this).attr('id');
      var $text = $(this).text();

      $(this).html('').prepend('#')
             .append('' + $text + '');
    });

    $('.collapse').not(function() {
      return "#" + $(this).attr('id') == window.location.hash;
    }).next('.collapsible').hide();

    $('.collapse').click(function(e) {
      e.preventDefault();
      $(this).next('.collapsible').slideToggle('fast');
    });

    $('a[href^="#fnref"]').attr({title: 'continue reading'}).html('');
  };

  window.refresh();
});
<|endoftext|>


<commit_before>angular
    .module('app', [
        'ui.router'
        ])
    .config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider){
        $urlRouterProvider.otherwise('/'); //seems to control what happens when navigating directly to routes from within the domain of the app

        //given to us by ui-router
        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: 'app/home/home.html'
            })
            .state('about', {
                url: '/about',
                templateUrl: 'app/about/about.html'
            })
    }])<commit_msg>breaks out home controller into separate file<commit_after>angular
    .module('app', [
        'ui.router'
        ])
    .config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider){
        $urlRouterProvider.otherwise('/'); //seems to control what happens when navigating directly to routes from within the domain of the app

        //given to us by ui-router
        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: 'app/home/home.html',
                controller: 'homeController'
            })
            .state('about', {
                url: '/about',
                templateUrl: 'app/about/about.html'
            })
    }])<|endoftext|>


<commit_before>'use strict';

// Start by defining the main module and adding the module dependencies.
angular.module(ApplicationConfiguration.applicationModuleName,
               ApplicationConfiguration.applicationModuleVendorDependencies);

// Setting HTML5 Location Mode.
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
  function($locationProvider) {
    // Enable app to use HTML5 History API.
    $locationProvider.html5Mode(true);//.hashPrefix('!');
  }
]);

//Then define the init function for starting up the application
angular.element(document).ready(function() {
  //Fixing facebook bug with redirect
  if (window.location.hash === '#_=_') {
    window.location.hash = '#!';
  }

  //Then init the app
  angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
<commit_msg>Remove irrelevant facebook bug as it does not affect the application after it is port to HTML5 mode.<commit_after>'use strict';

// Start by defining the main module and adding the module dependencies.
angular.module(ApplicationConfiguration.applicationModuleName,
               ApplicationConfiguration.applicationModuleVendorDependencies);

// Setting HTML5 Location Mode.
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
  function($locationProvider) {
    // Enable app to use HTML5 History API.
    $locationProvider.html5Mode(true);//.hashPrefix('!');
  }
]);

//Then define the init function for starting up the application
angular.element(document).ready(function() {
  //Then init the app
  angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
<|endoftext|>


<commit_before>var ws = new WebSocket("ws://localhost:8080");

ws.onopen = function() {
    ws.send("oslo");
};

ws.onmessage = function(e) {
    var rows = JSON.parse(e.data);
    console.log(rows);
};

<commit_msg>less french words<commit_after>var ws = new WebSocket("ws://localhost:8080");
var bus = new Bacon.Bus();

ws.onopen = function() {
    ws.send("oslo");
};

ws.onmessage = function(e) {
    var rows = JSON.parse(e.data);
    bus.push(rows);
};

<|endoftext|>


<commit_before>// Set up crossfilter
var ndx = crossfilter([
	{key: 'C', value: '6'},	{key: 'B', value: '5'},
	{key: 'B', value: '0'},	{key: 'C', value: '3'},
	{key: 'A', value: '8'},	{key: 'B', value: '6'},
	{key: 'B', value: '9'},	{key: 'C', value: '6'},
	{key: 'B', value: '1'},	{key: 'B', value: '9'},
	{key: 'A', value: '8'},	{key: 'B', value: '2'},
	{key: 'A', value: '3'},	{key: 'B', value: '8'},
	{key: 'B', value: '0'},	{key: 'A', value: '5'},
	{key: 'A', value: '9'},	{key: 'C', value: '3'},
	{key: 'C', value: '1'},	{key: 'A', value: '5'},
	{key: 'B', value: '3'},	{key: 'A', value: '2'},
	{key: 'B', value: '3'},	{key: 'C', value: '2'},
	{key: 'B', value: '0'},	{key: 'C', value: '2'},
	{key: 'C', value: '6'},	{key: 'B', value: '7'},
	{key: 'B', value: '9'},	{key: 'C', value: '4'},
	{key: 'B', value: '5'},	{key: 'A', value: '6'},
	{key: 'A', value: '0'},	{key: 'A', value: '6'},
	{key: 'A', value: '9'},	{key: 'A', value: '7'},
	{key: 'C', value: '2'},	{key: 'B', value: '8'},
	{key: 'C', value: '4'},	{key: 'C', value: '3'},
	{key: 'B', value: '8'},	{key: 'B', value: '2'},
	{key: 'B', value: '6'},	{key: 'B', value: '1'},
	{key: 'A', value: '1'},	{key: 'A', value: '6'},
	{key: 'A', value: '6'},	{key: 'B', value: '4'},
	{key: 'B', value: '7'},	{key: 'C', value: '7'},
	{key: 'A', value: '7'},	{key: 'A', value: '7'}
]);

// Define dimensions
var key = ndx.dimension(function(d) { return d.key; }),
		value = ndx.dimension(function(d) { return d.value; });

// Define groups
var keyGroup = key.group(),
		valueGroup = value.group();

// Define charts properties
var keyChart = dc.rowChart('#row-chart'),
		valueChart = dc.barChart('#bar-chart');

// Define charts
keyChart
.dimension(key)
.group(keyGroup);

valueChart
.dimension(value)
.group(valueGroup)
.x(d3.scale.linear().domain([0, 10]));

// Optional design
valueChart.round(dc.round.floor)
var width = $('#width').width();
valueChart.width(width);
keyChart.width(width); // für CC nich nötig
keyChart.margins({top: 0, right: 35, bottom: 25, left: 5})
valueChart.margins({top: 5, right: 35, bottom: 25, left: 15})

// Update all charts
dc.renderAll();

// Setup crosscompare
crosscompare
.add(keyChart, { type: 'bar', order: 'desc' })
.add(valueChart);<commit_msg>added legend to tutorial chart<commit_after>// Set up crossfilter
var ndx = crossfilter([
	{key: 'C', value: '6'},	{key: 'B', value: '5'},
	{key: 'B', value: '0'},	{key: 'C', value: '3'},
	{key: 'A', value: '8'},	{key: 'B', value: '6'},
	{key: 'B', value: '9'},	{key: 'C', value: '6'},
	{key: 'B', value: '1'},	{key: 'B', value: '9'},
	{key: 'A', value: '8'},	{key: 'B', value: '2'},
	{key: 'A', value: '3'},	{key: 'B', value: '8'},
	{key: 'B', value: '0'},	{key: 'A', value: '5'},
	{key: 'A', value: '9'},	{key: 'C', value: '3'},
	{key: 'C', value: '1'},	{key: 'A', value: '5'},
	{key: 'B', value: '3'},	{key: 'A', value: '2'},
	{key: 'B', value: '3'},	{key: 'C', value: '2'},
	{key: 'B', value: '0'},	{key: 'C', value: '2'},
	{key: 'C', value: '6'},	{key: 'B', value: '7'},
	{key: 'B', value: '9'},	{key: 'C', value: '4'},
	{key: 'B', value: '5'},	{key: 'A', value: '6'},
	{key: 'A', value: '0'},	{key: 'A', value: '6'},
	{key: 'A', value: '9'},	{key: 'A', value: '7'},
	{key: 'C', value: '2'},	{key: 'B', value: '8'},
	{key: 'C', value: '4'},	{key: 'C', value: '3'},
	{key: 'B', value: '8'},	{key: 'B', value: '2'},
	{key: 'B', value: '6'},	{key: 'B', value: '1'},
	{key: 'A', value: '1'},	{key: 'A', value: '6'},
	{key: 'A', value: '6'},	{key: 'B', value: '4'},
	{key: 'B', value: '7'},	{key: 'C', value: '7'},
	{key: 'A', value: '7'},	{key: 'A', value: '7'}
]);

// Define dimensions
var key = ndx.dimension(function(d) { return d.key; }),
		value = ndx.dimension(function(d) { return d.value; });

// Define groups
var keyGroup = key.group(),
		valueGroup = value.group();

// Define charts properties
var keyChart = dc.rowChart('#row-chart'),
		valueChart = dc.barChart('#bar-chart');

// Define charts
keyChart
.dimension(key)
.group(keyGroup);

valueChart
.dimension(value)
.group(valueGroup)
.x(d3.scale.linear().domain([0, 10]));

// Optional design
valueChart.round(dc.round.floor)
var width = $('#width').width();
valueChart.width(width);
keyChart.width(width); // für CC nich nötig
keyChart.margins({top: 0, right: 35, bottom: 25, left: 5})
valueChart.margins({top: 5, right: 35, bottom: 25, left: 15})

// Update all charts
dc.renderAll();

// Setup crosscompare
crosscompare
.addLegend(valueChart)
.add(keyChart, { type: 'bar', order: 'desc' })
.add(valueChart);<|endoftext|>