<commit_before>/*global hilary*/

hilary.register('gutentyp::config', { init: function () {
    "use strict";

    var config = {}, autoCreateSelectors;

    config.prefixes = {
        pipeline: {
            beforeComponent: 'gutentyp::before::',
            afterComponent: 'gutentyp::after::'
        }
    };

    config.attributes = {
        formBtn: {
            key: 'data-form-btn',
            value: 'true'
        }
    };

    config.colors = [];
    config.colors.push({ title: 'Black', name: 'black', value: '#000000' });
    config.colors.push({ title: 'Grey', name: 'grey', value: '#62615f' });
    config.colors.push({ title: 'Light Grey', name: 'lightGrey', value: '#dcddd7' });
    config.colors.push({ title: 'Pink', name: 'pink', value: '#cd52bd' });
    config.colors.push({ title: 'Red', name: 'red', value: '#9a0000' });
    config.colors.push({ title: 'Yellow', name: 'yellow', value: '#f0ac28' });
    config.colors.push({ title: 'Green', name: 'green', value: '#6bb343' });
    config.colors.push({ title: 'Blue', name: 'blue', value: '#3c8bc8' });
    config.colors.push({ title: 'Purple', name: 'purple', value: '#a952cd' });

    config.icons = {
        code: 'fa fa-code',
        pre: 'fa fa-file-code-o',
        blockquote: 'fa fa-quote-left',
        bold: 'fa fa-bold',
        italic: 'fa fa-italic',
        underline: 'fa fa-underline',
        strikethrough: 'fa fa-strikethrough',
        header: 'fa fa-header',
        image: 'fa fa-image',
        alignLeft: 'fa fa-align-left',
        alignCenter: 'fa fa-align-center',
        alignRight: 'fa fa-align-right',
        alignJustify: 'fa fa-align-justify',
        indent: 'fa fa-indent',
        outdent: 'fa fa-outdent',
        link: 'fa fa-link',
        unorderedList: 'fa fa-list-ul',
        orderedList: 'fa fa-list-ol'
    };

    config.cssClasses = {
        toGutentypify: 'gutentyp-ify',
        gutentypified: 'gutentyp-ified',
        hasEvents: 'has-events',
        hasToolbar: 'has-toolbar',
        hasComponents: 'has-components',
        editor: 'gutentyp-editor',
        textarea: 'gutentyp-textarea',
        toolbar: 'gutentyp-toolbar',
        toolbarBtn: 'gutentyp-toolbar-btn',
        toolbarBtnText: 'gutentyp-toolbar-btn-text',
        toolbarBtnIcon: 'gutentyp-toolbar-btn-icon',
        hidden: 'gutentyp-hidden'
    };

    autoCreateSelectors = function () {
        var i;

        config.selectors = {};

        for (i in config.cssClasses) {
            if (config.cssClasses.hasOwnProperty(i)) {
                config.selectors[i] = '.' + config.cssClasses[i];
            }
        }

        config.selectors.newEditors = config.selectors.editor + ':not(' + config.selectors.hasToolbar + ')';
        config.selectors.eventlessEditors = config.selectors.editor + ':not(' + config.selectors.hasEvents + ')';
        config.selectors.newToolbars = config.selectors.toolbar + ':not(' + config.selectors.hasComponents + ')';
    };

    autoCreateSelectors();

    return config;

}});
<commit_msg>makes config.autoCreateSelectors public<commit_after>/*global hilary*/

hilary.register('gutentyp::config', { init: function () {
    "use strict";

    var config = {};

    config.prefixes = {
        pipeline: {
            beforeComponent: 'gutentyp::before::',
            afterComponent: 'gutentyp::after::'
        }
    };

    config.attributes = {
        formBtn: {
            key: 'data-form-btn',
            value: 'true'
        }
    };

    config.colors = [];
    config.colors.push({ title: 'Black', name: 'black', value: '#000000' });
    config.colors.push({ title: 'Grey', name: 'grey', value: '#62615f' });
    config.colors.push({ title: 'Light Grey', name: 'lightGrey', value: '#dcddd7' });
    config.colors.push({ title: 'Pink', name: 'pink', value: '#cd52bd' });
    config.colors.push({ title: 'Red', name: 'red', value: '#9a0000' });
    config.colors.push({ title: 'Yellow', name: 'yellow', value: '#f0ac28' });
    config.colors.push({ title: 'Green', name: 'green', value: '#6bb343' });
    config.colors.push({ title: 'Blue', name: 'blue', value: '#3c8bc8' });
    config.colors.push({ title: 'Purple', name: 'purple', value: '#a952cd' });

    config.icons = {
        code: 'fa fa-code',
        pre: 'fa fa-file-code-o',
        blockquote: 'fa fa-quote-left',
        bold: 'fa fa-bold',
        italic: 'fa fa-italic',
        underline: 'fa fa-underline',
        strikethrough: 'fa fa-strikethrough',
        header: 'fa fa-header',
        image: 'fa fa-image',
        alignLeft: 'fa fa-align-left',
        alignCenter: 'fa fa-align-center',
        alignRight: 'fa fa-align-right',
        alignJustify: 'fa fa-align-justify',
        indent: 'fa fa-indent',
        outdent: 'fa fa-outdent',
        link: 'fa fa-link',
        unorderedList: 'fa fa-list-ul',
        orderedList: 'fa fa-list-ol'
    };

    config.cssClasses = {
        toGutentypify: 'gutentyp-ify',
        gutentypified: 'gutentyp-ified',
        hasEvents: 'has-events',
        hasToolbar: 'has-toolbar',
        hasComponents: 'has-components',
        editor: 'gutentyp-editor',
        textarea: 'gutentyp-textarea',
        toolbar: 'gutentyp-toolbar',
        toolbarBtn: 'gutentyp-toolbar-btn',
        toolbarBtnText: 'gutentyp-toolbar-btn-text',
        toolbarBtnIcon: 'gutentyp-toolbar-btn-icon',
        hidden: 'gutentyp-hidden'
    };

    config.autoCreateSelectors = function () {
        var i;

        config.selectors = {};

        for (i in config.cssClasses) {
            if (config.cssClasses.hasOwnProperty(i)) {
                config.selectors[i] = '.' + config.cssClasses[i];
            }
        }

        config.selectors.newEditors = config.selectors.editor + ':not(' + config.selectors.hasToolbar + ')';
        config.selectors.eventlessEditors = config.selectors.editor + ':not(' + config.selectors.hasEvents + ')';
        config.selectors.newToolbars = config.selectors.toolbar + ':not(' + config.selectors.hasComponents + ')';
    };

    config.autoCreateSelectors();

    return config;

}});
<|endoftext|>


<commit_before>'use strict';

var Logger = require('logb').getLogger(module.filename);
var ObjectID = require('bson-objectid');
var utils = require('./utils');
var ConnectionPool = require('@bitliner/connection-pool');

var Parser = {
	parseQuery: function(req) {
		var query;
		var id;

		query = req.query.rawQuery;
		id = (req.params.id) ? new ObjectID(req.params.id) : null;

		// query is in the URL
		if (query && query !== '' && query !== 'null') {
			query = JSON.parse(query);
		}

		// query is int he body
		if (!query) {
			query = req.body.query;
		}
		// if there is not query
		if (!query) {
			query = {};
		}

		query = utils.unescapeMongoDbModifiers(query);
		if (id) {
			query._id = id;
		}

		return query;

	},
	parseOptions: function(req) {
		var newOptions;

		var options = {
			new: true,
			upsert: false,
			multi: true
		};

		newOptions = req.body.options;

		if (newOptions) {
			options = utils.mergeRecursive(options, newOptions);
		}
		return options;

	},
	parseUpdate: function(req) {
		var update;
		var $set, $addToSet, $pull, $push;

		update = req.body.update || {};

		update = utils.unescapeMongoDbModifiers(update);
		$set = update.$set;
		$addToSet = update.$addToSet;
		$push = update.$push;
		$pull = update.$pull;

		if (!$set && !$addToSet && !$push && !$pull) {
			delete update._id;
		}

		return update;
	}
};

module.exports.getPutHttpHandler = function(opts) {

	return function(req, res) {
		var updateOne;

		updateOne = req.params.id ? true : false;

		if (!req.body) {
			return res.status(400).json({
				message: 'The request could not be understood by the server. Request body is missing'
			});
		}

		var query;
		var update;
		var options;

		query = Parser.parseQuery(req);
		update = Parser.parseUpdate(req);
		options = Parser.parseOptions(req);

		Logger.info('Running PUT', 'query', query, 'update', update, 'options', options);

		ConnectionPool.getDb(opts, function(err, db) {
			if (!err) {
				db.collection(req.params.collection, function(err, collection) {
					if (updateOne) {
						return collection.findAndModify(query, [], update, {}, {
							new: true,
							upsert: false
						}, function(err) {
							if (err) {
								Logger.error('Error, PUT', err);
								return res.json(500, err);
							}
							res.status(200).end();
						});
					} else {
						return collection.update(query, update, {
							upsert: false,
							multi: true
						}, function(err, numberOfDocs) {
							if (err) {
								Logger.error('Error, PUT', err);
								return res.status(500).json(err);
							}
							res.status(200).json(numberOfDocs);
							// If you want to return the documents uncomment these lines
							/*collection.find(spec).toArray(function(err, docs) {
								if (err) {
									Logger.error('Error, PUT', err);
									return res.status(500).json(err);
								}
								res.status(200).json(docs);
							});*/
						});
					}
				});
			}
		});
	};
};<commit_msg>+fixed findAndModify specifying options<commit_after>'use strict';

var Logger = require('logb').getLogger(module.filename);
var ObjectID = require('bson-objectid');
var utils = require('./utils');
var ConnectionPool = require('@bitliner/connection-pool');

var Parser = {
	parseQuery: function(req) {
		var query;
		var id;

		query = req.query.rawQuery;
		id = (req.params.id) ? new ObjectID(req.params.id) : null;

		// query is in the URL
		if (query && query !== '' && query !== 'null') {
			query = JSON.parse(query);
		}

		// query is int he body
		if (!query) {
			query = req.body.query;
		}
		// if there is not query
		if (!query) {
			query = {};
		}

		query = utils.unescapeMongoDbModifiers(query);
		if (id) {
			query._id = id;
		}

		return query;

	},
	parseOptions: function(req) {
		var newOptions;

		var options = {
			new: true,
			upsert: false,
			multi: true
		};

		newOptions = req.body.options;

		if (newOptions) {
			options = utils.mergeRecursive(options, newOptions);
		}
		return options;

	},
	parseUpdate: function(req) {
		var update;
		var $set, $addToSet, $pull, $push;

		update = req.body.update || {};

		update = utils.unescapeMongoDbModifiers(update);
		$set = update.$set;
		$addToSet = update.$addToSet;
		$push = update.$push;
		$pull = update.$pull;

		if (!$set && !$addToSet && !$push && !$pull) {
			delete update._id;
		}

		return update;
	}
};

module.exports.getPutHttpHandler = function(opts) {

	return function(req, res) {
		var updateOne;

		updateOne = req.params.id ? true : false;

		if (!req.body) {
			return res.status(400).json({
				message: 'The request could not be understood by the server. Request body is missing'
			});
		}

		var query;
		var update;
		var options;

		query = Parser.parseQuery(req);
		update = Parser.parseUpdate(req);
		options = Parser.parseOptions(req);

		Logger.info('Running PUT', 'query', query, 'update', update, 'options', options);

		ConnectionPool.getDb(opts, function(err, db) {
			if (!err) {
				db.collection(req.params.collection, function(err, collection) {
					if (updateOne) {
						return collection.findAndModify(query, [], update, {
							upsert: false,
							new: true
						}, {
							new: true,
							upsert: false
						}, function(err) {
							if (err) {
								Logger.error('Error, PUT', err);
								return res.json(500, err);
							}
							res.status(200).end();
						});
					} else {
						return collection.update(query, update, {
							upsert: false,
							multi: true
						}, function(err, numberOfDocs) {
							if (err) {
								Logger.error('Error, PUT', err);
								return res.status(500).json(err);
							}
							res.status(200).json(numberOfDocs);
							// If you want to return the documents uncomment these lines
							/*collection.find(spec).toArray(function(err, docs) {
								if (err) {
									Logger.error('Error, PUT', err);
									return res.status(500).json(err);
								}
								res.status(200).json(docs);
							});*/
						});
					}
				});
			}
		});
	};
};<|endoftext|>


<commit_before>module.exports = {
    auth: {
        type: {
            Account: 'account',
            Profile: 'profile',
            Role: 'role'
        },
        collection: {
            Account: 'accounts',
            Role: 'roles'
        }
    },
    master: {
        type: {
            Buyer: 'buyer',
            Supplier: 'supplier',
            uom: 'unit-of-measurement',
            Currency: 'currency',
            Vat: 'vat',
            Budget: 'budget',
            Machine: 'machine',
            Uster: 'uster'
        },
        collection: {
            Buyer: 'buyers',
            Supplier: 'suppliers',
            uom: 'unit-of-measurements',
            Product: 'products',
            Machine: 'machines',
            Division: 'divisions',
            Unit: 'units',
            Category: 'categories',
            Currency: 'currencies',
            Vat: 'vats',
            Budget: 'budgets',
            ThreadSpecification : 'thread-specifications',
            UsterClassification: 'uster-classifications',
            LotMachine: 'lot-machines',
            YarnEquivalentConversion: 'yarn-equivalent-conversions',
            Uster: 'usters',
            LampStandard : 'lamp-standards',
            AccountBank : 'account-banks',
            Instruction : 'instructions',
            OrderType : 'order-types',
            ProcessType : 'process-types'
        }
    },
    purchasing: {
        type: {
            PurchaseOrder: 'purchase-order',
            DeliveryOrder: 'delivery-order',
            PurchaseRequest: 'purchase-request',
            UnitPaymentOrder:'unit-payment-order',
        },
        collection: {
            PurchaseOrder: 'purchase-orders',
            PurchaseOrderExternal: 'purchase-order-externals',
            DeliveryOrder: 'delivery-orders',
            UnitReceiptNote: 'unit-receipt-notes',
            PurchaseRequest: 'purchase-requests',
            UnitPaymentCorrectionNote:'unit-payment-correction-notes',
            UnitPaymentOrder:'unit-payment-orders'
        }
    },
    production:{
        spinning : {
            winding : {
                type:{
                    WindingQualitySampling : 'winding-quality-sampling',
                    WindingProductionOutput : 'winding-production-output'
                },
                collection:{
                    WindingQualitySampling : 'winding-quality-samplings',
                    WindingProductionOutput : 'winding-production-outputs'
                }
            },
            type : {
                DailySpinningProductionReport : 'daily-spinning-production-report'
            },
            collection: {
                DailySpinningProductionReport : 'daily-spinning-production-report'
            }
        },
        finishingPrinting :{
            type:{
                SalesContract : 'sales-contract'
            },
            collection:{
                SalesContract : 'sales-contracts'
            }
        }
    }
}
<commit_msg>updating map<commit_after>module.exports = {
    auth: {
        type: {
            Account: 'account',
            Profile: 'profile',
            Role: 'role'
        },
        collection: {
            Account: 'accounts',
            Role: 'roles'
        }
    },
    master: {
        type: {
            Buyer: 'buyer',
            Supplier: 'supplier',
            uom: 'unit-of-measurement',
            Currency: 'currency',
            Vat: 'vat',
            Budget: 'budget',
            Machine: 'machine',
            Uster: 'uster',
            Step : 'step'
        },
        collection: {
            Buyer: 'buyers',
            Supplier: 'suppliers',
            uom: 'unit-of-measurements',
            Product: 'products',
            Machine: 'machines',
            Division: 'divisions',
            Unit: 'units',
            Category: 'categories',
            Currency: 'currencies',
            Vat: 'vats',
            Budget: 'budgets',
            ThreadSpecification : 'thread-specifications',
            UsterClassification: 'uster-classifications',
            LotMachine: 'lot-machines',
            YarnEquivalentConversion: 'yarn-equivalent-conversions',
            Uster: 'usters',
            LampStandard : 'lamp-standards',
            AccountBank : 'account-banks',
            Instruction : 'instructions',
            OrderType : 'order-types',
            ProcessType : 'process-types',
            ColorType : 'color-types',
            Step : 'steps'
        }
    },
    purchasing: {
        type: {
            PurchaseOrder: 'purchase-order',
            DeliveryOrder: 'delivery-order',
            PurchaseRequest: 'purchase-request',
            UnitPaymentOrder:'unit-payment-order',
        },
        collection: {
            PurchaseOrder: 'purchase-orders',
            PurchaseOrderExternal: 'purchase-order-externals',
            DeliveryOrder: 'delivery-orders',
            UnitReceiptNote: 'unit-receipt-notes',
            PurchaseRequest: 'purchase-requests',
            UnitPaymentCorrectionNote:'unit-payment-correction-notes',
            UnitPaymentOrder:'unit-payment-orders'
        }
    },
    production:{
        spinning : {
            winding : {
                type:{
                    WindingQualitySampling : 'winding-quality-sampling',
                    WindingProductionOutput : 'winding-production-output'
                },
                collection:{
                    WindingQualitySampling : 'winding-quality-samplings',
                    WindingProductionOutput : 'winding-production-outputs'
                }
            },
            type : {
                DailySpinningProductionReport : 'daily-spinning-production-report'
            },
            collection: {
                DailySpinningProductionReport : 'daily-spinning-production-report'
            }
        },
        finishingPrinting :{
            type:{
                SalesContract : 'sales-contract',
                DailyOperation : 'daily-operation'
            },
            collection:{
                SalesContract : 'sales-contracts',
                DailyOperation : 'daily-operations'
            }
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

var api_url = 'http://nodejs.org/api/';
var api_type = {
	miscs: true,
	globals: true,
	methods: true,
	vars: true,
	modules: true,
	classes: true
};

function getAPIData (target, cb) {
	if (target in window.localStorage) {
		var data = JSON.parse(window.localStorage[target]);
		cb && cb(data);
	}
	else {
		$.getJSON(api_url + target + '.json', function(data) {
			window.localStorage[target] = JSON.stringify(data);
			cb && cb(data);
		});
	}
}

function printContent (data, level, cb) {
	for (var index in data) {
		if (index in api_type) {
			for(var order in data[index]) {
				var current = data[index][order];

				var div = $('
').attr('class', 'block');
				var header = $('<h' + level + '>')
					.html(current.textRaw.replace('\\', ''))
					.attr('id', null);
				div.append(header);

				var desc = $('
');
				if ('stability' in current) {
					var stability = $('
').html('Stability ' + current.stability +
						': ' + current.stabilityText + '');
					desc.append(stability);
				}
				desc.append(current.desc);
				div.append(desc);

				$('div.content').append(div);

				var item = $('').html(current.textRaw.replace('\\', ''));
				$('div.item').append(item);

				printContent(current, level + 1);
			}
		}
	}

	cb && cb();
}

function selectItem () {
	for (var index = 0;index < $('div.content .block').size();index++) {
		var current = $('div.content .block').eq(index);
		if(current.position().top >= 0) {
			$('div.item span').eq(index).addClass('active_b').siblings().removeClass('active_b');
			return;
		}
	}
}

function contentResize () {
	var content = $('div.content .block').last().css({
		height: $('div.content').height() - 30
	});
}

$(document).ready(function () {
	getAPIData('index', function (data) {
		$.each(data.desc, function (index) {
			var item = data.desc[index];
			if ('text' == item.type) {
				var text = item.text.match(/\[(.+)\]\((.+)\.html\)/);
				$('div.nav').append('' + text[1] + '');
			}
		});

		$('div.nav span').eq(0).click();
	});
});

$('body').delegate('div.nav span', 'click', function () {
	$(this).addClass('active_a').siblings().removeClass('active_a');

	$('div.item').html('');
	$('div.content').html('');
	$('div.content').stop().animate({
		scrollTop: 0
	}, 750);

	getAPIData($(this).attr('class').split(' ')[0], function (data) {
		printContent(data, 1, function () {
			selectItem();
			contentResize();

			for(var index = 0;index < $('div.item span').size();index++) {
				$('div.item span').eq(index).attr('data-order', index);
			}
		});
	});
}).delegate('div.item span', 'click', function () {
	var index = $(this).attr('data-order');
	var moveTo = $('div.content .block').eq(index).position().top - $('div.content .block').eq(0).position().top;

	$('div.content').stop().animate({
		scrollTop: moveTo
	}, 750);
});

$('div.content').on('scroll', function () {
	selectItem();
	contentResize();
});<commit_msg>update<commit_after>'use strict';

var api_url = 'http://nodejs.org/api/';
var api_type = {
	miscs: true,
	globals: true,
	methods: true,
	vars: true,
	modules: true,
	classes: true
};

function getAPIData (target, cb) {
	if (target in window.localStorage) {
		var data = JSON.parse(window.localStorage[target]);
		cb && cb(data);
	}
	else {
		$.getJSON(api_url + target + '.json', function(data) {
			window.localStorage[target] = JSON.stringify(data);
			cb && cb(data);
		});
	}
}

function printContent (data, level, cb) {
	for (var index in data) {
		if (index in api_type) {
			for(var order in data[index]) {
				var current = data[index][order];

				var div = $('
').attr('class', 'block');
				var header = $('<h' + level + '>')
					.html(current.textRaw.replace('\\', ''))
					.attr('id', null);
				div.append(header);

				var desc = $('
');
				if ('stability' in current) {
					var stability = $('
').html('Stability ' + current.stability +
						': ' + current.stabilityText + '');
					desc.append(stability);
				}
				desc.append(current.desc);
				div.append(desc);

				$('div.content').append(div);

				var item = $('').html(current.textRaw.replace('\\', ''));
				$('div.item').append(item);

				printContent(current, level + 1);
			}
		}
	}

	cb && cb();
}

function selectItem () {
	for (var index = 0;index < $('div.content .block').size();index++) {
		var current = $('div.content .block').eq(index);
		if(current.position().top >= 0) {
			$('div.item span').eq(index).addClass('active_b').siblings().removeClass('active_b');
			return;
		}
	}
}

function contentResize () {
	if ($('div.content .block').last().height() < $('div.content').height()) {
		var content = $('div.content .block').last().css({
			height: $('div.content').height() - 30
		});
	}
}

$(document).ready(function () {
	getAPIData('index', function (data) {
		$.each(data.desc, function (index) {
			var item = data.desc[index];
			if ('text' == item.type) {
				var text = item.text.match(/\[(.+)\]\((.+)\.html\)/);
				$('div.nav').append('' + text[1] + '');
			}
		});

		$('div.nav span').eq(0).click();
	});
});

$('body').delegate('div.nav span', 'click', function () {
	$(this).addClass('active_a').siblings().removeClass('active_a');

	$('div.item').html('');
	$('div.content').html('');
	$('div.content').stop().animate({
		scrollTop: 0
	}, 750);

	getAPIData($(this).attr('class').split(' ')[0], function (data) {
		printContent(data, 1, function () {
			selectItem();
			contentResize();

			for(var index = 0;index < $('div.item span').size();index++) {
				$('div.item span').eq(index).attr('data-order', index);
			}
		});
	});
}).delegate('div.item span', 'click', function () {
	var index = $(this).attr('data-order');
	var moveTo = $('div.content .block').eq(index).position().top - $('div.content .block').eq(0).position().top;

	$('div.content').stop().animate({
		scrollTop: moveTo
	}, 750);
});

$('div.content').on('scroll', function () {
	selectItem();
	contentResize();
});<|endoftext|>


<commit_before>var fs = require('fs');
var util = require('util');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var exists = fs.exists || path.exists;

var pwmpath = '/sys/class/pwm';

var getChipPath = function(chipNum) {
    return pwmpath + '/pwmchip' + chipNum;
};
var getPinPath = function(chipNum, pinNum) {
    return getChipPath(chipNum) + '/pwm' + pinNum;
};

var logError = function(e) { if (e) console.log(e.code, e.action, e.path); };
var logMessage = function() { if (exports.logging) console.log.apply(console, arguments) };

var _write = function(str, file, fn, override) {
    if (typeof fn !== "function") fn = logError;
    fs.writeFile(file, str, function(err) {
	if (err && !override) {
	    err.path = file;
	    err.action = 'write';
	    logError(err);
	} else {
	    if (typeof fn === "function") fn();
	}
    });
};
var _read = function(file, fn) {
    fs.readFile(file, "utf-8", function(err, data) {
	if (err) {
	    err.path = file;
	    err.action = 'read';
	    logError(err);
	} else {
	    if (typeof fn === "function") fn(data);
	    else logMessage("value: ", data);
	}
    });
};

var _unexport = function(chipNum, pinNum, fn) {
    _write(pinNum, getChipPath(chipNum) + '/unexport', function(err) {
	if (err) return logError(err);
	if (typeof fn === 'function') fn();
    }, 1);
};
var _export = function(chipNum, pinNum, fn) {
    if (exists(getPinPath(chipNum, pinNum))) {
	// already exported, unexport and export again
	logMessage('Header already exported');
	_unexport(chipNum, pinNum, function() { _export(chipNum, pinNum, fn); });
    } else {
	logMessage('Exporting pwm' + pinNum);
	_write(pinNum, getChipPath(chipNum) + '/export', function(err) {
	    // if there's an error when exporting, unexport and repeat
	    if (err) _unexport(chipNum, pinNum, function() { _export(chipNum, pinNum, fn); });
	    else if (typeof fn === 'function') fn();
	}, 1);
    }
};

// fs.watch doesn't get fired because the file never
// gets 'accessed' when setting header via hardware
// manually watching value changes
var FileWatcher = function(path, interval, fn) {
    if (typeof fn === 'undefined') {
	fn = interval;
	interval = 100;
    }
    if (typeof interval !== 'number') return false;
    if (typeof fn !== 'function') return false;

    var value;
    var readTimer = setInterval(function() {
	_read(path, function(val) {
	    if (value !== val) {
		if (typeof value !== 'undefined') fn(val);
		value = val;
	    }
	});
    }, interval);

    this.stop = function() { clearInterval(readTimer); };
};

var PWM = function(chipNum, pinNum, fn) {
    this.chipNum = chipNum;
    this.pinNum = pinNum;

    this.cache = {};
    this.ready = false

    this.PATH = {};
    this.PATH.PIN        = pwmpath + '/pwmchip' + this.chipNum + '/pwm' + this.pinNum;
    this.PATH.DUTY_CYCLE = this.PATH.PIN + '/duty_cycle';
    this.PATH.ENABLE     = this.PATH.PIN + '/enable';
    this.PATH.PERIOD     = this.PATH.PIN + '/period';

    this.export(this.chipNum, this.pinNum, function() {
        this.ready = true;
        if (typeof fn === "function") fn();
        for (var i in this.cache.value) {
            this._set(i, this.cache[i].value, this.cache[i].callback);
        }
    }.bind(this));
};

util.inherits(PWM, EventEmitter);

/**
 * Export and unexport gpio#, takes callback which fires when operation is completed
 */
PWM.prototype.export = function(fn) { _export(this.headerNum, fn); };
PWM.prototype.unexport = function(fn) {
    if (this.valueWatcher) this.valueWatcher.stop();
    _unexport(this.headerNum, fn);
};

/**
 * Gets/Sets enable
 */
PWM.prototype.getEnable = function(callback) {
    this._get(this.PATH.ENABLE, callback);
};
PWM.prototype.setEnable = function(value, callback) {
    this._set(this.PATH.ENABLE, value, callback);
};

/**
 * Gets/Sets period
 */
PWM.prototype.getPeriod = function(callback) {
    this._get(this.PATH.PERIOD, callback);
};
PWM.prototype.setPeriod = function(value, callback) {
    this._set(this.PATH.PERIOD, value, callback);
};

/**
 * Gets/Sets duty cycle
 */
PWM.prototype.getDutyCycle = function(callback) {
    this._get(this.PATH.DUTY_CYCLE, callback);
};
PWM.prototype.setDutyCycle = function(value, callback) {
    this._set(this.PATH.DUTY_CYCLE, value, callback);
};

/**
 * Internal getter/setter
 */
PWM.prototype._get = function(path, fn) {
    if (!this.ready) {
        if (typeof fn === "function") fn.call(this, undefined);
        return;
    }

    _read(path, function(val) {
	val = parseInt(val, 10);
	if (val !== currVal) {
	    if (typeof fn === "function") fn.call(this, val);
	}
    }.bind(this));
};

PWM.prototype._set = function(path, value, callback) {
    if (!this.ready) {
        this.cache[path] = {
            value: value,
            callback: callback,
        };
        return;
    }

    _write(v, path, function() {
	this.emit('valueChange', v);
	this.emit('change', v);
	if (typeof callback === 'function') callback();
    }.bind(this));
};

PWM.prototype.reset = function() {
    for (var i in this.PATH) {
        this._set(this.PATH[i], 0);
    }
};

exports.logging = false;
exports.export = function(chipNum, pinNum, fn) { return new PWM(chipNum, pinNum, fn); };
exports.unexport = _unexport;
<commit_msg>rework exporting calls<commit_after>var fs = require('fs');
var util = require('util');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var exists = fs.exists || path.exists;

var pwmpath = '/sys/class/pwm';

var getChipPath = function(chipNum) {
    return pwmpath + '/pwmchip' + chipNum;
};
var getPinPath = function(chipNum, pinNum) {
    return getChipPath(chipNum) + '/pwm' + pinNum;
};

var logError = function(e) { if (e) console.log(e.code, e.action, e.path); };
var logMessage = function() { if (exports.logging) console.log.apply(console, arguments) };

var _write = function(str, file, fn, override) {
    if (typeof fn !== "function") fn = logError;
    fs.writeFile(file, str, function(err) {
	if (err && !override) {
	    err.path = file;
	    err.action = 'write';
	    logError(err);
	} else {
	    if (typeof fn === "function") fn();
	}
    });
};
var _read = function(file, fn) {
    fs.readFile(file, "utf-8", function(err, data) {
	if (err) {
	    err.path = file;
	    err.action = 'read';
	    logError(err);
	} else {
	    if (typeof fn === "function") fn(data);
	    else logMessage("value: ", data);
	}
    });
};

var _unexport = function(chipNum, pinNum, fn) {
    _write(pinNum, getChipPath(chipNum) + '/unexport', function(err) {
	if (err) return logError(err);
	if (typeof fn === 'function') fn();
    }, 1);
};
var _export = function(chipNum, pinNum, fn) {
    if (exists(getPinPath(chipNum, pinNum))) {
	// already exported, unexport and export again
	logMessage('Header already exported');
	_unexport(chipNum, pinNum, function() { _export(chipNum, pinNum, fn); });
    } else {
	logMessage('Exporting pwm' + pinNum);
	_write(pinNum, getChipPath(chipNum) + '/export', function(err) {
	    // if there's an error when exporting, unexport and repeat
	    if (err) _unexport(chipNum, pinNum, function() { _export(chipNum, pinNum, fn); });
	    else if (typeof fn === 'function') fn();
	}, 1);
    }
};

// fs.watch doesn't get fired because the file never
// gets 'accessed' when setting header via hardware
// manually watching value changes
var FileWatcher = function(path, interval, fn) {
    if (typeof fn === 'undefined') {
	fn = interval;
	interval = 100;
    }
    if (typeof interval !== 'number') return false;
    if (typeof fn !== 'function') return false;

    var value;
    var readTimer = setInterval(function() {
	_read(path, function(val) {
	    if (value !== val) {
		if (typeof value !== 'undefined') fn(val);
		value = val;
	    }
	});
    }, interval);

    this.stop = function() { clearInterval(readTimer); };
};

var PWM = function(chipNum, pinNum) {
    this.chipNum = chipNum;
    this.pinNum = pinNum;

    this.cache = {};
    this.ready = false

    this.PATH = {};
    this.PATH.PIN        = pwmpath + '/pwmchip' + this.chipNum + '/pwm' + this.pinNum;
    this.PATH.DUTY_CYCLE = this.PATH.PIN + '/duty_cycle';
    this.PATH.ENABLE     = this.PATH.PIN + '/enable';
    this.PATH.PERIOD     = this.PATH.PIN + '/period';
};

util.inherits(PWM, EventEmitter);

/**
 * Export and unexport gpio#, takes callback which fires when operation is completed
 */
PWM.prototype.export = function(fn) {
    _export(this.chipNum, this.pinNum, function() {
        this.ready = true;
        if (typeof fn === "function") fn();
        for (var i in this.cache.value) {
            this._set(i, this.cache[i].value, this.cache[i].callback);
        }
    }.bind(this));
};
PWM.prototype.unexport = function(fn) {
    if (this.valueWatcher) this.valueWatcher.stop();
    _unexport(this.headerNum, fn);
};

/**
 * Gets/Sets enable
 */
PWM.prototype.getEnable = function(callback) {
    this._get(this.PATH.ENABLE, callback);
};
PWM.prototype.setEnable = function(value, callback) {
    this._set(this.PATH.ENABLE, value, callback);
};

/**
 * Gets/Sets period
 */
PWM.prototype.getPeriod = function(callback) {
    this._get(this.PATH.PERIOD, callback);
};
PWM.prototype.setPeriod = function(value, callback) {
    this._set(this.PATH.PERIOD, value, callback);
};

/**
 * Gets/Sets duty cycle
 */
PWM.prototype.getDutyCycle = function(callback) {
    this._get(this.PATH.DUTY_CYCLE, callback);
};
PWM.prototype.setDutyCycle = function(value, callback) {
    this._set(this.PATH.DUTY_CYCLE, value, callback);
};

/**
 * Internal getter/setter
 */
PWM.prototype._get = function(path, fn) {
    if (!this.ready) {
        if (typeof fn === "function") fn.call(this, undefined);
        return;
    }

    _read(path, function(val) {
	val = parseInt(val, 10);
	if (val !== currVal) {
	    if (typeof fn === "function") fn.call(this, val);
	}
    }.bind(this));
};

PWM.prototype._set = function(path, value, callback) {
    if (!this.ready) {
        this.cache[path] = {
            value: value,
            callback: callback,
        };
        return;
    }

    _write(v, path, function() {
	this.emit('valueChange', v);
	this.emit('change', v);
	if (typeof callback === 'function') callback();
    }.bind(this));
};

PWM.prototype.reset = function() {
    for (var i in this.PATH) {
        this._set(this.PATH[i], 0);
    }
};

exports.logging = true;
exports.export = function(chipNum, pinNum, fn) {
    var pwm = new PWM(chipNum, pinNum);
    pwm.export(fn);
    return pwm;
};
exports.unexport = _unexport;
<|endoftext|>


<commit_before>var async = require("async");
var winston = require("winston");
var debug = require("debug")("lego");
var Brick = require("./brick");
var _ = require("underscore");
var domain = require("domain");
var util = require("util");

var Lego = function (options) {
    //each time pipe calls , add an item
    this._chain = [];

    //start params
    this.params = {};

    //options
    this.options = _.extend({
        timeout: 0       //timeout for each brick, default 0 , no timeout control
    }, options || {});

    this.propertyQueue = [];

};

Lego.prototype.start = function (params) {
    this.params = params || {};
    return this;
};

/**
 *
 * parallel handle bricks
 *
 * */
Lego.prototype.pipe = function () {
    var args = Array.prototype.slice.call(arguments, 0);
    var self = this;

    if (!args.length) {
        winston.error("Lego.combo none bricks provide");
        throw new Error("function Lego.pipe : Bricks must provide");
    }

    this._chain.push(function (finish) {
        //parallel call
        var tasks = {};

        args.forEach(function (ModuleBrick) {
            var brick = new ModuleBrick(self);

            //以Brick的名字命名
            tasks[ModuleBrick.Name] = function (cb) {
                brick.handle(self.params, function (status, data) {
                    debug("brick handle finish , status=" + status + ",data=" + JSON.stringify(data || {}));
                    if (status == Brick.SUCCESS) {
                        cb(null, data);
                    } else {
                        cb(null, null);
                    }
                });
            }
        });

        async.parallel(tasks, function (err, results) {
            /**
             * results 会变成 {
             *      BrickName1: xxx,
             *      BrickName2: xxx
             * }
             * 所以当2个名字一样的Brick在同一个Lego中使用的时候会出现覆盖的情况
             *
             * */

                //和params合并， 传给下一个pipe
            finish(null, _.extend(self.params, results));
        });
    });

    return this;
};

Lego.prototype.done = function (cb) {
    if (!cb) {
        //只warning一下
        winston.warn("Lego.done need a callback function");
    }
    var self = this;
    if (this._chain.length) {
        async.waterfall(this._chain, function (err, result) {
            //clear chain
            self._chain = [];
            cb && cb.call(self, result);
        });
    } else {
        cb && cb.call(self, self.params);
    }
    return this;
};

//TODO
/**
 * 在一次pipe的全部Brick处理完以后，提供此函数，可以把部分数据提到data的顶层，
 * 方便后续pipe的模块依赖顶层的数据，而不是Brick返回的内部数据
 *
 * @param brick {Brick|String}
 * @param property{String}
 * @param toProperty{String}
 * */
Lego.prototype.top = function (brick, property, toProperty) {
    if (typeof  brick == "String") {
        //Name of brick , try find by name
        brick = Brick.name(brick);
    }

    if (!brick || !brick.prototype instanceof(Brick)) {
        winston.error("Lego.top param brick must be a Brick");
        return this;
    }

    if (typeof  property != "String" || typeof  toProperty != "String") {
        winston.error("Lego.top param property,toProperty must be String");
        return this;
    }

    //add to Queue
    this.propertyQueue.push({
        brick: brick,
        property: property,
        toProperty: toProperty
    });

    return this;
};

var transProperty = function (from, to, fromProperty, toProperty) {
    function query(obj, propStr) {
        var props = propStr.split(".");
        var propName;
        while (obj && (propName = props.unshift())) {
            obj = obj[propName] || null;
        }
        return obj;
    }

    function build(obj, propStr, data) {
        var target = obj || {};
        var props = propStr.split(".");
        var propName;
        var i = 0;
        while (i++ < props.length - 1 && (propName = props.unshift())) {
            if (!target[propName] || !util.isObject(target[propName])) {
                target[propName] = {};
            }
            target = target[propName];
        }
        target[props[props.length - 1]] = data;
    }

    build(to, toProperty, query(from, fromProperty) || null);
};

module.exports = Lego;
Lego.Brick = Brick;
Lego._transProperty = transProperty;<commit_msg>trans property<commit_after>var async = require("async");
var winston = require("winston");
var debug = require("debug")("lego");
var Brick = require("./brick");
var _ = require("underscore");
var domain = require("domain");
var util = require("util");

var Lego = function (options) {
    //each time pipe calls , add an item
    this._chain = [];

    //start params
    this.params = {};

    //options
    this.options = _.extend({
        timeout: 0       //timeout for each brick, default 0 , no timeout control
    }, options || {});

    this.propertyQueue = [];

};

Lego.prototype.start = function (params) {
    this.params = params || {};
    return this;
};

/**
 *
 * parallel handle bricks
 *
 * */
Lego.prototype.pipe = function () {
    var args = Array.prototype.slice.call(arguments, 0);
    var self = this;

    if (!args.length) {
        winston.error("Lego.combo none bricks provide");
        throw new Error("function Lego.pipe : Bricks must provide");
    }

    this._chain.push(function (finish) {
        //parallel call
        var tasks = {};

        args.forEach(function (ModuleBrick) {
            var brick = new ModuleBrick(self);

            //以Brick的名字命名
            tasks[ModuleBrick.Name] = function (cb) {
                brick.handle(self.params, function (status, data) {
                    debug("brick handle finish , status=" + status + ",data=" + JSON.stringify(data || {}));
                    if (status == Brick.SUCCESS) {
                        //find transProperties
                        self.propertyQueue.forEach(function (trans) {
                            if (trans.brick instanceof ModuleBrick) {
                                transProperty(data, self.params, trans.prototype, t.toProperty);
                            }
                        });
                        cb(null, data);
                    } else {
                        cb(null, null);
                    }
                });
            }
        });

        async.parallel(tasks, function (err, results) {
            /**
             * results 会变成 {
             *      BrickName1: xxx,
             *      BrickName2: xxx
             * }
             * 所以当2个名字一样的Brick在同一个Lego中使用的时候会出现覆盖的情况
             *
             * */

                //和params合并， 传给下一个pipe
            finish(null, _.extend(self.params, results));
        });
    });

    return this;
};

Lego.prototype.done = function (cb) {
    if (!cb) {
        //只warning一下
        winston.warn("Lego.done need a callback function");
    }
    var self = this;
    if (this._chain.length) {
        async.waterfall(this._chain, function (err, result) {
            //clear chain
            self._chain = [];
            cb && cb.call(self, result);
        });
    } else {
        cb && cb.call(self, self.params);
    }
    return this;
};

//TODO
/**
 * 在一次pipe的全部Brick处理完以后，提供此函数，可以把部分数据提到data的顶层，
 * 方便后续pipe的模块依赖顶层的数据，而不是Brick返回的内部数据
 *
 * @param brick {Brick|String}
 * @param property{String}
 * @param toProperty{String}
 * */
Lego.prototype.top = function (brick, property, toProperty) {
    if (typeof  brick == "String") {
        //Name of brick , try find by name
        brick = Brick.name(brick);
    }

    if (!brick || !brick.prototype instanceof(Brick)) {
        winston.error("Lego.top param brick must be a Brick");
        return this;
    }

    if (typeof  property != "String" || typeof  toProperty != "String") {
        winston.error("Lego.top param property,toProperty must be String");
        return this;
    }

    //add to Queue
    this.propertyQueue.push({
        brick: brick,
        property: property,
        toProperty: toProperty
    });

    return this;
};

var transProperty = function (from, to, fromProperty, toProperty) {
    function query(obj, propStr) {
        var props = propStr.split(".");
        var propName;
        while (obj && (propName = props.unshift())) {
            obj = obj[propName] || null;
        }
        return obj;
    }

    function build(obj, propStr, data) {
        var target = obj || {};
        var props = propStr.split(".");
        var propName;
        var i = 0;
        while (i++ < props.length - 1 && (propName = props.unshift())) {
            if (!target[propName] || !util.isObject(target[propName])) {
                target[propName] = {};
            }
            target = target[propName];
        }
        target[props[props.length - 1]] = data;
    }

    build(to, toProperty, query(from, fromProperty) || null);
};

module.exports = Lego;
Lego.Brick = Brick;
Lego._transProperty = transProperty;<|endoftext|>


<commit_before>var emulabeller = (function () {
    'use strict';

    // autoload wav file and TextGrid for testing
    // will only work if running on server...
    var autoLoad = true;

    var tierInfos = {"tiers": [],  "canvases": []};

    var osciCanvas = document.querySelector('#wave');
    var specCanvas = document.querySelector('#spectrogram');
    var scrollCanvas = document.querySelector('#scrollbar');
    var draggableBar = document.querySelector('#resizer');
    var timeline = document.querySelector('#timeline');
    var tiers = document.querySelector('#tiers');
    var fileSelect = document.querySelector('#fileSelect');
    var showLeftPush = document.getElementById('serverSelect');
    var labeller = Object.create(EmuLabeller);

    labeller.init({
        osciCanvas: osciCanvas,
        specCanvas: specCanvas,
        scrollCanvas: scrollCanvas,
        waveColor: 'white',
        progressColor: 'grey',
        loadingColor: 'purple',
        cursorColor: 'red',
        tierInfos: tierInfos,
        draggableBar : draggableBar,
        timeline : timeline,
        tiers : tiers,
        fileSelect : fileSelect,
        showLeftPush : showLeftPush,
        internalCanvasWidth : '2048',      // in pixel
        internalCanvasHeightSmall : '128',  // in pixel -> Cans
        internalCanvasHeightBig : '64',   // in pixel -> Wave & Spectro
        mode: 'server'                     // or standalone
    });

    // see if on iPad... if so preload data... just for testing
    var isiPad = navigator.userAgent.match(/iPad/i) !== null;
     if(isiPad || autoLoad){
        labeller.load('data/msajc003.wav');
        labeller.iohandler.xhrLoad('data/msajc003.TextGrid', 3);
     }

	// initial  launch

    $('#fileGetterBtn')[0].addEventListener('change', labeller.fileAPIread, false);

    // hack for hiding inputs of dialogs.. SIC!!!
    $("#dialog-messageSh").hide();
    $("#dialog-messageSetLabel").hide();
    $('#specSettings').click(function() {
        var isOpen = $('#specDialog').dialog('isOpen');
        if(!isOpen) {
            $('#specDialog').dialog('open');
            $("#specDialog").dialog('moveToTop');
            isOpen = true;
        }
        else {
            $('#specDialog').dialog('close');
            isOpen = false;
        }
    });
    $("#specDialog").dialog({
        bgiframe: true,
        autoOpen: false,
        width: 500,
        closeOnEscape: true,
        show: 'fade',
        hide: 'fade',
        position: 'center',
        stack: false,
        buttons: {
            OK: function() {
                var signalline = document.querySelector('#hero');
                var nN = $("#windowLength").val();
                var nvrf = $("#viewrange_from").val();
                var nvrt = $("#viewrange_to").val();
                var ndr = $("#dynamicRange").val();
                var nwf = $("#windowFunction").val();
                //var newSpectroHeight = $("#spectroHeight").val();
                if(isNaN(nN) || isNaN(nvrf) || isNaN(nvrt)|| isNaN(ndr)) {
                    alert("Please enter valid numbers !");
                }
                else {

                    //canvas.style.height = newSpectroHeight+"px";
                    //specCanvas.style.height = newSpectroHeight+"px";
                    //signalline.style.marginTop = ((2*newSpectroHeight)+20)+"px";

                    labeller.spectogramDrawer.N = parseInt(nN,10);
                    labeller.spectogramDrawer.freq = parseInt(nvrt,10);
                    labeller.spectogramDrawer.freq_lower = parseInt(nvrf,10);
                    labeller.spectogramDrawer.dynRangeInDB = parseInt(ndr,10);
                    labeller.spectogramDrawer.windowFunction = parseInt(nwf,10);
                    labeller.spectogramDrawer.clearImageCache();
                    labeller.spectogramDrawer.killSpectroRenderingThread();
                    labeller.spectogramDrawer.drawImage(labeller.backend.currentBuffer,labeller.viewPort);
                    labeller.spectogramDrawer.progress(labeller.backend.getPlayedPercents(), labeller.viewPort, labeller.backend.currentBuffer.length);
                    $(this).dialog('close');
                }

            },
            Cancel: function() {
                $(this).dialog('close');
            }
         }
    });

    // event redirect for Open File Button
    document.querySelector('#fileSelect').addEventListener('click', function(e) {
            // Use the native click() of the file input.
            document.querySelector('#fileGetterBtn').click();
        },
    false);

    document.addEventListener('keyup', function (e) {
        // spacebar
        if(!emulabeller.isModalShowing && emulabeller.internalMode == labeller.EDITMODE.LABEL_RENAME) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (27 == code) {
                emulabeller.saveCanvasDoubleClick();
                emulabeller.removeCanvasDoubleClick();
            }
        }
    });

    // keypress bindings
    document.addEventListener('keypress', function (e) {
        // spacebar

        if(!emulabeller.isModalShowing && emulabeller.internalMode != labeller.EDITMODE.LABEL_RENAME){

            if (32 == e.keyCode) {
                // SPACEBAR -> play what is in view
                e.preventDefault();
                emulabeller.playPauseInView();
            }
            if (114 == e.keyCode) {
                // R key -> play sel
                emulabeller.playInMode("sel");
            }
            if (102 == e.keyCode) {
                // F key -> play entire file
                emulabeller.playInMode("all");
            }
            if (119 == e.keyCode){
                // W key -> zoom in
                emulabeller.zoomViewPort(1);
            }
            if (115 == e.keyCode){
                // S key -> zoom out
                emulabeller.zoomViewPort(0);
            }
            if (100 == e.keyCode){
                // D key -> shift right
                emulabeller.shiftViewP(1);
            }
            if (97 == e.keyCode){
                // A key -> shift left
                emulabeller.shiftViewP(0);
            }
            if (113 == e.keyCode){
                // Q key -> view all
                emulabeller.setView(-Infinity, Infinity);
            }
            if (101 == e.keyCode){
                // E key -> zoom in to selected segment
                emulabeller.zoomSel();
            }
            if (111 == e.keyCode){
                // O key
                if(emulabeller.externalMode==labeller.USAGEMODE.STANDALONE)
                 $('#fileGetterBtn').click();
                if(emulabeller.externalMode==labeller.USAGEMODE.SERVER)
                 emulabeller.openSubmenu();
            }
            if (99 == e.keyCode){
                // C key
                emulabeller.editLabel();
            }
            if (116 == e.keyCode){
                // T key
                emulabeller.moveSelTierToTop();
            }
            if (13 == e.keyCode){
                // ENTER key
                emulabeller.addSegmentAtSelection();
            }
            console.log(e.keyCode);
        }
    });

    return labeller;
}());
<commit_msg>ESC doesnt save label<commit_after>var emulabeller = (function () {
    'use strict';

    // autoload wav file and TextGrid for testing
    // will only work if running on server...
    var autoLoad = true;

    var tierInfos = {"tiers": [],  "canvases": []};

    var osciCanvas = document.querySelector('#wave');
    var specCanvas = document.querySelector('#spectrogram');
    var scrollCanvas = document.querySelector('#scrollbar');
    var draggableBar = document.querySelector('#resizer');
    var timeline = document.querySelector('#timeline');
    var tiers = document.querySelector('#tiers');
    var fileSelect = document.querySelector('#fileSelect');
    var showLeftPush = document.getElementById('serverSelect');
    var labeller = Object.create(EmuLabeller);

    labeller.init({
        osciCanvas: osciCanvas,
        specCanvas: specCanvas,
        scrollCanvas: scrollCanvas,
        waveColor: 'white',
        progressColor: 'grey',
        loadingColor: 'purple',
        cursorColor: 'red',
        tierInfos: tierInfos,
        draggableBar : draggableBar,
        timeline : timeline,
        tiers : tiers,
        fileSelect : fileSelect,
        showLeftPush : showLeftPush,
        internalCanvasWidth : '2048',      // in pixel
        internalCanvasHeightSmall : '128',  // in pixel -> Cans
        internalCanvasHeightBig : '64',   // in pixel -> Wave & Spectro
        mode: 'server'                     // or standalone
    });

    // see if on iPad... if so preload data... just for testing
    var isiPad = navigator.userAgent.match(/iPad/i) !== null;
     if(isiPad || autoLoad){
        labeller.load('data/msajc003.wav');
        labeller.iohandler.xhrLoad('data/msajc003.TextGrid', 3);
     }

	// initial  launch

    $('#fileGetterBtn')[0].addEventListener('change', labeller.fileAPIread, false);

    // hack for hiding inputs of dialogs.. SIC!!!
    $("#dialog-messageSh").hide();
    $("#dialog-messageSetLabel").hide();
    $('#specSettings').click(function() {
        var isOpen = $('#specDialog').dialog('isOpen');
        if(!isOpen) {
            $('#specDialog').dialog('open');
            $("#specDialog").dialog('moveToTop');
            isOpen = true;
        }
        else {
            $('#specDialog').dialog('close');
            isOpen = false;
        }
    });
    $("#specDialog").dialog({
        bgiframe: true,
        autoOpen: false,
        width: 500,
        closeOnEscape: true,
        show: 'fade',
        hide: 'fade',
        position: 'center',
        stack: false,
        buttons: {
            OK: function() {
                var signalline = document.querySelector('#hero');
                var nN = $("#windowLength").val();
                var nvrf = $("#viewrange_from").val();
                var nvrt = $("#viewrange_to").val();
                var ndr = $("#dynamicRange").val();
                var nwf = $("#windowFunction").val();
                //var newSpectroHeight = $("#spectroHeight").val();
                if(isNaN(nN) || isNaN(nvrf) || isNaN(nvrt)|| isNaN(ndr)) {
                    alert("Please enter valid numbers !");
                }
                else {

                    //canvas.style.height = newSpectroHeight+"px";
                    //specCanvas.style.height = newSpectroHeight+"px";
                    //signalline.style.marginTop = ((2*newSpectroHeight)+20)+"px";

                    labeller.spectogramDrawer.N = parseInt(nN,10);
                    labeller.spectogramDrawer.freq = parseInt(nvrt,10);
                    labeller.spectogramDrawer.freq_lower = parseInt(nvrf,10);
                    labeller.spectogramDrawer.dynRangeInDB = parseInt(ndr,10);
                    labeller.spectogramDrawer.windowFunction = parseInt(nwf,10);
                    labeller.spectogramDrawer.clearImageCache();
                    labeller.spectogramDrawer.killSpectroRenderingThread();
                    labeller.spectogramDrawer.drawImage(labeller.backend.currentBuffer,labeller.viewPort);
                    labeller.spectogramDrawer.progress(labeller.backend.getPlayedPercents(), labeller.viewPort, labeller.backend.currentBuffer.length);
                    $(this).dialog('close');
                }

            },
            Cancel: function() {
                $(this).dialog('close');
            }
         }
    });

    // event redirect for Open File Button
    document.querySelector('#fileSelect').addEventListener('click', function(e) {
            // Use the native click() of the file input.
            document.querySelector('#fileGetterBtn').click();
        },
    false);

    document.addEventListener('keyup', function (e) {
        // spacebar
        if(!emulabeller.isModalShowing && emulabeller.internalMode == labeller.EDITMODE.LABEL_RENAME) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (27 == code) {
                emulabeller.removeCanvasDoubleClick();
            }
        }
    });

    // keypress bindings
    document.addEventListener('keypress', function (e) {
        // spacebar

        if(!emulabeller.isModalShowing && emulabeller.internalMode != labeller.EDITMODE.LABEL_RENAME){

            if (32 == e.keyCode) {
                // SPACEBAR -> play what is in view
                e.preventDefault();
                emulabeller.playPauseInView();
            }
            if (114 == e.keyCode) {
                // R key -> play sel
                emulabeller.playInMode("sel");
            }
            if (102 == e.keyCode) {
                // F key -> play entire file
                emulabeller.playInMode("all");
            }
            if (119 == e.keyCode){
                // W key -> zoom in
                emulabeller.zoomViewPort(1);
            }
            if (115 == e.keyCode){
                // S key -> zoom out
                emulabeller.zoomViewPort(0);
            }
            if (100 == e.keyCode){
                // D key -> shift right
                emulabeller.shiftViewP(1);
            }
            if (97 == e.keyCode){
                // A key -> shift left
                emulabeller.shiftViewP(0);
            }
            if (113 == e.keyCode){
                // Q key -> view all
                emulabeller.setView(-Infinity, Infinity);
            }
            if (101 == e.keyCode){
                // E key -> zoom in to selected segment
                emulabeller.zoomSel();
            }
            if (111 == e.keyCode){
                // O key
                if(emulabeller.externalMode==labeller.USAGEMODE.STANDALONE)
                 $('#fileGetterBtn').click();
                if(emulabeller.externalMode==labeller.USAGEMODE.SERVER)
                 emulabeller.openSubmenu();
            }
            if (99 == e.keyCode){
                // C key
                emulabeller.editLabel();
            }
            if (116 == e.keyCode){
                // T key
                emulabeller.moveSelTierToTop();
            }
            if (13 == e.keyCode){
                // ENTER key
                emulabeller.addSegmentAtSelection();
            }
            console.log(e.keyCode);
        }
    });

    return labeller;
}());
<|endoftext|>


<commit_before>var querystring = require( 'querystring' )
var trim = require( './trim' )

/**
 * Link
 * @constructor
 * @return {Link}
 */
function Link( value ) {

  if( !(this instanceof Link) ) {
    return new Link( value )
  }

  /** @type {Array} URI references */
  this.refs = []

}

/**
 * General matching pattern
 * @type {RegExp}
 */
Link.pattern = /(?:\<([^\>]+)\>)((\s*;\s*([a-z\*]+)=(("[^"]+")|('[^']+')|([^\,\;]+)))*)(\s*,\s*|$)/gi

/**
 * Attribute matching pattern
 * @type {RegExp}
 */
Link.attrPattern = /([a-z\*]+)=(?:(?:"([^"]+)")|(?:'([^']+)')|([^\,\;]+))/gi

/**
 * Determines whether an encoding can be
 * natively handled with a `Buffer`
 * @param {String} value
 * @return {Boolean}
 */
Link.isCompatibleEncoding = function( value ) {
  return /^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i.test( value )
}

/**
 * Format a given extended attribute and it's value
 * @param {String} attr
 * @param {Object} data
 * @return {String}
 */
Link.formatExtendedAttribute = function( attr, data ) {

    var encoding = ( data.encoding || 'utf-8' ).toUpperCase()
    var language = data.language || 'en'

    var encodedValue = ''

    if( Buffer.isBuffer( data.value ) && Link.isCompatibleEncoding( encoding ) ) {
      encodedValue = data.value.toString( encoding )
    } else if( Buffer.isBuffer( data.value ) ) {
      encodedValue = data.value.toString( 'hex' )
        .replace( /[0-9a-f]{2}/gi, '%$1' )
    } else {
      encodedValue = querystring.escape( data.value )
    }

    return attr + '=' + encoding + '\'' +
      language + '\'' + encodedValue

}

/**
 * Format a given attribute and it's value
 * @param {String} attr
 * @param {String|Object} value
 * @return {String}
 */
Link.formatAttribute = function( attr, value ) {

  // NOTE: Properly test this condition
  if( /\*$/.test( attr ) || typeof value !== 'string' )
    return Link.formatExtendedAttribute( attr, value )

  // Strictly, not all values matching this
  // selector would need quotes, but it's better to be safe
  var needsQuotes = /[^a-z]/i.test( value )

  if( needsQuotes ) {
    // We don't need to escape <SP> <,> <;>
    value = querystring.escape( value )
      .replace( /%20/g, ' ' )
      .replace( /%2C/g, ',' )
      .replace( /%3B/g, ';' )

    value = '"' + value + '"'
  }

  return attr + '=' + value

}

/**
 * Parses an extended value and attempts to decode it
 * @internal
 * @param {String} value
 * @return {Object}
 */
Link.parseExtendedValue = function( value ) {
  var parts = /([^']+)?(?:'([^']+)')?(.+)/.exec( value )
  return {
    language: parts[2].toLowerCase(),
    encoding: Link.isCompatibleEncoding( parts[1] ) ?
      null : parts[1].toLowerCase(),
    value: Link.isCompatibleEncoding( parts[1] ) ?
      querystring.unescape( parts[3] ) : parts[3]
  }
}

/**
 * Set an attribute on a link ref
 * @param {Object} link
 * @param {String} attr
 * @param {String} value
 */
Link.setAttr = function( link, attr, value ) {

  // Occurrences after the first "rel" MUST be ignored by parsers
  // @see RFC 5988, Section 5.3: Relation Type
  if( attr === 'rel' && link[ attr ] != null )
    return link

  if( Array.isArray( link[ attr ] ) ) {
    link[ attr ].push( value )
  } else if( link[ attr ] != null ) {
    link[ attr ] = [ link[ attr ], value ]
  } else {
    link[ attr ] = value
  }

  return link

}

/**
 * Parses uri attributes
 */
Link.parseParams = function( link, uri ) {
  var kvs = {}
  var params = /(.+)\?(.+)/gi.exec( uri )
  if( !params ) {
    return link
  }
  params = params[2].split('&')
  for( var i = 0; i < params.length; i++ ) {
    var param = params[i].split('=');
    kvs[ param[0] ] = param[1]
  }
  Link.setAttr( link, 'params', kvs )
  return link
}

/**
 * Parses out URI attributes
 * @internal
 * @param {Object} link
 * @param {String} parts
 * @return {Object} link
 */
Link.parseAttrs = function( link, parts ) {

  var match = null
  var attr = ''
  var value = ''
  var attrs = ''

  var uriAttrs = /<(.*)>;\s*(.*)/gi.exec( parts )
  if( uriAttrs ) {
    attrs = uriAttrs[2]
    link = Link.parseParams( link, uriAttrs[1] )
  }

  while( match = Link.attrPattern.exec( attrs ) ) {
    attr = match[1].toLowerCase()
    value = match[4] || match[3] || match[2]
    if( /\*$/.test( attr ) ) {
      Link.setAttr( link, attr, Link.parseExtendedValue( value ) )
    } else if( /%/.test( value ) ) {
      Link.setAttr( link, attr, querystring.unescape( value ) )
    } else {
      Link.setAttr( link, attr, value )
    }
  }

  return link

}

Link.parse = function( value ) {
  return new Link().parse( value )
}

/**
 * Link prototype
 * @type {Object}
 */
Link.prototype = {

  constructor: Link,

  /**
   * Get refs with given relation type
   * @param {String} value
   * @return {Array<Object>}
   */
  rel: function( value ) {

    var links = []

    for( var i = 0; i < this.refs.length; i++ ) {
      if( this.refs[ i ].rel === value ) {
        links.push( this.refs[ i ] )
      }
    }

    return links

  },

  /**
   * Get refs where given attribute has a given value
   * @param {String} attr
   * @param {String} value
   * @return {Array<Object>}
   */
  get: function( attr, value ) {

    attr = attr.toLowerCase()

    var links = []

    for( var i = 0; i < this.refs.length; i++ ) {
      if( this.refs[ i ][ attr ] === value ) {
        links.push( this.refs[ i ] )
      }
    }

    return links

  },

  set: function( link ) {
    this.refs.push( link )
    return this
  },

  has: function( attr, value ) {
    return this.get( attr, value ) != null
  },

  parse: function( value ) {

    // Unfold folded lines
    value = trim( value )
      .replace( /\r?\n[\x20\x09]+/g, '' )

    var match = null

    while( match = Link.pattern.exec( value ) ) {
      var link = Link.parseAttrs({ uri: match[1] }, match[0] )
      this.refs.push( link )
    }

    return this

  },

  toString: function() {

    var refs = []
    var link = ''
    var ref = null

    for( var i = 0; i < this.refs.length; i++ ) {
      ref = this.refs[i]
      link = Object.keys( this.refs[i] ).reduce( function( link, attr ) {
        if( attr === 'uri' ) return link
        return link + '; ' + Link.formatAttribute( attr, ref[ attr ] )
      }, '<' + ref.uri + '>' )
      refs.push( link )
    }

    return refs.join( ', ' )

  },

}

// Exports
module.exports = Link
<commit_msg>refactor(link): Fix whitespace<commit_after>var querystring = require( 'querystring' )
var trim = require( './trim' )

/**
 * Link
 * @constructor
 * @return {Link}
 */
function Link( value ) {

  if( !(this instanceof Link) ) {
    return new Link( value )
  }

  /** @type {Array} URI references */
  this.refs = []

}

/**
 * General matching pattern
 * @type {RegExp}
 */
Link.pattern = /(?:\<([^\>]+)\>)((\s*;\s*([a-z\*]+)=(("[^"]+")|('[^']+')|([^\,\;]+)))*)(\s*,\s*|$)/gi

/**
 * Attribute matching pattern
 * @type {RegExp}
 */
Link.attrPattern = /([a-z\*]+)=(?:(?:"([^"]+)")|(?:'([^']+)')|([^\,\;]+))/gi

/**
 * Determines whether an encoding can be
 * natively handled with a `Buffer`
 * @param {String} value
 * @return {Boolean}
 */
Link.isCompatibleEncoding = function( value ) {
  return /^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i.test( value )
}

/**
 * Format a given extended attribute and it's value
 * @param {String} attr
 * @param {Object} data
 * @return {String}
 */
Link.formatExtendedAttribute = function( attr, data ) {

  var encoding = ( data.encoding || 'utf-8' ).toUpperCase()
  var language = data.language || 'en'

  var encodedValue = ''

  if( Buffer.isBuffer( data.value ) && Link.isCompatibleEncoding( encoding ) ) {
    encodedValue = data.value.toString( encoding )
  } else if( Buffer.isBuffer( data.value ) ) {
    encodedValue = data.value.toString( 'hex' )
      .replace( /[0-9a-f]{2}/gi, '%$1' )
  } else {
    encodedValue = querystring.escape( data.value )
  }

  return attr + '=' + encoding + '\'' +
    language + '\'' + encodedValue

}

/**
 * Format a given attribute and it's value
 * @param {String} attr
 * @param {String|Object} value
 * @return {String}
 */
Link.formatAttribute = function( attr, value ) {

  // NOTE: Properly test this condition
  if( /\*$/.test( attr ) || typeof value !== 'string' )
    return Link.formatExtendedAttribute( attr, value )

  // Strictly, not all values matching this
  // selector would need quotes, but it's better to be safe
  var needsQuotes = /[^a-z]/i.test( value )

  if( needsQuotes ) {
    // We don't need to escape <SP> <,> <;>
    value = querystring.escape( value )
      .replace( /%20/g, ' ' )
      .replace( /%2C/g, ',' )
      .replace( /%3B/g, ';' )

    value = '"' + value + '"'
  }

  return attr + '=' + value

}

/**
 * Parses an extended value and attempts to decode it
 * @internal
 * @param {String} value
 * @return {Object}
 */
Link.parseExtendedValue = function( value ) {
  var parts = /([^']+)?(?:'([^']+)')?(.+)/.exec( value )
  return {
    language: parts[2].toLowerCase(),
    encoding: Link.isCompatibleEncoding( parts[1] ) ?
      null : parts[1].toLowerCase(),
    value: Link.isCompatibleEncoding( parts[1] ) ?
      querystring.unescape( parts[3] ) : parts[3]
  }
}

/**
 * Set an attribute on a link ref
 * @param {Object} link
 * @param {String} attr
 * @param {String} value
 */
Link.setAttr = function( link, attr, value ) {

  // Occurrences after the first "rel" MUST be ignored by parsers
  // @see RFC 5988, Section 5.3: Relation Type
  if( attr === 'rel' && link[ attr ] != null )
    return link

  if( Array.isArray( link[ attr ] ) ) {
    link[ attr ].push( value )
  } else if( link[ attr ] != null ) {
    link[ attr ] = [ link[ attr ], value ]
  } else {
    link[ attr ] = value
  }

  return link

}

/**
 * Parses uri attributes
 */
Link.parseParams = function( link, uri ) {

  var kvs = {}
  var params = /(.+)\?(.+)/gi.exec( uri )

  if( !params ) {
    return link
  }

  params = params[2].split('&')

  for( var i = 0; i < params.length; i++ ) {
    var param = params[i].split('=');
    kvs[ param[0] ] = param[1]
  }

  Link.setAttr( link, 'params', kvs )

  return link

}

/**
 * Parses out URI attributes
 * @internal
 * @param {Object} link
 * @param {String} parts
 * @return {Object} link
 */
Link.parseAttrs = function( link, parts ) {

  var match = null
  var attr = ''
  var value = ''
  var attrs = ''

  var uriAttrs = /<(.*)>;\s*(.*)/gi.exec( parts )
  if( uriAttrs ) {
    attrs = uriAttrs[2]
    link = Link.parseParams( link, uriAttrs[1] )
  }

  while( match = Link.attrPattern.exec( attrs ) ) {
    attr = match[1].toLowerCase()
    value = match[4] || match[3] || match[2]
    if( /\*$/.test( attr ) ) {
      Link.setAttr( link, attr, Link.parseExtendedValue( value ) )
    } else if( /%/.test( value ) ) {
      Link.setAttr( link, attr, querystring.unescape( value ) )
    } else {
      Link.setAttr( link, attr, value )
    }
  }

  return link

}

Link.parse = function( value ) {
  return new Link().parse( value )
}

/**
 * Link prototype
 * @type {Object}
 */
Link.prototype = {

  constructor: Link,

  /**
   * Get refs with given relation type
   * @param {String} value
   * @return {Array<Object>}
   */
  rel: function( value ) {

    var links = []

    for( var i = 0; i < this.refs.length; i++ ) {
      if( this.refs[ i ].rel === value ) {
        links.push( this.refs[ i ] )
      }
    }

    return links

  },

  /**
   * Get refs where given attribute has a given value
   * @param {String} attr
   * @param {String} value
   * @return {Array<Object>}
   */
  get: function( attr, value ) {

    attr = attr.toLowerCase()

    var links = []

    for( var i = 0; i < this.refs.length; i++ ) {
      if( this.refs[ i ][ attr ] === value ) {
        links.push( this.refs[ i ] )
      }
    }

    return links

  },

  set: function( link ) {
    this.refs.push( link )
    return this
  },

  has: function( attr, value ) {
    return this.get( attr, value ) != null
  },

  parse: function( value ) {

    // Unfold folded lines
    value = trim( value )
      .replace( /\r?\n[\x20\x09]+/g, '' )

    var match = null

    while( match = Link.pattern.exec( value ) ) {
      var link = Link.parseAttrs({ uri: match[1] }, match[0] )
      this.refs.push( link )
    }

    return this

  },

  toString: function() {

    var refs = []
    var link = ''
    var ref = null

    for( var i = 0; i < this.refs.length; i++ ) {
      ref = this.refs[i]
      link = Object.keys( this.refs[i] ).reduce( function( link, attr ) {
        if( attr === 'uri' ) return link
        return link + '; ' + Link.formatAttribute( attr, ref[ attr ] )
      }, '<' + ref.uri + '>' )
      refs.push( link )
    }

    return refs.join( ', ' )

  },

}

// Exports
module.exports = Link
<|endoftext|>


<commit_before>/**
 * Handle websocket connections.
 *
 * @public
 * @param {object} The session object.
 * @param {object} The connected websocket.
 */
module.exports = function handler (session, websocket) {

    /**
     * Handle websocket message.
     *
     * @private
     * @param {sring} The message data.
     */
    websocket.on('message', function (message) {

        // parse message
        // protocoll: [type, instance, event, id, err data]
        try {
            message = JSON.parse(message);
        } catch (error) {
            return;
        }

        // get role from session
        var role = session[engine.session_role];

        // event name
        var event = message[2];

        // get module instance or the core module (engine)
        var instance = message[1] === 0 && event === 'load' ? engine : engine.module.access(role, message[1], event);

        // ignore if instance doesn't exists
        if (!instance) {
            return //wsError(ws, new Error('Instance "' + message[1] + '"or event "' + event + '" not found'));
        }

        // get the link object
        var id = message[3];
        var link = instance._links[id];

        // data and error
        var data = message[5];
        var err = message[4];

        // create link and emit link event
        if (!link) {

            // create a new link with a custom id
            link = engine.link.call(instance, event, null, id, websocket);
            link.session = session;

            // save session in event
            link[engine.session_role] = role;
            link[engine.session_user] = session[engine.session_role];
            link[engine.session_locale] = session[engine.session_locale];

            // ensure socket on link
            link.socket = link.socket || websocket;

            // emit the new crated link
            instance.emit(event, link);
        }

        // ensure socket on link
        link.socket = link.socket || websocket;

        // handle message types
        switch (message[0]) {

            // END
            case 0:

                // call the end handler
                link._end(err, data);

                // destroy link
                delete instance._links[id];

                break;

            // DATA
            case 1:

                // call data handlers
                if (link._h.length) {
                    for (var i = 0; i < link._h.length; ++i) {
                        link._h[i].call(link._, err, data);
                    }
                }
        }
    });
};

/*
// broadcast message to all connected sockets
function broadcast (event, err, data) {
    var self = this;

    data = createMessage(self._._name, event, err, data);

    // broadcast
    for (var i = 0, l = WS.clients.length; i < l; ++i) {
        WS.clients[i].send(data);
    }
}

// send server websocket errors
function wsError (ws, err, msgId) {
    ws.send(createMessage(env.Z_CORE_INST, 'error', err, null, msgId));
}
*/
<commit_msg>removed link.js<commit_after><|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];
         var html = '';
         html += '
' + Username + '
';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid;
         html += '
Channel ID: ' + ChannelID;
         html += '
Cover ID: ' + Coverid;
         html += '
Thumbnail ID: ' + Thumbnail;
         html += '
---Preference---'
         html += '
interactive: ' + Tetris;
         html += '
Audience: ' + Audience;
         html += '
SelfStreamMute: ' + StreamMute;
         html += '
BeamBot FollowNotify' + FollowNotify +'';
         html += '
transcoding: ' + te;
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];
         var html = '';
         html += '
' + Username + '
';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid;
         html += '
Channel ID: ' + ChannelID;
         html += '
Cover ID: ' + Coverid;
         html += '
Thumbnail ID: ' + Thumbnail;
         html += '
---Preference---'
         html += '
interactive: ' + Tetris;
         html += '
Audience: ' + Audience;
         html += '
SelfStreamMute: ' + StreamMute;
         html += '
BeamBot FollowNotify:' + FollowNotify +'';
         html += '
transcoding: ' + te;
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<|endoftext|>


<commit_before>(function ($){
  /* wait for the page to be loaded */
  $(function(){
    /* Enable the toggle effect
    --------------------------------------------------------- */
    var $tgl = $("#nav_menu_toggle");
    var $hideToRight = $(".hide-right");
    var $hideToTop =  $(".hide-top");
    var $hideToFade =  $(".hide-fade");
    var animopts = {duration: 400, queue: false};

    if ($tgl) { // if a tgl is found
      function hideElements () {
        $tgl.rotate({animateTo:-90});
        $hideToRight.animate({width: "toggle"},animopts);
        $hideToTop.slideUp(animopts);
        $hideToFade.fadeOut(animopts);
      }

      function showElements () {
        $tgl.rotate({animateTo:0});
        $hideToRight.animate({width: "toggle"},animopts);
        $hideToTop.slideDown(animopts);
        $hideToFade.fadeIn(animopts);
      }

      function alternate(fnOn, fnOff) {
        var on = true;
        return function() {
          if (on) { fnOn(); } else { fnOff(); }
          on = !on;
        }
      }

      alternate.on = true;

      $tgl.on('click', alternate(hideElements, showElements));
    }

    /* Enable the background-slide-show
    --------------------------------------------------------- */
    var $body = $('body');
    var bgset = $body.data('bg');
    if (bgset && bgset.length) { // if slides are defined
      var slides = [];
      for (var i=0; i<bgset.length; i++) {
        slides[i] = {image: bgset[i]};
      }
      $.supersized({ slideshow: 1, vertical_center : 1, fit_portrait: 0, fit_landscape: 0, slides : slides });
    }

  });
})(jQuery);
<commit_msg>adding image-preloading<commit_after>(function ($){
  /* wait for the page to be loaded */
  $(function(){
    /* Enable the toggle effect
    --------------------------------------------------------- */
    var $tgl = $("#nav_menu_toggle");
    var $hideToRight = $(".hide-right");
    var $hideToTop =  $(".hide-top");
    var $hideToFade =  $(".hide-fade");
    var animopts = {duration: 400, queue: false};

    if ($tgl) { // if a tgl is found
      function hideElements () {
        $tgl.rotate({animateTo:-90});
        $hideToRight.animate({width: "toggle"},animopts);
        $hideToTop.slideUp(animopts);
        $hideToFade.fadeOut(animopts);
      }

      function showElements () {
        $tgl.rotate({animateTo:0});
        $hideToRight.animate({width: "toggle"},animopts);
        $hideToTop.slideDown(animopts);
        $hideToFade.fadeIn(animopts);
      }

      function alternate(fnOn, fnOff) {
        var on = true;
        return function() {
          if (on) { fnOn(); } else { fnOff(); }
          on = !on;
        }
      }

      alternate.on = true;

      $tgl.on('click', alternate(hideElements, showElements));
    }

    /* Enable the background-slide-show
    --------------------------------------------------------- */
    var $body = $('body');
    var bgset = $body.data('bg');
    if (bgset && bgset.length) { // if slides are defined
      var slides = [];
      $(bgset).each(function(){
        $('<img/>')[0].src = this; // preloads the image without adding it to the page
        slides.push({image: this});
      });
      $.supersized({ slideshow: 1, vertical_center : 1, fit_portrait: 0, fit_landscape: 0, slides : slides });
    }

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


<commit_before>var options = {

  viewportId: 'viewport',
  sourceCanvasId: 'imgSource',
  testImage: './img/test-image.jpg',
  imageWidth: 640,
  imageHeight: 480,
  resolution: 0.25,
  pixelChar: '•'

}

// http://www.html5canvastutorials.com/advanced/html5-canvas-load-image-data-url/
// http://stackoverflow.com/questions/6735470/get-pixel-color-from-canvas-on-mouseover
function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function getHexAtPoint(x, y, ctx){

  var p = ctx.getImageData(x, y, 1, 1).data,
      hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);

  return hex;

}

$(document).ready(function(){

  var canvas = document.getElementById(options.sourceCanvasId),
      context = canvas.getContext('2d');

  // load image from data url
  var imageObj = new Image();
  imageObj.onload = function() {

    context.drawImage(this, 0, 0);

    var viewport = $('#' + options.viewportId),
        rows = options.imageHeight * options.resolution,
        cols = options.imageWidth * options.resolution;

    for(var r = 0; r < rows; r++){

      for(var c = 0; c < cols; c++){

        var xOnCanvas = c * (1 / options.resolution),
            yOnCanvas = r * (1 / options.resolution);

        var colorAtPoint = getHexAtPoint(xOnCanvas, yOnCanvas, context);

        viewport.append("" + options.pixelChar + "");

      }

      viewport.append("
");

    }

  };

  imageObj.src = options.testImage;

});
<commit_msg>Moving canvas hex sampling into separate function<commit_after>var options = {

  viewportId: 'viewport',
  sourceCanvasId: 'imgSource',
  testImage: './img/test-image.jpg',
  imageWidth: 640,
  imageHeight: 480,
  resolution: 0.25,
  pixelChar: '•'

}

// http://www.html5canvastutorials.com/advanced/html5-canvas-load-image-data-url/
// http://stackoverflow.com/questions/6735470/get-pixel-color-from-canvas-on-mouseover
function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function getHexAtPoint(x, y, ctx){

  var p = ctx.getImageData(x, y, 1, 1).data,
      hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);

  return hex;

}

function buildHexMatrix(imageWidth, imageHeight, resolution, context){

  var matrixStart = new Date().getTime();

  var matrix = [];

  var rows = imageHeight * resolution,
      cols = imageWidth * resolution;

  for(var r = 0; r < rows; r++){

    var currentRow = [];

    for(var c = 0; c < cols; c++){

      var xOnCanvas = c * (1 / resolution),
          yOnCanvas = r * (1 / resolution);

      var colorAtPoint = getHexAtPoint(xOnCanvas, yOnCanvas, context);

      currentRow.push(colorAtPoint);

    }

    matrix.push(currentRow)

  }

  var matrixEnd = new Date().getTime();

  console.log("Matrix generation time: " + (matrixEnd - matrixStart));

  return matrix;

}

$(document).ready(function(){

  var canvas = document.getElementById(options.sourceCanvasId),
      context = canvas.getContext('2d');

  // load image from data url
  var imageObj = new Image();
  imageObj.onload = function() {

    context.drawImage(this, 0, 0);

    var hexMatrix = buildHexMatrix(options.imageHeight, options.imageWidth, options.resolution, context);

    var viewport = $('#' + options.viewportId);

  };

  imageObj.src = options.testImage;

});
<|endoftext|>


<commit_before>var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;

var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

var separation = 325;
var amountX = 50, amountY = 50;

var camera, scene, stats, renderer;

var orb, particles, lines, oldLines;

var object, uniforms, attributes;

var start = Date.now();

init();
animate();

function init() {
  var container = document.createElement('div');
  $('body').append(container);

  camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 );
  camera.position.z = 875;

  scene = new THREE.Scene();

  // outside circle
  var resolution = 150;
  var amplitude = 575;
  var size = 360 / resolution;

  var geometry = new THREE.Geometry();
  var material = new THREE.LineBasicMaterial( { color: 0x656565 } );
  for(var i = 0; i <= resolution; i++) {
      var segment = ( i * size ) * Math.PI / 180;
      geometry.vertices.push( new THREE.Vector3( Math.cos( segment ) * amplitude, Math.sin( segment ) * amplitude, 0 ) );
  }

  var circle = new THREE.Line( geometry, material );
  scene.add( circle );

  // red sphere
  var material = new THREE.MeshBasicMaterial( {
      color: 0x660022,
      opacity: 0.5,
      transparent: true,
  } );

  var sphere = new THREE.Mesh(
      new THREE.SphereGeometry( 456, 28, 28 ),
      material
  );
  scene.add( sphere );

  // orb parent container
  orb = new THREE.Object3D();
  scene.add( orb );

  // particles and lines
  var particleGeo = new THREE.Geometry();
  var lineGeo = new THREE.Geometry();

  for ( var i = 0; i < 1500; i ++ ) {
    var particle = new THREE.Vector3();

    particle.x = Math.random() * 2 - 1;
    particle.y = Math.random() * 2 - 1;
    particle.z = Math.random() * 2 - 1;
    particle.normalize();
    particle.multiplyScalar( Math.random() * 10 + 450 );

    particleGeo.vertices.push( particle );

    for (var j = 0; j < particleGeo.vertices.length-1; j++) {
      d = particle.distanceTo(particleGeo.vertices[j]);

      if (d < separation / 5) {
        lineGeo.vertices.push( particle );
        lineGeo.vertices.push( particleGeo.vertices[j] );
      }
    }
  }

  var particleMat = new THREE.ParticleBasicMaterial( { size: 3 } );
  particles = new THREE.ParticleSystem( particleGeo, particleMat );
  orb.add( particles );

  var shader = THREE.DisintegrateShader;

  attributes = THREE.UniformsUtils.clone( shader.attributes );
  uniforms = THREE.UniformsUtils.clone( shader.uniforms );

  var shaderMaterial = new THREE.ShaderMaterial( {

    uniforms:       uniforms,
    attributes:     attributes,
    vertexShader:   shader.vertexShader,
    fragmentShader: shader.fragmentShader,
    blending:       THREE.AdditiveBlending,
    depthTest:      false,
    transparent:    true,
    vertexColors:   THREE.VertexColors

  });

  shaderMaterial.linewidth = 1;

  lineGeo.dynamic = true;

  lines = new THREE.Line( lineGeo, shaderMaterial, THREE.LinePieces );

  var vertices = lines.geometry.vertices;
  var color = attributes.customColor.value;

  for( var v = 0; v < vertices.length; v ++ ) {

    color[ v ] = new THREE.Color( 0xffffff );

  }

  orb.add( lines );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  $(container).append( renderer.domElement );

  stats = new Stats();
  stats.domElement.style.position = 'absolute';
  stats.domElement.style.top = '0px';
  $(container).append( stats.domElement );

  window.addEventListener( 'resize', onWindowResize, false );

  // setInterval(function() { recalcLines() }, 3000);
}

function onWindowResize() {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );
}

function recalcLines() {
  var sign;

  if ( Math.random() > .5 )
    sign = true;
  else
    sign = false;

  if (sign) {
    separation += Math.random()*50;
  } else {
    separation -= Math.random()*50;
  }

  var lineGeo = new THREE.Geometry();

  console.log('recalculated');

  for ( var i = 0; i < particles.geometry.vertices.length; i ++ ) {
    for (var j = i + 1; j < particles.geometry.vertices.length; j++) {
      d = particles.geometry.vertices[i].distanceTo(particles.geometry.vertices[j]);

      if (d < separation / 5) {
        lineGeo.vertices.push( particles.geometry.vertices[i] );
        lineGeo.vertices.push( particles.geometry.vertices[j] );
      }
    }
  }

  material = new THREE.LineBasicMaterial( { opacity: 0.25, linewidth: 1, transparent: true } );

  // oldLines = new THREE.Line( lines.geometry, material, THREE.LinePieces );

  orb.remove( lines );
  // orb.add( oldLines );

  // var tween = new TWEEN.Tween( { opacity: 0.25 } )
  //   .to( { opacity: 0 }, 5000 )
  //   .easing( TWEEN.Easing.Linear.None )
  //   .onUpdate( function () {

  //     oldLines.material.opacity = this.opacity;

  //   } )
  //   .start();

  lines = new THREE.Line( lineGeo, material, THREE.LinePieces );
  orb.add( lines );
}

function animate() {
  requestAnimationFrame( animate );

  render();
  TWEEN.update();
  stats.update();
}

function render() {
  uniforms.time.value = .00015 * ( Date.now() - start );

  camera.lookAt( scene.position );

  orb.rotation.x += .002;
  orb.rotation.y += .002;
  orb.rotation.z -= .002;

  renderer.render( scene, camera );

  // lines.material.opacity = 1 + Math.sin(new Date().getTime() * .0025);
}<commit_msg>setup tweens for hiding and showing red shere<commit_after>var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;

var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

var separation = 325;
var amountX = 50, amountY = 50;

var camera, scene, stats, renderer;

var orb, redSphere, particles, lines, oldLines;

var object, uniforms, attributes;

var hideRedSphere, showRedSphere;

var start = Date.now();

init();
animate();

function init() {
  var container = document.createElement('div');
  $('body').append(container);

  camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 );
  camera.position.z = 875;

  scene = new THREE.Scene();

  // outside circle
  var resolution = 150;
  var amplitude = 575;
  var size = 360 / resolution;

  var geometry = new THREE.Geometry();
  var material = new THREE.LineBasicMaterial( { color: 0x656565 } );
  for(var i = 0; i <= resolution; i++) {
      var segment = ( i * size ) * Math.PI / 180;
      geometry.vertices.push( new THREE.Vector3( Math.cos( segment ) * amplitude, Math.sin( segment ) * amplitude, 0 ) );
  }

  var circle = new THREE.Line( geometry, material );
  scene.add( circle );

  // red sphere
  var material = new THREE.MeshBasicMaterial( {
      color: 0x660022,
      opacity: 0.5,
      transparent: true,
  } );

  redSphere = new THREE.Mesh(
      new THREE.SphereGeometry( 456, 28, 28 ),
      material
  );
  scene.add( redSphere );

  // orb parent container
  orb = new THREE.Object3D();
  scene.add( orb );

  // particles and lines
  var particleGeo = new THREE.Geometry();
  var lineGeo = new THREE.Geometry();

  for ( var i = 0; i < 1500; i ++ ) {
    var particle = new THREE.Vector3();

    particle.x = Math.random() * 2 - 1;
    particle.y = Math.random() * 2 - 1;
    particle.z = Math.random() * 2 - 1;
    particle.normalize();
    particle.multiplyScalar( Math.random() * 10 + 450 );

    particleGeo.vertices.push( particle );

    for (var j = 0; j < particleGeo.vertices.length-1; j++) {
      d = particle.distanceTo(particleGeo.vertices[j]);

      if (d < separation / 5) {
        lineGeo.vertices.push( particle );
        lineGeo.vertices.push( particleGeo.vertices[j] );
      }
    }
  }

  var particleMat = new THREE.ParticleBasicMaterial( { size: 3 } );
  particles = new THREE.ParticleSystem( particleGeo, particleMat );
  orb.add( particles );

  var shader = THREE.DisintegrateShader;

  attributes = THREE.UniformsUtils.clone( shader.attributes );
  uniforms = THREE.UniformsUtils.clone( shader.uniforms );

  var shaderMaterial = new THREE.ShaderMaterial( {

    uniforms:       uniforms,
    attributes:     attributes,
    vertexShader:   shader.vertexShader,
    fragmentShader: shader.fragmentShader,
    blending:       THREE.AdditiveBlending,
    depthTest:      false,
    transparent:    true,
    vertexColors:   THREE.VertexColors

  });

  shaderMaterial.linewidth = 1;

  lineGeo.dynamic = true;

  lines = new THREE.Line( lineGeo, shaderMaterial, THREE.LinePieces );

  var vertices = lines.geometry.vertices;
  var color = attributes.customColor.value;

  for( var v = 0; v < vertices.length; v ++ ) {

    color[ v ] = new THREE.Color( 0xffffff );

  }

  orb.add( lines );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  $(container).append( renderer.domElement );

  stats = new Stats();
  stats.domElement.style.position = 'absolute';
  stats.domElement.style.top = '0px';
  $(container).append( stats.domElement );

  window.addEventListener( 'resize', onWindowResize, false );

  // defineTweens
  defineTweens();
}

function onWindowResize() {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );
}

function recalcLines() {
  var sign;

  if ( Math.random() > .5 )
    sign = true;
  else
    sign = false;

  if (sign) {
    separation += Math.random()*50;
  } else {
    separation -= Math.random()*50;
  }

  var lineGeo = new THREE.Geometry();

  console.log('recalculated');

  for ( var i = 0; i < particles.geometry.vertices.length; i ++ ) {
    for (var j = i + 1; j < particles.geometry.vertices.length; j++) {
      d = particles.geometry.vertices[i].distanceTo(particles.geometry.vertices[j]);

      if (d < separation / 5) {
        lineGeo.vertices.push( particles.geometry.vertices[i] );
        lineGeo.vertices.push( particles.geometry.vertices[j] );
      }
    }
  }

  material = new THREE.LineBasicMaterial( { opacity: 0.25, linewidth: 1, transparent: true } );

  // oldLines = new THREE.Line( lines.geometry, material, THREE.LinePieces );

  orb.remove( lines );
  // orb.add( oldLines );

  // var tween = new TWEEN.Tween( { opacity: 0.25 } )
  //   .to( { opacity: 0 }, 5000 )
  //   .easing( TWEEN.Easing.Linear.None )
  //   .onUpdate( function () {

  //     oldLines.material.opacity = this.opacity;

  //   } )
  //   .start();

  lines = new THREE.Line( lineGeo, material, THREE.LinePieces );
  orb.add( lines );
}

function animate() {
  requestAnimationFrame( animate );

  render();
  TWEEN.update();
  stats.update();
}

function render() {
  uniforms.time.value = .00015 * ( Date.now() - start );

  camera.lookAt( scene.position );

  orb.rotation.x += .002;
  orb.rotation.y += .002;
  orb.rotation.z -= .002;

  renderer.render( scene, camera );

  // lines.material.opacity = 1 + Math.sin(new Date().getTime() * .0025);
}

function defineTweens() {
  hideRedSphere = new TWEEN.Tween( { x: 1.0, y: 1.0, z:1.0 } )
  .to( { x: 0.01, y: 0.01, z: 0.01 }, 1000 )
  .easing( TWEEN.Easing.Linear.None )
  .onUpdate( function () {
    redSphere.scale = {x: this.x, y: this.y, z: this.z};
  })
  .onComplete( function() {
    redSphere.visible = false;
  });

  showRedSphere = new TWEEN.Tween( { x: 0.01, y: 0.01, z: 0.01 } )
  .to( { x: 1.0, y: 1.0, z:1.0 }, 1000 )
  .easing( TWEEN.Easing.Linear.None )
  .onStart( function() {
    redSphere.visible = true;
  })
  .onUpdate( function () {
    redSphere.scale = {x: this.x, y: this.y, z: this.z};
  });
}

}<|endoftext|>