<commit_before>import Path from 'path'
import fs from 'fs'
import child_process from 'child_process'
import { Map } from 'immutable'
import http from 'http'
import url from 'url'
import * as constants from '../constants/helper.js'

export const checkSiaPath = () => new Promise((resolve, reject) => {
	fs.stat(SiaAPI.config.attr('siac').path, (err) => {
		 if (!err) {
			if (Path.basename(SiaAPI.config.attr('siac').path).indexOf('siac') !== -1) {
				resolve()
			} else {
				reject({ message: 'Invalid binary name.' })
			}
		 } else {
			reject(err)
		 }
	})
})

export const initPlugin = () => checkSiaPath().catch(() => {
	//Look in the siad folder for siac.
	SiaAPI.config.attr('siac', { path: Path.resolve( Path.dirname(SiaAPI.config.attr('siad').path), (process.platform === 'win32' ? './siac.exe' : './siac') ) })
	checkSiaPath().catch(() => {
		// config.path doesn't exist. Prompt the user for siac's location
		if (!SiaAPI.config.attr('siac')) {
			SiaAPI.config.attr('siac', { path: '' })
		}
		SiaAPI.showError({ title: 'Siac not found', content: 'Sia-UI couldn\'t locate siac. Please navigate to siac.' })
		const siacPath = SiaAPI.openFile({
			title: 'Please locate siac.',
			properties: ['openFile'],
			defaultPath: Path.join('..', SiaAPI.config.attr('siac').path || './' ),
			filters: [{ name: 'siac', extensions: ['*'] }],
		})
		if (siacPath) {
			if (Path.basename(siacPath[0]).indexOf('siac') === -1) {
				SiaAPI.showError({ title: 'Invalid Binary Name', content: 'The siac binary must be called siac. Restart the plugin to choose a valid binary.' })
			} else {
				SiaAPI.config.attr('siac', { path: siacPath[0] })
			}
		} else {
			SiaAPI.showError({ title: 'Siac not found', content: 'This plugin will be unusable until a proper siac binary is found.' })
		}
	})
	SiaAPI.config.save()
})

export const commandType = function(commandString, specialArray) {
	//Cleans string and sees if any subarray in array starts with the string when split.
	const args = commandString.replace(/\s*\s/g, ' ').trim().split(' ')
	if (args[0] === './siac' || args[0] === 'siac') {
		args.shift()
	}

	//Can't do a simple match because commands can be passed additional arguments.
	return specialArray.findIndex( (command) =>
		command.reduce((matches, argument, i) =>
			(matches && argument === args[i]),
		true) && commandString.indexOf('-h') === -1 //Also covers --help.
		//Don't show a password prompt if user is looking for help.
	)
}

export const spawnCommand = function(commandStr, actions, newid) {
	//Create new command object. Id doesn't need to be unique, just can't be the same for adjacent commands.

	//We set the command first so the user sees exactly what they type. (Minus leading and trailing spaces, double spaces, etc.)
	let commandString = commandStr.replace(/\s*\s/g, ' ').trim()
	const newCommand = Map({ command: commandString, result: '', id: newid, stat: 'running' })
	actions.addCommand(newCommand)

	//Remove surrounding whitespace and leading siac command.
	if (commandString.startsWith('siac')) {
		commandString = commandString.slice(4).trim()
	} else if (commandString.startsWith('./siac')) {
		commandString = commandString.slice(6).trim()
	}

	//Add address flag to siac.
	let args = commandString.split(' ')
	if (args.indexOf('-a') === -1 && args.indexOf('--address') === -1 && SiaAPI.config.attr('address')) {
		args = args.concat([ '-a', SiaAPI.config.attr('address') ])
	}

	const siac = child_process.spawn('./siac', args, { cwd: Path.dirname(SiaAPI.config.attr('siac').path || '') })

	//Update the UI when the process receives new ouput.
	const consumeChunk = function(chunk) {
		const chunkTrimmed = chunk.toString().replace(/stty: stdin isn't a terminal\n/g, '')
		actions.updateCommand(newCommand.get('command'), newCommand.get('id'), chunkTrimmed)
	}
	siac.stdout.on('data', consumeChunk)
	siac.stderr.on('data', consumeChunk)

	let closed = false
	const streamClosed = function() {
		if (!closed) {
			actions.endCommand(newCommand.get('command'), newCommand.get('id'))
			closed = true
		}
	}

	siac.on('error', (e) => {
		consumeChunk(`Error running command: ${e.message}.\nIs your siac path correct?`)
		streamClosed()
	})
	siac.on('close', () => {
		streamClosed()
	})

	//If window is small auto close command overview so we can see the return value.
	if (document.getElementsByClassName('command-history-list')[0].offsetHeight < 180) {
		actions.hideCommandOverview()
	}

	return siac
}

export const httpCommand = function(commandStr, actions, newid) {
	let commandString = commandStr
	const originalCommand = commandStr.replace(/\s*\s/g, ' ').trim()

	//Remove surrounding whitespace and leading siac command.
	if (commandString.startsWith('siac')) {
		commandString = commandString.slice(4).trim()
	} else if (commandString.startsWith('./siac')) {
		commandString = commandString.slice(6).trim()
	}

	//Parse arguments.
	const args = commandString.split(' ')

	//Add address flag to siac.
	let siaAddr = url.parse('http://localhost:9980')

	if (args.indexOf('-a') === -1 && args.indexOf('--address') === -1) {
		if (SiaAPI.config.attr('address')) {
			//Load default address.
			siaAddr = url.parse('http://' + SiaAPI.config.attr('address'))
		}
	} else {
		//Parse address flag.
		let index = args.indexOf('-a')
		if  (index === -1) {
			index = args.indexOf('--address')

		}
		if (index < args.length-1) {
			siaAddr = url.parse('http://' + args[index+1])
		}
		args.splice(index, 2)
		commandString = args.join(' ')
	}

	let apiURL = ''
	switch (commandString) {
	case 'wallet unlock':
		apiURL = '/wallet/unlock'
		break

	case 'wallet load seed':
		apiURL = '/wallet/seed'
		break

	default:
		return spawnCommand(commandString, actions).stdin
	}

	//Spawn new command if we are good to go.
	const newCommand = Map({ command: originalCommand, result: '', id: newid, stat: 'running' })
	actions.addCommand(newCommand)

	//Update the UI when the process receives new ouput.
	let buffer = ''
	const consumeChunk = function(chunk) {
		buffer += chunk.toString()
	}

	let closed = false
	const streamClosed = function(res) {
		if (!closed) {
			try {
				buffer = JSON.parse(buffer).message
			} catch (e){}

			if (res.statusCode >= 200 && res.statusCode <= 299){
				buffer += 'Success'
			}

			actions.updateCommand(newCommand.get('command'), newCommand.get('id'), buffer)
			actions.endCommand(newCommand.get('command'), newCommand.get('id'))
			closed = true
		}
	}

	//If window is small auto close command overview so we can see the return value.
	if (document.getElementsByClassName('command-history-list')[0].offsetHeight < 180) {
		actions.hideCommandOverview()
	}

	const options = {
		hostname: siaAddr.hostname,
		port: siaAddr.port,
		path: apiURL,
		method: 'POST',
		headers: {
			'User-Agent': 'Sia-Agent',
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	}
	const req = http.request(options, (res) => {
		res.on('data', consumeChunk)
		res.on('end', () => streamClosed(res))
	})
	req.on('error', (e) => {
		consumeChunk(e.message)
		streamClosed()
	})
	return req
}

export const commandInputHelper = function(e, actions, currentCommand, showCommandOverview, newid) {
	//These commands need a password prompt or other special handling.
	const specialCommands = [ ['wallet', 'load', 'seed'], ['wallet', 'unlock'], ['help'], ['?'] ]

	const eventTarget = e.target
	//Enter button.
	if (e.keyCode === 13) {

		//Check if command is special.
		switch ( commandType(currentCommand, specialCommands) ) {
		case constants.REGULAR_COMMAND: //Regular command.
			spawnCommand(currentCommand, actions, newid) //Spawn command defined in index.js.
			break

		case constants.WALLET_UNLOCK: //wallet unlock
		case constants.WALLET_SEED: //wallet load seed
			actions.showWalletPrompt()
			break

		case constants.HELP: //help
			const text = 'help'
		case constants.HELP_QMARK: //?
			const newText = text || '?'
			if (showCommandOverview) {
				actions.hideCommandOverview()
			} else {
				actions.showCommandOverview()
			}

			//The command log won't actually show a help command but we still want to be able to select it in the command history.
			const newCommand = Map({ command: newText, result: '', id: newid })
			actions.addCommand(newCommand)
			actions.endCommand(newCommand.get('command'), newCommand.get('id'))
			break

		default:
			break
		}
	 } else if (e.keyCode === 38) {
		//Up arrow.
		actions.loadPrevCommand(eventTarget.value)
		setTimeout( () => {
			eventTarget.setSelectionRange(eventTarget.value.length, eventTarget.value.length)
		}, 0)
	} else if (e.keyCode === 40) {
		//Down arrow.
		actions.loadNextCommand(eventTarget.value)
		setTimeout(() => {
			eventTarget.setSelectionRange(eventTarget.value.length, eventTarget.value.length)
		}, 0)
	}
}

<commit_msg>Minor format fix<commit_after>import Path from 'path'
import fs from 'fs'
import child_process from 'child_process'
import { Map } from 'immutable'
import http from 'http'
import url from 'url'
import * as constants from '../constants/helper.js'

export const checkSiaPath = () => new Promise((resolve, reject) => {
	fs.stat(SiaAPI.config.attr('siac').path, (err) => {
		 if (!err) {
			if (Path.basename(SiaAPI.config.attr('siac').path).indexOf('siac') !== -1) {
				resolve()
			} else {
				reject({ message: 'Invalid binary name.' })
			}
		 } else {
			reject(err)
		 }
	})
})

export const initPlugin = () => checkSiaPath().catch(() => {
	//Look in the siad folder for siac.
	SiaAPI.config.attr('siac', { path: Path.resolve( Path.dirname(SiaAPI.config.attr('siad').path), (process.platform === 'win32' ? './siac.exe' : './siac') ) })
	checkSiaPath().catch(() => {
		// config.path doesn't exist. Prompt the user for siac's location
		if (!SiaAPI.config.attr('siac')) {
			SiaAPI.config.attr('siac', { path: '' })
		}
		SiaAPI.showError({ title: 'Siac not found', content: 'Sia-UI couldn\'t locate siac. Please navigate to siac.' })
		const siacPath = SiaAPI.openFile({
			title: 'Please locate siac.',
			properties: ['openFile'],
			defaultPath: Path.join('..', SiaAPI.config.attr('siac').path || './' ),
			filters: [{ name: 'siac', extensions: ['*'] }],
		})
		if (siacPath) {
			if (Path.basename(siacPath[0]).indexOf('siac') === -1) {
				SiaAPI.showError({ title: 'Invalid Binary Name', content: 'The siac binary must be called siac. Restart the plugin to choose a valid binary.' })
			} else {
				SiaAPI.config.attr('siac', { path: siacPath[0] })
			}
		} else {
			SiaAPI.showError({ title: 'Siac not found', content: 'This plugin will be unusable until a proper siac binary is found.' })
		}
	})
	SiaAPI.config.save()
})

export const commandType = function(commandString, specialArray) {
	//Cleans string and sees if any subarray in array starts with the string when split.
	const args = commandString.replace(/\s*\s/g, ' ').trim().split(' ')
	if (args[0] === './siac' || args[0] === 'siac') {
		args.shift()
	}

	//Can't do a simple match because commands can be passed additional arguments.
	return specialArray.findIndex( (command) =>
		command.reduce((matches, argument, i) =>
			(matches && argument === args[i]),
		true) && commandString.indexOf('-h') === -1 //Also covers --help.
		//Don't show a password prompt if user is looking for help.
	)
}

export const spawnCommand = function(commandStr, actions, newid) {
	//Create new command object. Id doesn't need to be unique, just can't be the same for adjacent commands.

	//We set the command first so the user sees exactly what they type. (Minus leading and trailing spaces, double spaces, etc.)
	let commandString = commandStr.replace(/\s*\s/g, ' ').trim()
	const newCommand = Map({ command: commandString, result: '', id: newid, stat: 'running' })
	actions.addCommand(newCommand)

	//Remove surrounding whitespace and leading siac command.
	if (commandString.startsWith('siac')) {
		commandString = commandString.slice(4).trim()
	} else if (commandString.startsWith('./siac')) {
		commandString = commandString.slice(6).trim()
	}

	//Add address flag to siac.
	let args = commandString.split(' ')
	if (args.indexOf('-a') === -1 && args.indexOf('--address') === -1 && SiaAPI.config.attr('address')) {
		args = args.concat([ '-a', SiaAPI.config.attr('address') ])
	}

	const siac = child_process.spawn('./siac', args, { cwd: Path.dirname(SiaAPI.config.attr('siac').path || '') })

	//Update the UI when the process receives new ouput.
	const consumeChunk = function(chunk) {
		const chunkTrimmed = chunk.toString().replace(/stty: stdin isn't a terminal\n/g, '')
		actions.updateCommand(newCommand.get('command'), newCommand.get('id'), chunkTrimmed)
	}
	siac.stdout.on('data', consumeChunk)
	siac.stderr.on('data', consumeChunk)

	let closed = false
	const streamClosed = function() {
		if (!closed) {
			actions.endCommand(newCommand.get('command'), newCommand.get('id'))
			closed = true
		}
	}

	siac.on('error', (e) => {
		consumeChunk(`Error running command: ${e.message}.\nIs your siac path correct?`)
		streamClosed()
	})
	siac.on('close', () => {
		streamClosed()
	})

	//If window is small auto close command overview so we can see the return value.
	if (document.getElementsByClassName('command-history-list')[0].offsetHeight < 180) {
		actions.hideCommandOverview()
	}

	return siac
}

export const httpCommand = function(commandStr, actions, newid) {
	let commandString = commandStr
	const originalCommand = commandStr.replace(/\s*\s/g, ' ').trim()

	//Remove surrounding whitespace and leading siac command.
	if (commandString.startsWith('siac')) {
		commandString = commandString.slice(4).trim()
	} else if (commandString.startsWith('./siac')) {
		commandString = commandString.slice(6).trim()
	}

	//Parse arguments.
	const args = commandString.split(' ')

	//Add address flag to siac.
	let siaAddr = url.parse('http://localhost:9980')

	if (args.indexOf('-a') === -1 && args.indexOf('--address') === -1) {
		if (SiaAPI.config.attr('address')) {
			//Load default address.
			siaAddr = url.parse('http://' + SiaAPI.config.attr('address'))
		}
	} else {
		//Parse address flag.
		let index = args.indexOf('-a')
		if  (index === -1) {
			index = args.indexOf('--address')

		}
		if (index < args.length-1) {
			siaAddr = url.parse('http://' + args[index+1])
		}
		args.splice(index, 2)
		commandString = args.join(' ')
	}

	let apiURL = ''
	switch (commandString) {
	case 'wallet unlock':
		apiURL = '/wallet/unlock'
		break

	case 'wallet load seed':
		apiURL = '/wallet/seed'
		break

	default:
		return spawnCommand(commandString, actions).stdin
	}

	//Spawn new command if we are good to go.
	const newCommand = Map({ command: originalCommand, result: '', id: newid, stat: 'running' })
	actions.addCommand(newCommand)

	//Update the UI when the process receives new ouput.
	let buffer = ''
	const consumeChunk = function(chunk) {
		buffer += chunk.toString()
	}

	let closed = false
	const streamClosed = function(res) {
		if (!closed) {
			try {
				buffer = JSON.parse(buffer).message
			} catch (e) {}

			if (res.statusCode >= 200 && res.statusCode <= 299) {
				buffer += 'Success'
			}

			actions.updateCommand(newCommand.get('command'), newCommand.get('id'), buffer)
			actions.endCommand(newCommand.get('command'), newCommand.get('id'))
			closed = true
		}
	}

	//If window is small auto close command overview so we can see the return value.
	if (document.getElementsByClassName('command-history-list')[0].offsetHeight < 180) {
		actions.hideCommandOverview()
	}

	const options = {
		hostname: siaAddr.hostname,
		port: siaAddr.port,
		path: apiURL,
		method: 'POST',
		headers: {
			'User-Agent': 'Sia-Agent',
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	}
	const req = http.request(options, (res) => {
		res.on('data', consumeChunk)
		res.on('end', () => streamClosed(res))
	})
	req.on('error', (e) => {
		consumeChunk(e.message)
		streamClosed()
	})
	return req
}

export const commandInputHelper = function(e, actions, currentCommand, showCommandOverview, newid) {
	//These commands need a password prompt or other special handling.
	const specialCommands = [ ['wallet', 'load', 'seed'], ['wallet', 'unlock'], ['help'], ['?'] ]

	const eventTarget = e.target
	//Enter button.
	if (e.keyCode === 13) {

		//Check if command is special.
		switch ( commandType(currentCommand, specialCommands) ) {
		case constants.REGULAR_COMMAND: //Regular command.
			spawnCommand(currentCommand, actions, newid) //Spawn command defined in index.js.
			break

		case constants.WALLET_UNLOCK: //wallet unlock
		case constants.WALLET_SEED: //wallet load seed
			actions.showWalletPrompt()
			break

		case constants.HELP: //help
			const text = 'help'
		case constants.HELP_QMARK: //?
			const newText = text || '?'
			if (showCommandOverview) {
				actions.hideCommandOverview()
			} else {
				actions.showCommandOverview()
			}

			//The command log won't actually show a help command but we still want to be able to select it in the command history.
			const newCommand = Map({ command: newText, result: '', id: newid })
			actions.addCommand(newCommand)
			actions.endCommand(newCommand.get('command'), newCommand.get('id'))
			break

		default:
			break
		}
	 } else if (e.keyCode === 38) {
		//Up arrow.
		actions.loadPrevCommand(eventTarget.value)
		setTimeout( () => {
			eventTarget.setSelectionRange(eventTarget.value.length, eventTarget.value.length)
		}, 0)
	} else if (e.keyCode === 40) {
		//Down arrow.
		actions.loadNextCommand(eventTarget.value)
		setTimeout(() => {
			eventTarget.setSelectionRange(eventTarget.value.length, eventTarget.value.length)
		}, 0)
	}
}

<|endoftext|>


<commit_before>// Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

// For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
// the contiguous subarray [4,−1,2,1] has the largest sum = 6.

var maxSubArray = function(nums) {
  var max = nums[0],
      sum = 0;
  nums.forEach((e, i) => {
    sum += e;
    if (sum > max)
      max = sum;
    if (sum < 0)
      sum = 0;
  });
  return max;
};
<commit_msg>add process<commit_after>// Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

// For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
// the contiguous subarray [4,−1,2,1] has the largest sum = 6.

// set variable max as the first subset of nums array
// set sum to 0
// loop through nums with a for each loop
  // set or add sum to the first element
  // if sum is greater than max set it
  // if sum is less than 0 set to 0
// return max

var maxSubArray = function(nums) {
  var max = nums[0],
      sum = 0;
  nums.forEach((e, i) => {
    sum += e;
    if (sum > max)
      max = sum;
    if (sum < 0)
      sum = 0;
  });
  return max;
};
<|endoftext|>


<commit_before>/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 */

(function($) {

$.fn.extend({
	countable: function(options) {
		return this.each(function() {
			var $this = $(this), interval, prev_char_diff, $el;
			options = $.extend({
				threshold: 0.5,
				appendMethod: 'insertAfter', // insertBefore || insertAfter
				startOpacity: .25,
				maxLength: parseInt( $this.attr('maxlength'), 10 ),
				maxClassName: 'maxed',
				className: 'counter',
				tagName: 'span',
				interval: 750,
				positiveCopy: "You have {n} characters left.",
				negativeCopy: "You are {n} characters over.",
				fadeDuration: 'normal'
			}, options);

			$el = $('<'+options.tagName+'/>')
				.html( options.positiveCopy.replace("{n}", '') )
				.addClass( options.className );
			if ( $.support.opacity ) $el.css({ opacity: 0 }); // don't set opacity for IE to avoid clear text issues.
			$el[options.appendMethod]($this);

			$this
				.bind('keyup', check)
				.bind('focus blur', function(event) {
					if ( event.type == 'blur' ) clearInterval( interval );
					if ( event.type == 'focus' && !interval ) setInterval(check, options.interval);
				});

			function check() {
				var val = $this.val(), length = val.length, percentage_complete = length/options.maxLength, char_diff = options.maxLength - length;
				if ( prev_char_diff != undefined && char_diff == prev_char_diff ) return;
				opacity = options.startOpacity + ((options.threshold - percentage_complete) * ((options.startOpacity * 2) - 2));

				if ( $el.is(':hidden') && percentage_complete >= options.threshold )
					$el.show();
				if ( $el.is(':visible') && percentage_complete < options.threshold )
					$el.hide();

				if ( $.support.opacity ) // don't set opacity for IE to avoid clear text issues.
					$el.stop().fadeTo( options.fadeDuration, percentage_complete >= options.threshold ? opacity : 0 );

				if ( char_diff >= 0 ) {
					if ( $el.is( '.'+options.maxClassName ) )
						$el.html( options.positiveCopy.replace("{n}", '') );
				} else {
					if ( !$el.is( '.'+options.maxClassName ) )
						$el.html( options.negativeCopy.replace("{n}", '') );
				}

				$el[ (char_diff < 0 ? 'add' : 'remove') + 'Class' ]( options.maxClassName );
				$el.find('.num').text( Math.abs(char_diff) );

				if ( char_diff == -1 || char_diff == 1 )
					$el.html( $el.html().replace(/characters\b/, "character") );
				else
					$el.html( $el.html().replace(/character\b/, "characters") );

				prev_char_diff = char_diff;
			};
			check();
		});
	}
});

})(jQuery);<commit_msg>Updated `appendMethod` options and added `target` option.<commit_after>/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 */

(function($) {

$.fn.extend({
	countable: function(options) {
		return this.each(function() {
			var $this = $(this), interval, prev_char_diff, $el;
			options = $.extend({
				threshold: .5,
				appendMethod: 'insertAfter', // insertBefore || insertAfter || prependTo || appendTo
				target: $this, // element in which to place the counter
				startOpacity: .25,
				maxLength: parseInt( $this.attr('maxlength'), 10 ) || 0,
				maxClassName: 'maxed',
				className: 'counter',
				tagName: 'span',
				interval: 750,
				positiveCopy: "You have {n} characters left.",
				negativeCopy: "You are {n} characters over.",
				fadeDuration: 'normal'
			}, options);

			$el = $('<'+options.tagName+'/>')
				.html( options.positiveCopy.replace("{n}", '') )
				.addClass( options.className );
			if ( $.support.opacity ) $el.css({ opacity: 0 }); // don't set opacity for IE to avoid clear text issues.
			$el[options.appendMethod](options.target);

			$this
				.bind('keyup', check)
				.bind('focus blur', function(event) {
					if ( event.type == 'blur' ) clearInterval( interval );
					if ( event.type == 'focus' && !interval ) setInterval(check, options.interval);
				});

			function check() {
				var val = $this.val(), length = val.length, percentage_complete = length/options.maxLength, char_diff = options.maxLength - length;
				if ( prev_char_diff != undefined && char_diff == prev_char_diff ) return;
				opacity = options.startOpacity + ((options.threshold - percentage_complete) * ((options.startOpacity * 2) - 2));

				if ( $el.is(':hidden') && percentage_complete >= options.threshold )
					$el.show();
				if ( $el.is(':visible') && percentage_complete < options.threshold )
					$el.hide();

				if ( $.support.opacity ) // don't set opacity for IE to avoid clear text issues.
					$el.stop().fadeTo( options.fadeDuration, percentage_complete >= options.threshold ? opacity : 0 );

				if ( char_diff >= 0 ) {
					if ( $el.is( '.'+options.maxClassName ) )
						$el.html( options.positiveCopy.replace("{n}", '') );
				} else {
					if ( !$el.is( '.'+options.maxClassName ) )
						$el.html( options.negativeCopy.replace("{n}", '') );
				}

				$el[ (char_diff < 0 ? 'add' : 'remove') + 'Class' ]( options.maxClassName );
				$el.find('.num').text( Math.abs(char_diff) );

				if ( char_diff == -1 || char_diff == 1 )
					$el.html( $el.html().replace(/characters\b/, "character") );
				else
					$el.html( $el.html().replace(/character\b/, "characters") );

				prev_char_diff = char_diff;
			};
			check();
		});
	}
});

})(jQuery);<|endoftext|>


<commit_before>module.exports = {
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  extends: '../.eslintrc.js',
  // required to lint *.vue files
  env: {
    'browser': true,
    'mocha': true
  }
}
<commit_msg>disable rule<commit_after>module.exports = {
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  extends: '../.eslintrc.js',
  // required to lint *.vue files
  env: {
    'browser': true,
    'mocha': true
  },
  rules: {
    'camelcase': 'off'
  }
}
<|endoftext|>


<commit_before>/**
 * @author: 	Inscure
 * @email: 	drimer.eco@gmail.com
 * @website:	http://extreme-fusion.pl/
 */

(function($) {
  $.fn.liveDraggable = function (opts) {
		this.on('mousemove', opts.selector, function() {
			$(this).draggable();
		});
	};
}(jQuery));
<commit_msg>Update jquery.draggable.js<commit_after>/**
 * @author: 	Inscure
 * @email: 	drimer.eco@gmail.com
 * @website:	http://extreme-fusion.pl/
 */

(function($) {
  $.fn.liveDraggable = function (opts) {
  		$(opts.selector).css({'cursor': 'move'});
		this.on('mousemove', opts.selector, function() {
			$(this).draggable();
		});
	};
}(jQuery));
<|endoftext|>


<commit_before>// API for the User interface to use
/////////////////////////////

/////////////////////////////
// UserPublicKey methods
function UserPublicKey(publicSignKey, publicBoxKey) {
    this.pSignKey = publicSignKey // 32 bytes
    this.pBoxKey = publicBoxKey; // 32 bytes

    // ((err, publicKeyString) -> ())
    this.getPublicKeys = function() {
	var tmp = new Uint8Array(this.pSignKey.length + this.pBoxKey.length);
	tmp.set(this.pSignKey, 0);
	tmp.set(this.pBoxKey, this.pSignKey.length);
	return tmp;
    }

    // (Uint8Array, User, (nonce, cipher) -> ())
    this.encryptMessageFor = function(input, us, cb) {
	var nonce = nacl.randomBytes(24);
	cb(nonce, nacl.box(input, nonce, this.pBoxKey, us.sBoxKey));
    }

    // Uint8Array => boolean
    this.unsignMessage = function(sig) {
	return nacl.sign.open(sig, this.pSignKey);
    }

    this.isValidSignature = function(signedHash, raw) {
	var a = hash(raw);
	var b = unsignMessage(signedHash);
	return arraysEqual(a, b);
    }

    // Uint8Array => Uint8Array
    this.hash = function(input) {
	var hasher = new BLAKE2s(32);
	hasher.update(input);
	return hasher.digest();
    }
}

/////////////////////////////
// User methods
// (string, string, (User -> ())
function generateKeyPairs(username, password, cb) {
    var hash = new BLAKE2s(32)
    hash.update(nacl.util.decodeUTF8(password))
    salt = nacl.util.decodeUTF8(username)
    scrypt(hash.digest(), salt, 17, 8, 64, 1000, function(keyBytes) {
	var bothBytes = nacl.util.decodeBase64(keyBytes);
	var signBytes = bothBytes.subarray(0, 32);
	var boxBytes = bothBytes.subarray(32, 64);
	return cb(new User(nacl.sign.keyPair.fromSeed(signBytes), nacl.box.keyPair.fromSecretKey(new Uint8Array(boxBytes))));
    }, 'base64');
}

function User(signKeyPair, boxKeyPair) {
    UserPublicKey.call(this, signKeyPair.publicKey, boxKeyPair.publicKey);
    this.sSignKey = signKeyPair.secretKey; // 64 bytes
    this.sBoxKey = boxKeyPair.secretKey; // 32 bytes

    // (Uint8Array, (nonce, sig) => ())
    this.hashAndSignMessage = function(input, cb) {
	signMessage(this.hash(input), cb);
    }

    // (Uint8Array, (nonce, sig) => ())
    this.signMessage = function(input) {
	return nacl.sign(input, this.sSignKey);
    }

    // (Uint8Array, (err, literals) -> ())
    this.decryptMessage = function(cipher, nonce, them, cb) {
	cb(nacl.box.open(cipher, nonce, them.pBoxKey, this.sBoxKey));
    }

    this.getSecretKeys = function() {
	var tmp = new Uint8Array(this.sSignKey.length + this.sBoxKey.length);
	tmp.set(this.sSignKey, 0);
	tmp.set(this.sBoxKey, this.sSignKey.length);
	return tmp;
    }
}

/////////////////////////////
// SymmetricKey methods

// () => Uint8Array
function randomSymmetricKey() {
    return SymmetricKey(nacl.randomBytes(32));
}

// () => Uint8Array
function randomIV() {
    return nacl.randomBytes(24);
}

function SymmetricKey(key) {
    this.key = key;

    // (Uint8Array, Uint8Array[24]) => Uint8Array
    this.encrypt = function(data, nonce) {
	return nacl.secretbox(data, nonce, this.key);
    }

    // (Uint8Array, Uint8Array) => Uint8Array
    this.decrypt = function(cipher, nonce) {
	return nacl.secretbox.open(data, nonce, this.key);
    }
}

/////////////////////////////
// Util methods

// byte[] input and return
function encryptBytesToBytes(input, pubKey) {
    return Java.to(encryptUint8ToUint8(input, pubKey), "byte[]");
}

// byte[] cipher and return
function decryptBytesToBytes(cipher, privKey) {
    return Java.to(decryptUint8ToUint8(cipher, privKey), "byte[]");
}

function get(path, onSuccess, onError) {

    var request = new XMLHttpRequest();
    request.open("GET", path);

    request.onreadystatechange=function()
    {
        if (request.readyState != 4)
            return;

        if (request.status == 200)
            onSuccess(request.response);
        else
            onError(request.status);
    }

    request.send();
}

function post(path, data, onSuccess, onError) {

    var request = new XMLHttpRequest();
    request.open("POST" , path);

    request.onreadystatechange=function()
    {
        if (request.readyState != 4)
            return;

        if (request.status == 200)
            onSuccess(request.response);
        else
            onError(request.status);
    }

    request.send(data);
}

//Java is Big-endian
function readInt(bytes, position) {
    var count = 0;
    for(var i = position; i <  position +4 ; i++)
        count = count << 8 + bytes[i];
    return count;
}

//Java is Big-endian
function writeInt(bytes, position, intValue) {
    intValue |= 0;
    for(var i = position + 3; position <= i ; i--)
        bytes[position] = intValue & 0xff;
        intValue >>= 8;
}

function arraysEqual(leftArray, rightArray) {
    if (leftArray.length != rightArray.length)
        return false;

    for (var i=0; i < leftArray.length; i++)
        if (leftArray[i] != rightArray[i])
            return false;

    return true;
}

function DHTClient() {
    //
    //put
    //
    this.put = function(keyData, valueData, username, sharingKeyData, mapKeyData, proofData, onSuccess, onError) {
            var arrays = [keyData, valueData, username, sharingKeyData, mapKeyData, proofData];
            var prepared  = prepare(arrays);
            post("dht/put", prepared, onSuccess, onError);

    };
    //
    //get
    //
    this.get = function(keyData, onSuccess, onError) {
        post("dht/get", prepared([keyData]), onSuccess, onError);
    };

    //
    //contains
    //
    this.contains = function(keyData, onSuccess, onError) {
            post("dht/contains", prepared([keyData]), onSuccess, onError);
    };
}

function CoreNodeClient() {
        //String -> fn- >fn -> void
        this.getPublicKey = function(username, onSuccess, onError) {
            post("core/getPublicKey", username, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.updateStaticData = function(username, signedHash, staticData, onSuccess, onError) {
            var prepared = prepare([toUint8Array(username), signedHash, staticData]);
            post("core/updateStaticData", prepared, onSuccess, onError);
        };

        //String -> fn- >fn -> void
        this.getStaticData = function(username, onSuccess, onError) {
            var prepared = prepare([toUint8Array(username)]);
            post("core/getStaticData", prepared, onSuccess, onError);
        };

        //Uint8Array -> fn -> fn -> void
        this.getUsername = function(publicKey, onSuccess, onError) {
            post("core/getUsername", publicKey, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.addUsername = function(username, encodedUserKey, signedHash, staticData) {
            var prepared = prepare([toUint8Array(username), encodedUserKey, signedHash, staticData]);
            post("core/addUsername", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> fn -> fn -> void
        this.followRequest = function( target,  encryptedPermission, onSuccess, onError) {
             var prepared = prepare([ target,  encryptedPermission]);
             post("core/followRequest", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> fn -> fn -> void
        this.getFollowRequests = function( username, onSuccess, onError) {
             var prepared = prepare([toUint8Array(username)]);
             post("core/getFollowRequests", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.removeFollowRequest = function( target,  data,  signedHash, onSuccess, onError) {
             var prepared = prepare([ toUint8Array(target),  data,  signedHash]);
             post("core/removeFollowRequest", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.allowSharingKey = function( username,  encodedSharingPublicKey,  signedHash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingPublicKey,  signedHash]);
            post("core/allowSharingKey", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.banSharingKey = function( username,  encodedSharingPublicKey,  signedHash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingPublicKey,  signedHash]);
            post("core/banSharingKey", prepared, onSuccess, onError);
};

        //String -> Uint8Array -> Uint8Array -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.addMetadataBlob = function( username,  encodedSharingPublicKey,  mapKey,  metadataBlob,  sharingKeySignedHash, onSuccess, onError) {
             var prepared = prepare([ toUint8Array(username),  encodedSharingPublicKey,  mapKey,  metadataBlob,  sharingKeySignedHash]);
             post("core/addMetadataBlob", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.removeMetadataBlob = function( username,  encodedSharingKey,  mapKey,  sharingKeySignedMapKey, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingKey,  mapKey,  sharingKeySignedMapKey]);
            post("core/removeMetadataBlob", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.removeUsername = function( username,  userKey,  signedHash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  userKey,  signedHash]);
            post("core/removeUsername", prepared, onSuccess, onError);
        };

        //String -> fn -> fn -> void
        this.getSharingKeys = function( username, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username)]);
            post("core/getSharingKeys", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> fn -> fn -> void
        this.getMetadataBlob = function( username,  encodedSharingKey,  mapKey, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingKey,  mapKey]);
            post("core/getMetadataBlob", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.isFragmentAllowed = function( owner,  encodedSharingKey,  mapkey,  hash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(owner),  encodedSharingKey,  mapkey,  hash]);
            post("core/isFragmentAllowed", prepared, onSuccess, onError);
        };

        //String -> fn -> fn -> void
        this.getQuota = function( user, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(user)]);
            post("core/getQuota", prepared, onSuccess, onError);
        };

        //String -> fn -> fn -> void
        this.getUsage = function(username, onSuccess, onError) {
            var prepared = prepare([toUint8Array(username)]);
            post("core/getUsage", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.getFragmentHashes = function( username, sharingKey, mapKey, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username), sharingKey, mapKey]);
            post("core/getFragmentHashes", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> Uint8Array -> [Uint8Array] -> Uint8Array -> fn -> fn -> void
        this.addFragmentHashes = function(username, encodedSharingPublicKey, mapKey, metadataBlob, allHashes, sharingKeySignedHash) {
                var prepared1 = prepare([toUint8Array(username), encodedSharingPublicKey, mapKey, metadatablob]);
                var prepared2 = prepare(allHashes);
                var prepared3 = prepare([sharingKeySignedHash]);

                var comb = new Uint8Array(prepared1.length + prepared2.length + prepared3.length);
                var current = 0;
                comb.set(prepared1, current);
                current += prepared1.length;
                comb.set(prepared2, current);
                current += prepared2.length;
                comb.set(prepared3, current);

                post("core/addFragmentHashes", comb, onSuccess, onError);

        };

        //String -> Uint8Array -> -> String -> Uint8Array -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.registerFragmentStorage = function(spaceDonor, nodeAddress,  owner,  encodedSharingKey,  hash,  signedKeyPlusHash, onSuccess, onError) {
                var prepared = prepare([toUint8Array(spaceDonor), nodeAddress, toUint8Array(owner), encodedSharingKey, hash, signedKeyPlusHash]);
                post("core/registerFragmentStorage", comb, onSuccess, onError);
        };
}
function UserContext() {

}

//String -> Uint8Array
function toUint8Array(string) {
        var array = new Uint8Array(string.length);
        for (var i=0; i < string.length; i++)
                array[i] = string.charCodeAt(i);
        return array;
}
function prepare(arrays) {
    var length = 0;
    for (var i=0; i < arrays.length; i++)
            length += arrays[i].length;

    var lengths = arrays.length * 4;
    var prepared = new Uint8Array(length + lengths);
    var current = 0;
    for (var i=0; i < arrays.length; i++){
        writeInt(prepared, current, arrays[i].length);
        current +=4;
        var arr = arrays[i];
        prepared.set(arr, current);
        current += arr.length;
    }
    return prepared;
}
<commit_msg>Started adding (jasmine) unit tests for javascript api.<commit_after>if (typeof module !== "undefined")
    var nacl = require("./nacl");

// API for the User interface to use
/////////////////////////////

/////////////////////////////
// UserPublicKey methods
function UserPublicKey(publicSignKey, publicBoxKey) {
    this.pSignKey = publicSignKey; // 32 bytes
    this.pBoxKey = publicBoxKey; // 32 bytes

    // ((err, publicKeyString) -> ())
    this.getPublicKeys = function() {
	var tmp = new Uint8Array(this.pSignKey.length + this.pBoxKey.length);
	tmp.set(this.pSignKey, 0);
	tmp.set(this.pBoxKey, this.pSignKey.length);
	return tmp;
    }

    // (Uint8Array, User, (nonce, cipher) -> ())
    this.encryptMessageFor = function(input, us, cb) {
	var nonce = nacl.randomBytes(24);
	cb(nonce, nacl.box(input, nonce, this.pBoxKey, us.sBoxKey));
    }

    // Uint8Array => boolean
    this.unsignMessage = function(sig) {
	return nacl.sign.open(sig, this.pSignKey);
    }

    this.isValidSignature = function(signedHash, raw) {
	var a = hash(raw);
	var b = unsignMessage(signedHash);
	return arraysEqual(a, b);
    }

    // Uint8Array => Uint8Array
    this.hash = function(input) {
	var hasher = new BLAKE2s(32);
	hasher.update(input);
	return hasher.digest();
    }
}

/////////////////////////////
// User methods
// (string, string, (User -> ())
function generateKeyPairs(username, password, cb) {
    var hash = new BLAKE2s(32)
    hash.update(nacl.util.decodeUTF8(password))
    salt = nacl.util.decodeUTF8(username)
    scrypt(hash.digest(), salt, 17, 8, 64, 1000, function(keyBytes) {
	var bothBytes = nacl.util.decodeBase64(keyBytes);
	var signBytes = bothBytes.subarray(0, 32);
	var boxBytes = bothBytes.subarray(32, 64);
	return cb(new User(nacl.sign.keyPair.fromSeed(signBytes), nacl.box.keyPair.fromSecretKey(new Uint8Array(boxBytes))));
    }, 'base64');
}

function User(signKeyPair, boxKeyPair) {
    UserPublicKey.call(this, signKeyPair.publicKey, boxKeyPair.publicKey);
    this.sSignKey = signKeyPair.secretKey; // 64 bytes
    this.sBoxKey = boxKeyPair.secretKey; // 32 bytes

    // (Uint8Array, (nonce, sig) => ())
    this.hashAndSignMessage = function(input, cb) {
	signMessage(this.hash(input), cb);
    }

    // (Uint8Array, (nonce, sig) => ())
    this.signMessage = function(input) {
	return nacl.sign(input, this.sSignKey);
    }

    // (Uint8Array, (err, literals) -> ())
    this.decryptMessage = function(cipher, nonce, them, cb) {
	cb(nacl.box.open(cipher, nonce, them.pBoxKey, this.sBoxKey));
    }

    this.getSecretKeys = function() {
	var tmp = new Uint8Array(this.sSignKey.length + this.sBoxKey.length);
	tmp.set(this.sSignKey, 0);
	tmp.set(this.sBoxKey, this.sSignKey.length);
	return tmp;
    }
}

/////////////////////////////
// SymmetricKey methods

// () => Uint8Array
function randomSymmetricKey() {
    return SymmetricKey(nacl.randomBytes(32));
}

// () => Uint8Array
function randomIV() {
    return nacl.randomBytes(24);
}

function SymmetricKey(key) {
    this.key = key;

    // (Uint8Array, Uint8Array[24]) => Uint8Array
    this.encrypt = function(data, nonce) {
	return nacl.secretbox(data, nonce, this.key);
    }

    // (Uint8Array, Uint8Array) => Uint8Array
    this.decrypt = function(cipher, nonce) {
	return nacl.secretbox.open(cipher, nonce, this.key);
    }
}

/////////////////////////////
// Util methods

// byte[] input and return
function encryptBytesToBytes(input, pubKey) {
    return Java.to(encryptUint8ToUint8(input, pubKey), "byte[]");
}

// byte[] cipher and return
function decryptBytesToBytes(cipher, privKey) {
    return Java.to(decryptUint8ToUint8(cipher, privKey), "byte[]");
}

function get(path, onSuccess, onError) {

    var request = new XMLHttpRequest();
    request.open("GET", path);

    request.onreadystatechange=function()
    {
        if (request.readyState != 4)
            return;

        if (request.status == 200)
            onSuccess(request.response);
        else
            onError(request.status);
    }

    request.send();
}

function post(path, data, onSuccess, onError) {

    var request = new XMLHttpRequest();
    request.open("POST" , path);

    request.onreadystatechange=function()
    {
        if (request.readyState != 4)
            return;

        if (request.status == 200)
            onSuccess(request.response);
        else
            onError(request.status);
    }

    request.send(data);
}

//Java is Big-endian
function readInt(bytes, position) {
    var count = 0;
    for(var i = position; i <  position +4 ; i++)
        count = count << 8 + bytes[i];
    return count;
}

//Java is Big-endian
function writeInt(bytes, position, intValue) {
    intValue |= 0;
    for(var i = position + 3; position <= i ; i--)
        bytes[position] = intValue & 0xff;
        intValue >>= 8;
}

function arraysEqual(leftArray, rightArray) {
    if (leftArray.length != rightArray.length)
        return false;

    for (var i=0; i < leftArray.length; i++)
        if (leftArray[i] != rightArray[i])
            return false;

    return true;
}

function DHTClient() {
    //
    //put
    //
    this.put = function(keyData, valueData, username, sharingKeyData, mapKeyData, proofData, onSuccess, onError) {
            var arrays = [keyData, valueData, username, sharingKeyData, mapKeyData, proofData];
            var prepared  = prepare(arrays);
            post("dht/put", prepared, onSuccess, onError);

    };
    //
    //get
    //
    this.get = function(keyData, onSuccess, onError) {
        post("dht/get", prepared([keyData]), onSuccess, onError);
    };

    //
    //contains
    //
    this.contains = function(keyData, onSuccess, onError) {
            post("dht/contains", prepared([keyData]), onSuccess, onError);
    };
}

function CoreNodeClient() {
        //String -> fn- >fn -> void
        this.getPublicKey = function(username, onSuccess, onError) {
            post("core/getPublicKey", username, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.updateStaticData = function(username, signedHash, staticData, onSuccess, onError) {
            var prepared = prepare([toUint8Array(username), signedHash, staticData]);
            post("core/updateStaticData", prepared, onSuccess, onError);
        };

        //String -> fn- >fn -> void
        this.getStaticData = function(username, onSuccess, onError) {
            var prepared = prepare([toUint8Array(username)]);
            post("core/getStaticData", prepared, onSuccess, onError);
        };

        //Uint8Array -> fn -> fn -> void
        this.getUsername = function(publicKey, onSuccess, onError) {
            post("core/getUsername", publicKey, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.addUsername = function(username, encodedUserKey, signedHash, staticData) {
            var prepared = prepare([toUint8Array(username), encodedUserKey, signedHash, staticData]);
            post("core/addUsername", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> fn -> fn -> void
        this.followRequest = function( target,  encryptedPermission, onSuccess, onError) {
             var prepared = prepare([ target,  encryptedPermission]);
             post("core/followRequest", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> fn -> fn -> void
        this.getFollowRequests = function( username, onSuccess, onError) {
             var prepared = prepare([toUint8Array(username)]);
             post("core/getFollowRequests", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.removeFollowRequest = function( target,  data,  signedHash, onSuccess, onError) {
             var prepared = prepare([ toUint8Array(target),  data,  signedHash]);
             post("core/removeFollowRequest", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.allowSharingKey = function( username,  encodedSharingPublicKey,  signedHash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingPublicKey,  signedHash]);
            post("core/allowSharingKey", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.banSharingKey = function( username,  encodedSharingPublicKey,  signedHash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingPublicKey,  signedHash]);
            post("core/banSharingKey", prepared, onSuccess, onError);
};

        //String -> Uint8Array -> Uint8Array -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.addMetadataBlob = function( username,  encodedSharingPublicKey,  mapKey,  metadataBlob,  sharingKeySignedHash, onSuccess, onError) {
             var prepared = prepare([ toUint8Array(username),  encodedSharingPublicKey,  mapKey,  metadataBlob,  sharingKeySignedHash]);
             post("core/addMetadataBlob", prepared, onSuccess, onError);
        };

        //String -> Uint8Array -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.removeMetadataBlob = function( username,  encodedSharingKey,  mapKey,  sharingKeySignedMapKey, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingKey,  mapKey,  sharingKeySignedMapKey]);
            post("core/removeMetadataBlob", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.removeUsername = function( username,  userKey,  signedHash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  userKey,  signedHash]);
            post("core/removeUsername", prepared, onSuccess, onError);
        };

        //String -> fn -> fn -> void
        this.getSharingKeys = function( username, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username)]);
            post("core/getSharingKeys", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> fn -> fn -> void
        this.getMetadataBlob = function( username,  encodedSharingKey,  mapKey, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username),  encodedSharingKey,  mapKey]);
            post("core/getMetadataBlob", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.isFragmentAllowed = function( owner,  encodedSharingKey,  mapkey,  hash, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(owner),  encodedSharingKey,  mapkey,  hash]);
            post("core/isFragmentAllowed", prepared, onSuccess, onError);
        };

        //String -> fn -> fn -> void
        this.getQuota = function( user, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(user)]);
            post("core/getQuota", prepared, onSuccess, onError);
        };

        //String -> fn -> fn -> void
        this.getUsage = function(username, onSuccess, onError) {
            var prepared = prepare([toUint8Array(username)]);
            post("core/getUsage", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> fn -> fn -> void
        this.getFragmentHashes = function( username, sharingKey, mapKey, onSuccess, onError) {
            var prepared = prepare([ toUint8Array(username), sharingKey, mapKey]);
            post("core/getFragmentHashes", prepared, onSuccess, onError);
        };

        //String  -> Uint8Array  -> Uint8Array -> Uint8Array -> [Uint8Array] -> Uint8Array -> fn -> fn -> void
        this.addFragmentHashes = function(username, encodedSharingPublicKey, mapKey, metadataBlob, allHashes, sharingKeySignedHash) {
                var prepared1 = prepare([toUint8Array(username), encodedSharingPublicKey, mapKey, metadatablob]);
                var prepared2 = prepare(allHashes);
                var prepared3 = prepare([sharingKeySignedHash]);

                var comb = new Uint8Array(prepared1.length + prepared2.length + prepared3.length);
                var current = 0;
                comb.set(prepared1, current);
                current += prepared1.length;
                comb.set(prepared2, current);
                current += prepared2.length;
                comb.set(prepared3, current);

                post("core/addFragmentHashes", comb, onSuccess, onError);

        };

        //String -> Uint8Array -> -> String -> Uint8Array -> Uint8Array -> Uint8Array -> fn -> fn -> void
        this.registerFragmentStorage = function(spaceDonor, nodeAddress,  owner,  encodedSharingKey,  hash,  signedKeyPlusHash, onSuccess, onError) {
                var prepared = prepare([toUint8Array(spaceDonor), nodeAddress, toUint8Array(owner), encodedSharingKey, hash, signedKeyPlusHash]);
                post("core/registerFragmentStorage", comb, onSuccess, onError);
        };
}
function UserContext() {

}

//String -> Uint8Array
function toUint8Array(string) {
        var array = new Uint8Array(string.length);
        for (var i=0; i < string.length; i++)
                array[i] = string.charCodeAt(i);
        return array;
}
function prepare(arrays) {
    var length = 0;
    for (var i=0; i < arrays.length; i++)
            length += arrays[i].length;

    var lengths = arrays.length * 4;
    var prepared = new Uint8Array(length + lengths);
    var current = 0;
    for (var i=0; i < arrays.length; i++){
        writeInt(prepared, current, arrays[i].length);
        current +=4;
        var arr = arrays[i];
        prepared.set(arr, current);
        current += arr.length;
    }
    return prepared;
}

//module.exports.encryptStringToHex = encryptStringToHex;
//module.exports.decryptHexToString = decryptHexToString;

if (typeof module !== "undefined"){
    module.exports.randomSymmetricKey = randomSymmetricKey;
    module.exports.SymmetricKey = SymmetricKey;
}

<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.services')
    .service("MapService", [function () {
        var self = this;

        self.map = null;
        self.osmLayer = null;

        self.initMap = function () {
            self.map = new L.Map('map');

            // create the tile layer with correct attribution
            var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
            var osmAttrib = 'Map data © OpenStreetMap contributors';
            self.osmLayer = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 19, attribution: osmAttrib});

            // start the map in South-East England
            self.map.setView([49.8327786, 23.9420238], 11);
            self.map.addLayer(self.osmLayer);
            return map;
        };

        self.renderMarkers = function (geoJSON) {
            self.map.eachLayer(function (layer) {
                if (self.osmLayer !== layer) {
                    self.map.removeLayer(layer);
                }
            });
            var markers = L.markerClusterGroup({
                zoomToBoundsOnClick:false,
                animate:true,
                animateAddingMarkers:true,
                showCoverageOnHover:false});

            for (var i = 0; i < geoJSON.features.length; ++i) {
                var feature = geoJSON.features[i];
                var c = L.marker(new L.LatLng(feature.geometry.coordinates[1], feature.geometry.coordinates[0])
                );
                markers.addLayer(c);
            }
            self.map.addLayer(markers);

            markers.on('clusterclick', function (a) {
                if (self.map.getZoom()<=15){
                    a.layer.unspiderfied;
                }else{
                a.layer.spiderfy();
                }
            });
        };

    }
    ]);
<commit_msg>close #24<commit_after>'use strict';

angular.module('myApp.services')
    .service("MapService", [function () {
        var self = this;

        self.map = null;
        self.osmLayer = null;

        self.initMap = function () {
            self.map = new L.Map('map');

            // create the tile layer with correct attribution
            var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
            var osmAttrib = 'Map data © OpenStreetMap contributors';
            self.osmLayer = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 19, attribution: osmAttrib});

            // start the map in South-East England
            self.map.setView([49.8327786, 23.9420238], 11);
            self.map.addLayer(self.osmLayer);
            return map;
        };

        self.renderMarkers = function (geoJSON) {
            self.map.eachLayer(function (layer) {
                if (self.osmLayer !== layer) {
                    self.map.removeLayer(layer);
                }
            });
            var markers = L.markerClusterGroup({
                zoomToBoundsOnClick:true,
                animate:true,
                animateAddingMarkers:true,
                showCoverageOnHover:false});

            for (var i = 0; i < geoJSON.features.length; ++i) {
                var feature = geoJSON.features[i];
                var c = L.marker(new L.LatLng(feature.geometry.coordinates[1], feature.geometry.coordinates[0])
                );
                markers.addLayer(c);
            }
            self.map.addLayer(markers);

            markers.on('clusterclick', function (a) {
                if (self.map.getZoom()<=15){
                    a.layer.unspiderfied;
                }else{
                a.layer.spiderfy();
                }
            });
        };

    }
    ]);
<|endoftext|>


<commit_before>/*!
 * Amplify Request @VERSION
 *
 * Copyright 2011 appendTo LLC. (http://appendto.com/team)
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 *
 * http://amplifyjs.com
 */
(function( amplify, undefined ) {

function noop() {}
function isFunction( obj ) {
	return ({}).toString.call( obj ) === "[object Function]";
}

amplify.request = function( resourceId, data, callback ) {
	// default to an empty hash just so we can handle a missing resourceId
	// in one place
	var settings = resourceId || {};

	if ( typeof settings === "string" ) {
		if ( isFunction( data ) ) {
			callback = data;
			data = {};
		}
		settings = {
			resourceId: resourceId,
			data: data || {},
			success: callback
		};
	}

	var request = { abort: noop },
		resource = amplify.request.resources[ settings.resourceId ],
		success = settings.success || noop,
		error = settings.error || noop;
	settings.success = function( data, extra, status ) {
		amplify.publish( "request.success", settings, data, extra, status );
		amplify.publish( "request.complete", settings, data, extra, status );
		success.apply( this, arguments );
	};
	settings.error = function( data, extra, status ) {
		amplify.publish( "request.error", settings, data, extra, status );
		amplify.publish( "request.complete", settings, data, extra, status );
		error.apply( this, arguments );
	};

	if ( !resource ) {
		if ( !settings.resourceId ) {
			throw "amplify.request: no resourceId provided";
		}
		throw "amplify.request: unknown resourceId: " + settings.resourceId;
	}

	if ( amplify.publish( "request.before", settings ) ) {
		amplify.request.resources[ settings.resourceId ]( settings, request );
	}

	return request;
};

amplify.request.types = {};
amplify.request.resources = {};
amplify.request.define = function( resourceId, type, settings ) {
	if ( typeof type === "string" ) {
		if ( !( type in amplify.request.types ) ) {
			throw "amplify.request.define: unknown type: " + type;
		}

		settings.resourceId = resourceId;
		amplify.request.resources[ resourceId ] =
			amplify.request.types[ type ]( settings );
	} else {
		// no pre-processor or settings for one-off types (don't invoke)
		amplify.request.resources[ resourceId ] = type;
	}
};

}( amplify ) );

(function( amplify, $, undefined ) {

amplify.request.types.ajax = function( defnSettings ) {
	defnSettings = $.extend({
		type: "GET"
	}, defnSettings );

	return function( settings, request ) {
		var url = defnSettings.url,
			data = settings.data,
			abort = request.abort,
			ajaxSettings,
			regex,
			xhr;

		if ( typeof data !== "string" ) {
			data = $.extend( true, {}, defnSettings.data, data );
			$.each( data, function( key, value ) {
				regex = new RegExp( "{" + key + "}", "g");
				if ( regex.test( url ) ) {
					url = url.replace( regex, value );
					delete data[ key ];
				}
			});
		}

		xhr = $.ajax($.extend( {}, defnSettings, {
			url: url,
			type: defnSettings.type,
			data: data,
			dataType: defnSettings.dataType,
			success: function( data, status, xhr ) {
				settings.success( data, xhr, status );
			},
			// data parameter is for custom overrides that proxy this function
			error: function( xhr, status, error, data ) {
				if ( data === undefined ) {
					// TODO: add support for ajax errors with data
					data = null;
				}
				settings.error( data, xhr, status );
			},
			beforeSend: function( xhr, ajaxSettings ) {
				var ret = defnSettings.beforeSend ?
					defnSettings.beforeSend.apply( this, arguments ) : true;
				return ret && amplify.publish( "request.before.ajax",
					defnSettings, settings, ajaxSettings, xhr );
			}
		}) );

		request.abort = function() {
			xhr.abort();
			abort.call( this );
		};
	};
};

var cache = amplify.request.cache = {
	_key: function( resourceId, data ) {
		var length = data.length,
			i = 0,
			checksum = chunk();

		while ( i < length ) {
			checksum ^= chunk();
		}

		function chunk() {
			return data.charCodeAt( i++ ) << 24 |
				data.charCodeAt( i++ ) << 16 |
				data.charCodeAt( i++ ) << 8 |
				data.charCodeAt( i++ ) << 0;
		}

		return "request-" + resourceId + "-" + checksum;
	},

	_default: (function() {
		var memoryStore = {};
		return function( resource, settings, ajaxSettings ) {
			// data is already converted to a string by the time we get here
			var cacheKey = cache._key( resource.resourceId, ajaxSettings.data ),
				duration = resource.cache;

			if ( cacheKey in memoryStore ) {
				ajaxSettings.success( memoryStore[ cacheKey ] );
				return false;
			}
			var success = ajaxSettings.success;
			ajaxSettings.success = function( data ) {
				memoryStore[ cacheKey ] = data;
				if ( typeof duration === "number" ) {
					setTimeout(function() {
						delete memoryStore[ cacheKey ];
					}, duration );
				}
				success.apply( this, arguments );
			};
		};
	}())
};

if ( amplify.store ) {
	$.each( amplify.store.types, function( type ) {
		cache[ type ] = function( resource, settings, ajaxSettings ) {
			var cacheKey = cache._key( resource.resourceId, ajaxSettings.data ),
				cached = amplify.store[ type ]( cacheKey );

			if ( cached ) {
				ajaxSettings.success( cached );
				return false;
			}
			var success = ajaxSettings.success;
			ajaxSettings.success = function( data ) {
				var expires = ( 'expires' in resource ) ? resource.expires : undefined;
				if ( expires ) {
					delete resource[ 'expires' ];
				}
				amplify.store[ type]( cacheKey, data , { expires: expires } );
				success.apply( this, arguments );
			};
		};
	});
	cache.persist = cache[ amplify.store.type ];
}

amplify.subscribe( "request.before.ajax", function( resource ) {
	var cacheType = resource.cache;
	if ( cacheType ) {
		return cache[ cacheType in cache ? cacheType : "_default" ]
			.apply( this, arguments );
	}
});

amplify.request.decoders = {
	// http://labs.omniti.com/labs/jsend
	jsend: function( data, status, xhr, success, error ) {
		if ( data.status === "success" ) {
			success( data.data );
		} else if ( data.status === "fail" ) {
			error( data.data, "fail" );
		} else if ( data.status === "error" ) {
			delete data.status;
			error( data, "error" );
		}
	}
};

amplify.subscribe( "request.before.ajax", function( resource, settings, ajaxSettings ) {
	var _success = ajaxSettings.success,
		_error = ajaxSettings.error,
		decoder = $.isFunction( resource.decoder )
			? resource.decoder
			: resource.decoder in amplify.request.decoders
				? amplify.request.decoders[ resource.decoder ]
				: amplify.request.decoders._default;

	if ( !decoder ) {
		return;
	}

	function success( xhr ) {
		return function( data, status ) {
			_success( data, status || "success", xhr );
		};
	}
	function error( xhr, _status ) {
		return function( data, status ) {
			_error( xhr, status || _status, null, data );
		};
	}
	ajaxSettings.success = function( data, status, xhr ) {
		decoder( data, status, xhr, success( xhr ), error( xhr, "error" ) );
	};
	ajaxSettings.error = function( xhr, status ) {
		decoder( null, status, xhr, success( xhr ), error( xhr, status ) );
	};
});

}( amplify, jQuery ) );
<commit_msg>removed deleting expiration key, there is no need to do that, ever<commit_after>/*!
 * Amplify Request @VERSION
 *
 * Copyright 2011 appendTo LLC. (http://appendto.com/team)
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 *
 * http://amplifyjs.com
 */
(function( amplify, undefined ) {

function noop() {}
function isFunction( obj ) {
	return ({}).toString.call( obj ) === "[object Function]";
}

amplify.request = function( resourceId, data, callback ) {
	// default to an empty hash just so we can handle a missing resourceId
	// in one place
	var settings = resourceId || {};

	if ( typeof settings === "string" ) {
		if ( isFunction( data ) ) {
			callback = data;
			data = {};
		}
		settings = {
			resourceId: resourceId,
			data: data || {},
			success: callback
		};
	}

	var request = { abort: noop },
		resource = amplify.request.resources[ settings.resourceId ],
		success = settings.success || noop,
		error = settings.error || noop;
	settings.success = function( data, extra, status ) {
		amplify.publish( "request.success", settings, data, extra, status );
		amplify.publish( "request.complete", settings, data, extra, status );
		success.apply( this, arguments );
	};
	settings.error = function( data, extra, status ) {
		amplify.publish( "request.error", settings, data, extra, status );
		amplify.publish( "request.complete", settings, data, extra, status );
		error.apply( this, arguments );
	};

	if ( !resource ) {
		if ( !settings.resourceId ) {
			throw "amplify.request: no resourceId provided";
		}
		throw "amplify.request: unknown resourceId: " + settings.resourceId;
	}

	if ( amplify.publish( "request.before", settings ) ) {
		amplify.request.resources[ settings.resourceId ]( settings, request );
	}

	return request;
};

amplify.request.types = {};
amplify.request.resources = {};
amplify.request.define = function( resourceId, type, settings ) {
	if ( typeof type === "string" ) {
		if ( !( type in amplify.request.types ) ) {
			throw "amplify.request.define: unknown type: " + type;
		}

		settings.resourceId = resourceId;
		amplify.request.resources[ resourceId ] =
			amplify.request.types[ type ]( settings );
	} else {
		// no pre-processor or settings for one-off types (don't invoke)
		amplify.request.resources[ resourceId ] = type;
	}
};

}( amplify ) );

(function( amplify, $, undefined ) {

amplify.request.types.ajax = function( defnSettings ) {
	defnSettings = $.extend({
		type: "GET"
	}, defnSettings );

	return function( settings, request ) {
		var url = defnSettings.url,
			data = settings.data,
			abort = request.abort,
			ajaxSettings,
			regex,
			xhr;

		if ( typeof data !== "string" ) {
			data = $.extend( true, {}, defnSettings.data, data );
			$.each( data, function( key, value ) {
				regex = new RegExp( "{" + key + "}", "g");
				if ( regex.test( url ) ) {
					url = url.replace( regex, value );
					delete data[ key ];
				}
			});
		}

		xhr = $.ajax($.extend( {}, defnSettings, {
			url: url,
			type: defnSettings.type,
			data: data,
			dataType: defnSettings.dataType,
			success: function( data, status, xhr ) {
				settings.success( data, xhr, status );
			},
			// data parameter is for custom overrides that proxy this function
			error: function( xhr, status, error, data ) {
				if ( data === undefined ) {
					// TODO: add support for ajax errors with data
					data = null;
				}
				settings.error( data, xhr, status );
			},
			beforeSend: function( xhr, ajaxSettings ) {
				var ret = defnSettings.beforeSend ?
					defnSettings.beforeSend.apply( this, arguments ) : true;
				return ret && amplify.publish( "request.before.ajax",
					defnSettings, settings, ajaxSettings, xhr );
			}
		}) );

		request.abort = function() {
			xhr.abort();
			abort.call( this );
		};
	};
};

var cache = amplify.request.cache = {
	_key: function( resourceId, data ) {
		var length = data.length,
			i = 0,
			checksum = chunk();

		while ( i < length ) {
			checksum ^= chunk();
		}

		function chunk() {
			return data.charCodeAt( i++ ) << 24 |
				data.charCodeAt( i++ ) << 16 |
				data.charCodeAt( i++ ) << 8 |
				data.charCodeAt( i++ ) << 0;
		}

		return "request-" + resourceId + "-" + checksum;
	},

	_default: (function() {
		var memoryStore = {};
		return function( resource, settings, ajaxSettings ) {
			// data is already converted to a string by the time we get here
			var cacheKey = cache._key( resource.resourceId, ajaxSettings.data ),
				duration = resource.cache;

			if ( cacheKey in memoryStore ) {
				ajaxSettings.success( memoryStore[ cacheKey ] );
				return false;
			}
			var success = ajaxSettings.success;
			ajaxSettings.success = function( data ) {
				memoryStore[ cacheKey ] = data;
				if ( typeof duration === "number" ) {
					setTimeout(function() {
						delete memoryStore[ cacheKey ];
					}, duration );
				}
				success.apply( this, arguments );
			};
		};
	}())
};

if ( amplify.store ) {
	$.each( amplify.store.types, function( type ) {
		cache[ type ] = function( resource, settings, ajaxSettings ) {
			var cacheKey = cache._key( resource.resourceId, ajaxSettings.data ),
				cached = amplify.store[ type ]( cacheKey );

			if ( cached ) {
				ajaxSettings.success( cached );
				return false;
			}
			var success = ajaxSettings.success;
			ajaxSettings.success = function( data ) {
				var expires = ( 'expires' in resource ) ? resource.expires : undefined;

				amplify.store[ type]( cacheKey, data , { expires: expires } );
				success.apply( this, arguments );
			};
		};
	});
	cache.persist = cache[ amplify.store.type ];
}

amplify.subscribe( "request.before.ajax", function( resource ) {
	var cacheType = resource.cache;
	if ( cacheType ) {
		return cache[ cacheType in cache ? cacheType : "_default" ]
			.apply( this, arguments );
	}
});

amplify.request.decoders = {
	// http://labs.omniti.com/labs/jsend
	jsend: function( data, status, xhr, success, error ) {
		if ( data.status === "success" ) {
			success( data.data );
		} else if ( data.status === "fail" ) {
			error( data.data, "fail" );
		} else if ( data.status === "error" ) {
			delete data.status;
			error( data, "error" );
		}
	}
};

amplify.subscribe( "request.before.ajax", function( resource, settings, ajaxSettings ) {
	var _success = ajaxSettings.success,
		_error = ajaxSettings.error,
		decoder = $.isFunction( resource.decoder )
			? resource.decoder
			: resource.decoder in amplify.request.decoders
				? amplify.request.decoders[ resource.decoder ]
				: amplify.request.decoders._default;

	if ( !decoder ) {
		return;
	}

	function success( xhr ) {
		return function( data, status ) {
			_success( data, status || "success", xhr );
		};
	}
	function error( xhr, _status ) {
		return function( data, status ) {
			_error( xhr, status || _status, null, data );
		};
	}
	ajaxSettings.success = function( data, status, xhr ) {
		decoder( data, status, xhr, success( xhr ), error( xhr, "error" ) );
	};
	ajaxSettings.error = function( xhr, status ) {
		decoder( null, status, xhr, success( xhr ), error( xhr, status ) );
	};
});

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


<commit_before>function attachAndRun (target, event, listener, capture = false) {
  const events = event.split(' ')
  events.forEach((event) => event && target.addEventListener(event, listener, capture))
  listener.call(target)
  return {
    destroy() {
      events.forEach((event) => event && target.removeEventListener(event, listener, capture))
    }
  }
}

function getType (el) {
  const tagName = el.tagName.toLowerCase()
  const type = el.getAttribute('type')
  return `input-type-${tagName !== 'input' ? tagName : type}`
}

function input (el, conf = {}) {
  const target = conf.target ? conf.target(el) : el

  function setChangedStates (event) {
    const isFilled = el.value.trim() !== ''
    target.classList.toggle('input-filled', isFilled)
    target.classList.toggle('input-empty', !isFilled)

    if (event) {
      target.classList.toggle('input-changed', true)
    }
  }

  function setFocusStates () {
    const isFocused = document.activeElement === el

    if (!isFocused && target.classList.contains('input-focused')) {
      target.classList.add('input-had-focus')
    }

    target.classList.toggle('input-focused', isFocused)
    target.classList.toggle('input-blurred', !isFocused)
  }

  const inputListeners = attachAndRun(el, 'input change', setChangedStates)
  const focusListeners = attachAndRun(el, 'focus blur', setFocusStates)

  const typeClass = getType(el)
  target.classList.toggle(typeClass, true)

  return {
    remove() {
      inputListeners.destroy()
      focusListeners.destroy()
      target.classList.remove(
        'input-filled',
        'input-empty',
        'input-changed',
        'input-focused',
        'input-had-focus',
        'input-blurred',
        typeClass
      )
    }
  }
}

input.NAME = 'input'

export default input
<commit_msg>fix access to conf object<commit_after>function attachAndRun (target, event, listener, capture = false) {
  const events = event.split(' ')
  events.forEach((event) => event && target.addEventListener(event, listener, capture))
  listener.call(target)
  return {
    destroy() {
      events.forEach((event) => event && target.removeEventListener(event, listener, capture))
    }
  }
}

function getType (el) {
  const tagName = el.tagName.toLowerCase()
  const type = el.getAttribute('type')
  return `input-type-${tagName !== 'input' ? tagName : type}`
}

function input (el, opts = {}) {
  const target = opts.conf.target ? opts.conf.target(el) : el

  function setChangedStates (event) {
    const isFilled = el.value.trim() !== ''
    target.classList.toggle('input-filled', isFilled)
    target.classList.toggle('input-empty', !isFilled)

    if (event) {
      target.classList.toggle('input-changed', true)
    }
  }

  function setFocusStates () {
    const isFocused = document.activeElement === el

    if (!isFocused && target.classList.contains('input-focused')) {
      target.classList.add('input-had-focus')
    }

    target.classList.toggle('input-focused', isFocused)
    target.classList.toggle('input-blurred', !isFocused)
  }

  const inputListeners = attachAndRun(el, 'input change', setChangedStates)
  const focusListeners = attachAndRun(el, 'focus blur', setFocusStates)

  const typeClass = getType(el)
  target.classList.toggle(typeClass, true)

  return {
    remove() {
      inputListeners.destroy()
      focusListeners.destroy()
      target.classList.remove(
        'input-filled',
        'input-empty',
        'input-changed',
        'input-focused',
        'input-had-focus',
        'input-blurred',
        typeClass
      )
    }
  }
}

input.NAME = 'input'

export default input
<|endoftext|>


<commit_before>(function() {

  'use strict';

  function sqlService($q, $timeout, transformService) {

    var db = null;

    var onDeviceReady = function() {
      if (typeof window.sqlitePlugin !== 'undefined') {
        db = window.sqlitePlugin.openDatabase({
          name: 'onibus.db',
          createFromLocation: 1
        });
      } else if (window.openDatabase) {
        db = window.openDatabase('onibus.db', '1', 'db', 1024 * 1024 * 100);
      }
    };

    var $public = {};

    $public.isAvailable = function() {
      return db;
    };

    $public.init = function() {

      var def = $q.defer();

      // are we running in native app or in a browser?
      window.isphone = false;

      if (document.URL.indexOf('http://') === -1 &&
          document.URL.indexOf('https://') === -1) {
        window.isphone = true;
      }

      if ( window.isphone ) {
        document.addEventListener('deviceready', function() {

          onDeviceReady();

          $timeout(function() {
            def.resolve();
          }, 1);
        }, false);
      } else {

        onDeviceReady();
        $timeout(function() {
          def.resolve();
        }, 1);
      }

      return def.promise;
    };

    $public.query = function(q) {
      var deferred = $q.defer();
      db.transaction(function(tx) {
        tx.executeSql(q.text, q.values, function(tx, results) {
          deferred.resolve(results);
        }, function(tx, e) {
          deferred.reject(e);
        });
      });
      return deferred.promise;
    };

    $public.fetch = function(q) {

      var deferred = $q.defer();

      $public.query(q).then(function(res) {

        var obj = transformService.singleTransform(res);
        deferred.resolve(obj);

      }, deferred.reject);

      return deferred.promise;
    };

    $public.getAll = function(q) {

      var deferred = $q.defer();

      $public.query(q).then(function(res) {

        var obj = transformService.transformObject(res);
        deferred.resolve(obj);

      }, deferred.reject);

      return deferred.promise;
    };

    $public.multQuery = function(queries) {
      var requests = [], def = $q.defer();

      db.transaction(function(tx) {
        angular.forEach(queries, function(q) {
          var deferred = $q.defer();

          tx.executeSql(q.text, q.values, function(tx, results) {
            deferred.resolve(results);
          }, function(tx, e) {
            deferred.reject(e);
          });

          requests.push(deferred.promise);
        });

        def.resolve();
      });

      return def.promise.then(function() {
        return $q.all(requests);
      });
    };

    $public.batchInsert = function(tableName, dados) {
      var sql1 = squel.insert().into(tableName), queries = [];

      angular.forEach(dados, function(fields) {
        var sql2 = sql1.clone().setFields(fields).toParam();
        queries.push(sql2);
      });

      return this.multQuery(queries);
    };

    return $public;
  }

  sqlService.$inject = ['$q', '$timeout', 'transformService'];

  angular.module('services.sql', [
    'services.transform'
  ])
  .factory('sqlService', sqlService);

}());
<commit_msg>Updated sqlite plugin parameters<commit_after>(function() {

  'use strict';

  function sqlService($q, $timeout, transformService) {

    var db = null;

    var onDeviceReady = function() {
      if (typeof window.sqlitePlugin !== 'undefined') {
        db = window.sqlitePlugin.openDatabase({
          name: 'onibus.db',
          location: 'default',
          createFromLocation: 1
        });
      } else if (window.openDatabase) {
        db = window.openDatabase('onibus.db', '1', 'db', 1024 * 1024 * 100);
      }
    };

    var $public = {};

    $public.isAvailable = function() {
      return db;
    };

    $public.init = function() {

      var def = $q.defer();

      // are we running in native app or in a browser?
      window.isphone = false;

      if (document.URL.indexOf('http://') === -1 &&
          document.URL.indexOf('https://') === -1) {
        window.isphone = true;
      }

      if ( window.isphone ) {
        document.addEventListener('deviceready', function() {

          onDeviceReady();

          $timeout(function() {
            def.resolve();
          }, 1);
        }, false);
      } else {

        onDeviceReady();
        $timeout(function() {
          def.resolve();
        }, 1);
      }

      return def.promise;
    };

    $public.query = function(q) {
      var deferred = $q.defer();
      db.transaction(function(tx) {
        tx.executeSql(q.text, q.values, function(tx, results) {
          deferred.resolve(results);
        }, function(tx, e) {
          deferred.reject(e);
        });
      });
      return deferred.promise;
    };

    $public.fetch = function(q) {

      var deferred = $q.defer();

      $public.query(q).then(function(res) {

        var obj = transformService.singleTransform(res);
        deferred.resolve(obj);

      }, deferred.reject);

      return deferred.promise;
    };

    $public.getAll = function(q) {

      var deferred = $q.defer();

      $public.query(q).then(function(res) {

        var obj = transformService.transformObject(res);
        deferred.resolve(obj);

      }, deferred.reject);

      return deferred.promise;
    };

    $public.multQuery = function(queries) {
      var requests = [], def = $q.defer();

      db.transaction(function(tx) {
        angular.forEach(queries, function(q) {
          var deferred = $q.defer();

          tx.executeSql(q.text, q.values, function(tx, results) {
            deferred.resolve(results);
          }, function(tx, e) {
            deferred.reject(e);
          });

          requests.push(deferred.promise);
        });

        def.resolve();
      });

      return def.promise.then(function() {
        return $q.all(requests);
      });
    };

    $public.batchInsert = function(tableName, dados) {
      var sql1 = squel.insert().into(tableName), queries = [];

      angular.forEach(dados, function(fields) {
        var sql2 = sql1.clone().setFields(fields).toParam();
        queries.push(sql2);
      });

      return this.multQuery(queries);
    };

    return $public;
  }

  sqlService.$inject = ['$q', '$timeout', 'transformService'];

  angular.module('services.sql', [
    'services.transform'
  ])
  .factory('sqlService', sqlService);

}());
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('app')
        //.constant('apiUrl', "https://iotplatformbackend.herokuapp.com/");
    .constant('apiUrl', "http://127.0.0.1:9090/");
})();
<commit_msg>changed url<commit_after>(function() {
    'use strict';

    angular
        .module('app')
        .constant('apiUrl', "https://iotplatformbackend.herokuapp.com/");
    //.constant('apiUrl', "http://127.0.0.1:9090/");
})();
<|endoftext|>


<commit_before>$('#clear-all').click( function() {
  $('#taskTitle-data').val("");
  $('#task-desc').val("");
  $('#urgent-data').val("");

  console.log("All cleaned");
});

$('#update-task').click( function() {
  task_title = $('#taskTitle-data').val();
  task_desc = $('#task-desc').val();
  task_urgency = $('#urgent-data').val();
  reservation = $('#reservation').val();
  task_category = $('#category-data').val();
  contactPersons = $('#contactPersons').val();
  console.log("in update");

  data = { "task_id": task_id, "username": username, "title": task_title, "description": task_desc,
                "due_date": reservation };

  userData = JSON.stringify(data);

  NProgress.set(0.0);

  $.ajax({
    type: 'POST',
    url: '/api/editTask/'+ task_id + '/',
    contentType: 'application/json',

    success: function(result) {
      console.log(result);
      console.log(result.response);

      NProgress.set(1.0);

      $.gritter.add({
        title: 'Task Updated',
        text: 'Task Successfully Updated',
        class_name: 'success'
      });

    },
    fail: function(result) {
      alert('Failed to send Data');
    },

    data: userData
  });

  console.log(userData);
});

$('#add-task').click( function() {
  task_title = $('#taskTitle-data').val();
  task_desc = $('#task-desc').val();
  task_urgency = $('#urgent-data').val();
  date_data = $('#date-data').val();
  task_category = $('#category-data').val();

  if ($('#taskTitle-data').val() == "") {
    alert('Your task needs a title');
    return 0;
  }

  if (typeof($('#taskTitle-data').val()) != "string") {
    alert('Your task needs in text form');
    return 0;
  }

  if ($('#task-desc').val() == "") {
    alert('Your Task needs a description');
    return 0;
  }

  if (typeof($('#task-desc').val()) != "string") {
    alert('Your description needs to be in text form');
    return 0;
  }

  if ($('#date-data').val() == "") {
    alert('Your Task needs a date');
    return 0;
  }

  if (typeof($('#date-data').val()) != "string") {
    alert('Your date needs to be in text form');
    return 0;
  }

  data = { "task_id": task_id, "username": username, "title": task_title, "description": task_desc, "urgency": task_urgency,
                "due_date": date_data, "category": task_category };

  userData = JSON.stringify(data);

  NProgress.set(0.0);
  $.ajax({
    type: 'PUT',
    url: '/api/editTask/'+task_id + '/',
    contentType: 'application/json',

    success: function(result) {
      console.log(result);
      NProgress.set(1.0);
      var n = noty({text: 'Task Updated!', layout: "topRight", type: "information"});

    },
    fail: function(result) {
      alert('Failed to send Data');
      var n = noty({text: 'Task Update Failed!', layout: "topRight", type: "information"});
    },

    data: userData
  });

  console.log(userData);
});<commit_msg>taskupdate<commit_after>$('#update-task').click( function() {
  task_title = $('#taskTitle-data').val();
  task_desc = $('#task-desc').val();
  task_urgency = $('#urgent-data').val();
  reservation = $('#reservation').val();
  task_category = $('#category-data').val();
  contactPersons = $('#contactPersons').val();
  console.log("in update");

  data = { "task_id": task_id, "username": username, "title": task_title, "description": task_desc,
                "due_date": reservation };

  userData = JSON.stringify(data);

  NProgress.set(0.0);

  $.ajax({
    type: 'POST',
    url: '/api/editTask/'+ task_id + '/',
    contentType: 'application/json',

    success: function(result) {
      console.log(result);
      console.log(result.response);

      NProgress.set(1.0);

      $.gritter.add({
        title: 'Task Updated',
        text: 'Task Successfully Updated',
        class_name: 'success'
      });

    },
    fail: function(result) {
      alert('Failed to send Data');
    },

    data: userData
  });

  console.log(userData);
});

$('#add-task').click( function() {
  task_title = $('#taskTitle-data').val();
  task_desc = $('#task-desc').val();
  task_urgency = $('#urgent-data').val();
  date_data = $('#date-data').val();
  task_category = $('#category-data').val();

  if ($('#taskTitle-data').val() == "") {
    alert('Your task needs a title');
    return 0;
  }

  if (typeof($('#taskTitle-data').val()) != "string") {
    alert('Your task needs in text form');
    return 0;
  }

  if ($('#task-desc').val() == "") {
    alert('Your Task needs a description');
    return 0;
  }

  if (typeof($('#task-desc').val()) != "string") {
    alert('Your description needs to be in text form');
    return 0;
  }

  if ($('#date-data').val() == "") {
    alert('Your Task needs a date');
    return 0;
  }

  if (typeof($('#date-data').val()) != "string") {
    alert('Your date needs to be in text form');
    return 0;
  }

  data = { "task_id": task_id, "username": username, "title": task_title, "description": task_desc, "urgency": task_urgency,
                "due_date": date_data, "category": task_category };

  userData = JSON.stringify(data);

  NProgress.set(0.0);
  $.ajax({
    type: 'PUT',
    url: '/api/editTask/'+task_id + '/',
    contentType: 'application/json',

    success: function(result) {
      console.log(result);
      NProgress.set(1.0);
      var n = noty({text: 'Task Updated!', layout: "topRight", type: "information"});

    },
    fail: function(result) {
      alert('Failed to send Data');
      var n = noty({text: 'Task Update Failed!', layout: "topRight", type: "information"});
    },

    data: userData
  });

  console.log(userData);
});<|endoftext|>


<commit_before>import { createStore } from 'redux';
import rootReducer from '../reducers';

export default function configureStore () {
  const store = createStore(rootReducer)

  if (module.hot) {
    module.hot.accept(() => {
      const nextRootReducer = require('../reducers/index').default
      store.replaceReducer(nextRootReducer)
    })
  }
  return store
}
<commit_msg>applied thunk-middleware to store<commit_after>import thunkMiddleware from 'redux-thunk'
import { createStore, applyMiddleware } from 'redux'
import rootReducer from '../reducers'

export default function configureStore () {
  const store = createStore(rootReducer, applyMiddleware(thunkMiddleware))

  if (module.hot) {
    module.hot.accept(() => {
      const nextRootReducer = require('../reducers/index').default

      store.replaceReducer(nextRootReducer)
    })
  }

  return store
}
<|endoftext|>