<commit_before>var app = angular.module('ACM-Dash',[]);

app.config(function($interpolateProvider) {
	$interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
});

app.controller('ACM-Controller', ['$scope', '$http', '$interpolate', '$timeout', function($scope, $http, $interpolate, $timeout) {
	$scope.master = {};

	$scope.tab = [ "active", "", "" ];
	$scope.tabPane = [ "tab-pane active", "tab-pane", "tab-pane"];
	$scope.activeTab = function(tab) {
		$scope.tab = [ "", "", ""];
		$scope.tabPane = [ "tab-pane", "tab-pane", "tab-pane" ]
		if (tab == 0) {
			$scope.tab[0] = "active";
			$scope.tabPane[0] += " " + $scope.tab[0];
		}
		else if (tab == 1) {
			$scope.tab[1] = "active";
			$scope.tabPane[1] += " " + $scope.tab[1];
		}
		else if (tab == 2) {
			$scope.tab[2] = "active";
			$scope.tabPane[2] += " " + $scope.tab[2];
		}
	};

	$scope.time = new laserTime(123456);
	function laserTime(rawTime) {
		this.rawTime = rawTime;
		this.set = function(newTime) { this.rawTime = newTime };

		this.hours = function() { return parseInt(this.rawTime / 3600) };
		this.minutes = function() { return parseInt(this.rawTime % 3600 / 60) };
		this.seconds = function() { return this.rawTime % 60 };

		this.charge = function() { return (1.5 * parseFloat(this.rawTime / 60)).toFixed(2) };
	};

	$scope.progress = {
			isWaiting: false,
			button1: "btn btn-success",
			button2: "btn btn-danger"
		};

	$scope.getTime = function() {
		inProgress(true);
		$http.get("../getTime").success(function(res) {
			if (res == 2) {
				console.log("Error");
				$scope.time.set("Error");
			}
			else {
				console.log("Raw Time: " + res);
				$scope.time.set(res);
			}
			inProgress(false);
		});
	};

	$scope.resetTime = function() {
		inProgress(true);
		$http.get("../resetTime").success(function(res) {
			$scope.status = "Not successful";
			if (res[0] == 1) {
				$scope.status = "Success";
			}
			console.log($scope.status);
			inProgress(false);
		});
	};

	var inProgress = function(startRequest) {
		if (startRequest) {
			$scope.progress.isWaiting = true;
			$scope.progress.button1 = "btn btn-success disabled";
			$scope.progress.button2 = "btn btn-danger disabled";
		}
		else {
			$scope.progress.isWaiting = false;
			$scope.progress.button1 = "btn btn-success";
			$scope.progress.button2 = "btn btn-danger";
		}
	}

	$scope.user = {
		uid: "",
		memberName: "",
		memberType: "0",
		startDay: "",
		laserA: "1",
		laserB: "1",
		shopbot: "0",
		wood: "0",
		metal: "0",
		textile: "0",
		threeD: "0"
	};

	$scope.registerCard = function() {
		if ($scope.user.uid && $scope.user.memberName) {
			console.log(JSON.stringify($scope.user));
			var input = $scope.user.uid;

			$http({
				url: "../registerCard",
				method: "POST",
				headers: { 'Content-Type': 'application/json' },
				data: JSON.stringify($scope.user)})
				.success(function(data) {

					if (data != input) {
						$scope.entered = "Error";
						console.log($scope.entered);
					}
					else {
						$scope.entered = "User " + data + " registered.";
						console.log("ID registered: " + parseInt(data));
					}

				});

			$scope.user.uid = "";
			$scope.user.memberName = "";
			$scope.user.memberType = "0";
		}
	}

	var PATH = "../static/img/users/";
	$scope.display = {
			id: "",
			name: "",
			image: PATH + "GUEST.jpg",
			startDay: "",
			studio: "",
			access: ["red", "red", "red", "red", "red", "red", "red"],
			lifeTime: "",
			monthTime: ""
	};

	var socket = io.connect("http://localhost:5000");
	console.log("Socket Connected.");
	socket.on('scan', function(msg) {
		$scope.activeTab(0);
		$scope.display.id = msg[1];
		$scope.display.name = msg[2];
		$scope.display.image = PATH + msg[2] + ".jpg";
		$scope.display.startDay = msg[4];
		$scope.display.studio = msg[8];

		for (var i = 0; i < $scope.display.access.length; i++) {
			$scope.display.access[i] = parseInt(msg[i + 9]) ? "green" : "red";
		}

		$scope.display.lifeTime = (parseInt(msg[16]) / 60).toFixed(0);
		$scope.display.monthTime = (parseInt(msg[17]) / 60).toFixed(0);

		$scope.display.lifeTime = $scope.display.lifeTime.toString() + " minutes"
		$scope.display.monthTime = $scope.display.monthTime.toString() + " minutes"

		$scope.$apply();
    });

	$scope.changePic = function() {
		$scope.display.id = "420";
		$scope.display.name = "Harambe";
		$scope.display.image = PATH + "harambe.jpg";
		$scope.display.lifeTime = "";
		$scope.display.monthTime = "";
		$scope.$apply();
	};

	/*$scope.drawDonut = function() {
		var vis = d3.select("#time-display").append("g").append("svg");
		var pi = Math.PI;

		var containerWidth = d3.select("#content").node().getBoundingClientRect().width;
		var containerHeight = d3.select("#content").node().getBoundingClientRect().height;
		var j = 0.25;
		var x = j * containerWidth;
		var y = containerHeight/2;
		console.log(y);

		vis.attr("width", containerWidth).attr("height", 200);

		var arc = d3.arc()
			.innerRadius(75)
			.outerRadius(100)
			.startAngle(0)
			.endAngle(2 * pi);

		for (i = 0; i < 3; i++) {
			vis.append("path")
				.attr("d", arc)
				.attr("fill", "grey")
				.attr("transform", "translate(" + x + "," + 100 + ")");
				j += 0.25;
				x = j * containerWidth;
		};
		// ---------------------------------------------------------------
		j = 0.25;
		x = j * containerWidth;

		var data = [ $scope.hours, $scope.minutes, $scope.seconds ];
		var radianScale = d3.scaleLinear().domain([0, 59]).range([0, 2*pi]);
		data[0] = radianScale($scope.hours);
		data[1] = radianScale($scope.minutes);
		data[2] = radianScale($scope.seconds);

		var arc2 = d3.arc()
			.innerRadius(75)
			.outerRadius(100)
			.startAngle(0);

		var arc3 = d3.arc()
			.innerRadius(75)
			.outerRadius(100)
			.startAngle(0)
			.endAngle(pi/180);

		for (i = 0; i < 3; i++) {
			arc2.endAngle(data[i]);
			vis.append("path")
				.attr("fill", "blue")
				.attr("transform", "translate(" + x + "," + 100 + ")")
				.attr('d', arc3)
				.transition().delay(250)
				.attr("d", arc2);
				j += 0.25;
				x = j * containerWidth;
		};

	};*/

}]);<commit_msg>Removed timeout service. Successfully tested tab change on card scan<commit_after>var app = angular.module('ACM-Dash',[]);

app.config(function($interpolateProvider) {
	$interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
});

app.controller('ACM-Controller', ['$scope', '$http', '$interpolate', function($scope, $http, $interpolate) {
	$scope.master = {};

	$scope.tab = [ "active", "", "" ];
	$scope.tabPane = [ "tab-pane active", "tab-pane", "tab-pane"];
	$scope.activeTab = function(tab) {
		$scope.tab = [ "", "", ""];
		$scope.tabPane = [ "tab-pane", "tab-pane", "tab-pane" ]
		if (tab == 0) {
			$scope.tab[0] = "active";
			$scope.tabPane[0] += " " + $scope.tab[0];
		}
		else if (tab == 1) {
			$scope.tab[1] = "active";
			$scope.tabPane[1] += " " + $scope.tab[1];
		}
		else if (tab == 2) {
			$scope.tab[2] = "active";
			$scope.tabPane[2] += " " + $scope.tab[2];
		}
	};

	$scope.time = new laserTime(123456);
	function laserTime(rawTime) {
		this.rawTime = rawTime;
		this.set = function(newTime) { this.rawTime = newTime };

		this.hours = function() { return parseInt(this.rawTime / 3600) };
		this.minutes = function() { return parseInt(this.rawTime % 3600 / 60) };
		this.seconds = function() { return this.rawTime % 60 };

		this.charge = function() { return (1.5 * parseFloat(this.rawTime / 60)).toFixed(2) };
	};

	$scope.progress = {
			isWaiting: false,
			button1: "btn btn-success",
			button2: "btn btn-danger"
		};

	$scope.getTime = function() {
		inProgress(true);
		$http.get("../getTime").success(function(res) {
			if (res == 2) {
				console.log("Error");
				$scope.time.set("Error");
			}
			else {
				console.log("Raw Time: " + res);
				$scope.time.set(res);
			}
			inProgress(false);
		});
	};

	$scope.resetTime = function() {
		inProgress(true);
		$http.get("../resetTime").success(function(res) {
			$scope.status = "Not successful";
			if (res[0] == 1) {
				$scope.status = "Success";
			}
			console.log($scope.status);
			inProgress(false);
		});
	};

	var inProgress = function(startRequest) {
		if (startRequest) {
			$scope.progress.isWaiting = true;
			$scope.progress.button1 = "btn btn-success disabled";
			$scope.progress.button2 = "btn btn-danger disabled";
		}
		else {
			$scope.progress.isWaiting = false;
			$scope.progress.button1 = "btn btn-success";
			$scope.progress.button2 = "btn btn-danger";
		}
	}

	$scope.user = {
		uid: "",
		memberName: "",
		memberType: "0",
		startDay: "",
		laserA: "1",
		laserB: "1",
		shopbot: "0",
		wood: "0",
		metal: "0",
		textile: "0",
		threeD: "0"
	};

	$scope.registerCard = function() {
		if ($scope.user.uid && $scope.user.memberName) {
			console.log(JSON.stringify($scope.user));
			var input = $scope.user.uid;

			$http({
				url: "../registerCard",
				method: "POST",
				headers: { 'Content-Type': 'application/json' },
				data: JSON.stringify($scope.user)})
				.success(function(data) {

					if (data != input) {
						$scope.entered = "Error";
						console.log($scope.entered);
					}
					else {
						$scope.entered = "User " + data + " registered.";
						console.log("ID registered: " + parseInt(data));
					}

				});

			$scope.user.uid = "";
			$scope.user.memberName = "";
			$scope.user.memberType = "0";
		}
	}

	var PATH = "../static/img/users/";
	$scope.display = {
			id: "",
			name: "",
			image: PATH + "GUEST.jpg",
			startDay: "",
			studio: "",
			access: ["red", "red", "red", "red", "red", "red", "red"],
			lifeTime: "",
			monthTime: ""
	};

	var socket = io.connect("http://localhost:5000");
	console.log("Socket Connected.");
	socket.on('scan', function(msg) {
		$scope.activeTab(0);
		$scope.display.id = msg[1];
		$scope.display.name = msg[2];
		$scope.display.image = PATH + msg[2] + ".jpg";
		$scope.display.startDay = msg[4];
		$scope.display.studio = msg[8];

		for (var i = 0; i < $scope.display.access.length; i++) {
			$scope.display.access[i] = parseInt(msg[i + 9]) ? "green" : "red";
		}

		$scope.display.lifeTime = (parseInt(msg[16]) / 60).toFixed(0);
		$scope.display.monthTime = (parseInt(msg[17]) / 60).toFixed(0);

		$scope.display.lifeTime = $scope.display.lifeTime.toString() + " minutes"
		$scope.display.monthTime = $scope.display.monthTime.toString() + " minutes"

		$scope.$apply();
    });

	$scope.changePic = function() {
		$scope.display.id = "420";
		$scope.display.name = "Harambe";
		$scope.display.image = PATH + "harambe.jpg";
		$scope.display.lifeTime = "";
		$scope.display.monthTime = "";
		$scope.$apply();
	};

	/*$scope.drawDonut = function() {
		var vis = d3.select("#time-display").append("g").append("svg");
		var pi = Math.PI;

		var containerWidth = d3.select("#content").node().getBoundingClientRect().width;
		var containerHeight = d3.select("#content").node().getBoundingClientRect().height;
		var j = 0.25;
		var x = j * containerWidth;
		var y = containerHeight/2;
		console.log(y);

		vis.attr("width", containerWidth).attr("height", 200);

		var arc = d3.arc()
			.innerRadius(75)
			.outerRadius(100)
			.startAngle(0)
			.endAngle(2 * pi);

		for (i = 0; i < 3; i++) {
			vis.append("path")
				.attr("d", arc)
				.attr("fill", "grey")
				.attr("transform", "translate(" + x + "," + 100 + ")");
				j += 0.25;
				x = j * containerWidth;
		};
		// ---------------------------------------------------------------
		j = 0.25;
		x = j * containerWidth;

		var data = [ $scope.hours, $scope.minutes, $scope.seconds ];
		var radianScale = d3.scaleLinear().domain([0, 59]).range([0, 2*pi]);
		data[0] = radianScale($scope.hours);
		data[1] = radianScale($scope.minutes);
		data[2] = radianScale($scope.seconds);

		var arc2 = d3.arc()
			.innerRadius(75)
			.outerRadius(100)
			.startAngle(0);

		var arc3 = d3.arc()
			.innerRadius(75)
			.outerRadius(100)
			.startAngle(0)
			.endAngle(pi/180);

		for (i = 0; i < 3; i++) {
			arc2.endAngle(data[i]);
			vis.append("path")
				.attr("fill", "blue")
				.attr("transform", "translate(" + x + "," + 100 + ")")
				.attr('d', arc3)
				.transition().delay(250)
				.attr("d", arc2);
				j += 0.25;
				x = j * containerWidth;
		};

	};*/

}]);<|endoftext|>


<commit_before>import Ember from 'ember';
import TypeMixin from '../mixins/type';
import { set, get } from '@ember/object';
import { isArray } from '@ember/array';
import { displayKeyFor, validateLength, validateChars, validateHostname, validateDnsLabel } from '../utils/validate';
import { normalizeType } from '../utils/normalize';

const STRING_LIKE_TYPES = [
  'string',
  'date',
  'blob',
  'enum',
  'multiline',
  'masked',
  'password',
  'dnslLabel',
  'hostname',
];

var Actionable = Ember.Object.extend(Ember.ActionHandler);
var Resource = Actionable.extend(TypeMixin, {
  // You should probably override intl with a real translator...
  intl: {
    t(key) {
      return key;
    },
  },

  toString() {
    let str = 'resource:'+this.get('type');
    const id = this.get('id');

    if ( id ) {
      str += ':' + id;
    }

    return str;
  },

  serialize() {
    var data = this._super.apply(this,arguments);
    if ( this.constructor.mangleOut ) {
      return this.constructor.mangleOut(data);
    }

    return data;
  },

  validationErrors() {
    const intl = this.get('intl');

    const errors = [];
    const originalType = this.get('type');
    if ( !originalType ) {
      console.warn('No type found to validate', this);
      return [];
    }

    const type = normalizeType(originalType);
    const schema = this.get('store').getById('schema', type);

    if ( !schema ) {
      console.warn('No schema found to validate', type, this);
      return [];
    }

    // Trim all the values to start so that empty strings become nulls
    this.trimValues();

    const fields = schema.resourceFields||{};
    const keys = Object.keys(fields);
    let field, key, val, displayKey;
    for ( let i = 0 ; i < keys.length ; i++ ) {
      key = keys[i];
      field = fields[key];
      val = get(this, key);
      displayKey = displayKeyFor(type, key, intl);

      if ( val === undefined ) {
        val = null;
      }

      if ( field.type.indexOf('[') >= 0 ) {
        // array, map, reference
        // @TODO something...
      } else if ( val && typeof val.validationErrors === 'function' ) {
        // embedded schema type
        errors.pushObjects(val.validationErrors());
      } else if ( field.type === 'float' && typeof val === 'string' ) {
        // Coerce strings to floats
        val = parseFloat(val) || null; // NaN becomes null
        set(this, key, val);
      } else if ( field.type === 'int' && typeof val === 'string' ) {
        // Coerce strings to ints
        val = parseInt(val, 10) || null;
        set(this, key, val);
      }

      // Empty strings on nullable string fields -> null
      if ( field.nullable &&
          typeof val === 'string' &&
          val.length === 0 &&
          STRING_LIKE_TYPES.includes(field.type)
      ) {
        val = null;
        set(this, key, val);
      }

      let len = 0;
      if ( val ) {
        len = get(val, 'length');
      }

      if (
        field.required &&
        (
          val === null ||
          (typeof val === 'string' && len === 0) ||
          (isArray(val) && len === 0)
        )
      ) {
        errors.push(intl.t('validation.required', {key: displayKey}));
        continue;
      }

      validateLength(val, field, displayKey, intl, errors);
      validateChars( val, field, displayKey, intl, errors);

      if ( field.type === 'dnsLabel' || field.type === 'hostname' ) {
        // DNS types should be lowercase
        const tolower = (val||'').toLowerCase();
        if ( tolower !== val ) {
          val = tolower;
          set(this, key, val);
        }

        if ( field.type === 'dnsLabel' ) {
          validateDnsLabel(val, displayKey, intl, errors);
        } else if ( field.type === 'hostname') {
          validateHostname(val, displayKey, intl, errors);
        }
      }
    }

    return errors;
  },
});

// trimValues uses the definition of Resource so it needs to be a separate step
Resource.reopen({
  trimValues(depth, seenObjs) {
    if ( !depth ) {
      depth = 0;
    }

    if ( !seenObjs ) {
      seenObjs = [];
    }

    this.eachKeys((val,key) => {
      set(this, key, recurse(val,depth));
    }, false);

    return this;

    function recurse(val, depth) {
      if ( depth > 10 ) {
        return val;
      } else if ( typeof val === 'string' ) {
        return val.trim();
      } else if ( isArray(val) ) {
        val.beginPropertyChanges();
        val.forEach((v, idx) => {
          var out = recurse(v, depth+1);
          if ( val.objectAt(idx) !== out ) {
            val.replace(idx, 1, out);
          }
        });
        val.endPropertyChanges();
        return val;
      } else if ( Resource.detectInstance(val) ) {
        // Don't include a resource we've already seen in the chain
        if ( seenObjs.indexOf(val) > 0 ) {
          return null;
        }

        seenObjs.pushObject(val);
        return val.trimValues(depth+1, seenObjs);
      } else if ( val && typeof val === 'object' ) {
        Object.keys(val).forEach(function(key) {
          // Skip keys with dots in them, like container labels
          if ( key.indexOf('.') === -1 ) {
            set(val, key, recurse(val[key], depth+1));
          }
        });
        return val;
      } else {
        return val;
      }
    }
  },
});

Resource.reopenClass({
  // Request a default sort if none is specified
  defaultSortBy: '',

  // You can provide a function here to mangle data before it is passed to store.createRecord() for purposes of evil.
  mangleIn: null,

  // You can provide a function here to mangle data after it is serialized for purposes of even more evil.
  mangleOut: null,
});

export default Resource;
<commit_msg>Add schema computed property<commit_after>import Ember from 'ember';
import TypeMixin from '../mixins/type';
import { set, get } from '@ember/object';
import { isArray } from '@ember/array';
import { displayKeyFor, validateLength, validateChars, validateHostname, validateDnsLabel } from '../utils/validate';
import { normalizeType } from '../utils/normalize';

const STRING_LIKE_TYPES = [
  'string',
  'date',
  'blob',
  'enum',
  'multiline',
  'masked',
  'password',
  'dnslLabel',
  'hostname',
];

var Actionable = Ember.Object.extend(Ember.ActionHandler);
var Resource = Actionable.extend(TypeMixin, {
  // You should probably override intl with a real translator...
  intl: {
    t(key) {
      return key;
    },
  },

  toString() {
    let str = 'resource:'+this.get('type');
    const id = this.get('id');

    if ( id ) {
      str += ':' + id;
    }

    return str;
  },

  serialize() {
    var data = this._super.apply(this,arguments);
    if ( this.constructor.mangleOut ) {
      return this.constructor.mangleOut(data);
    }

    return data;
  },

  schema: function() {
    const schema = this.get('store').getById('schema', type);
    return schema;
  }.property('type'),

  validationErrors() {
    const intl = this.get('intl');

    const errors = [];
    const originalType = this.get('type');
    if ( !originalType ) {
      console.warn('No type found to validate', this);
      return [];
    }

    const type = normalizeType(originalType);
    const schema = this.get('store').getById('schema', type);

    if ( !schema ) {
      console.warn('No schema found to validate', type, this);
      return [];
    }

    // Trim all the values to start so that empty strings become nulls
    this.trimValues();

    const fields = schema.resourceFields||{};
    const keys = Object.keys(fields);
    let field, key, val, displayKey;
    for ( let i = 0 ; i < keys.length ; i++ ) {
      key = keys[i];
      field = fields[key];
      val = get(this, key);
      displayKey = displayKeyFor(type, key, intl);

      if ( val === undefined ) {
        val = null;
      }

      if ( field.type.indexOf('[') >= 0 ) {
        // array, map, reference
        // @TODO something...
      } else if ( val && typeof val.validationErrors === 'function' ) {
        // embedded schema type
        errors.pushObjects(val.validationErrors());
      } else if ( field.type === 'float' && typeof val === 'string' ) {
        // Coerce strings to floats
        val = parseFloat(val) || null; // NaN becomes null
        set(this, key, val);
      } else if ( field.type === 'int' && typeof val === 'string' ) {
        // Coerce strings to ints
        val = parseInt(val, 10) || null;
        set(this, key, val);
      }

      // Empty strings on nullable string fields -> null
      if ( field.nullable &&
          typeof val === 'string' &&
          val.length === 0 &&
          STRING_LIKE_TYPES.includes(field.type)
      ) {
        val = null;
        set(this, key, val);
      }

      let len = 0;
      if ( val ) {
        len = get(val, 'length');
      }

      if (
        field.required &&
        (
          val === null ||
          (typeof val === 'string' && len === 0) ||
          (isArray(val) && len === 0)
        )
      ) {
        errors.push(intl.t('validation.required', {key: displayKey}));
        continue;
      }

      validateLength(val, field, displayKey, intl, errors);
      validateChars( val, field, displayKey, intl, errors);

      if ( field.type === 'dnsLabel' || field.type === 'hostname' ) {
        // DNS types should be lowercase
        const tolower = (val||'').toLowerCase();
        if ( tolower !== val ) {
          val = tolower;
          set(this, key, val);
        }

        if ( field.type === 'dnsLabel' ) {
          validateDnsLabel(val, displayKey, intl, errors);
        } else if ( field.type === 'hostname') {
          validateHostname(val, displayKey, intl, errors);
        }
      }
    }

    return errors;
  },
});

// trimValues uses the definition of Resource so it needs to be a separate step
Resource.reopen({
  trimValues(depth, seenObjs) {
    if ( !depth ) {
      depth = 0;
    }

    if ( !seenObjs ) {
      seenObjs = [];
    }

    this.eachKeys((val,key) => {
      set(this, key, recurse(val,depth));
    }, false);

    return this;

    function recurse(val, depth) {
      if ( depth > 10 ) {
        return val;
      } else if ( typeof val === 'string' ) {
        return val.trim();
      } else if ( isArray(val) ) {
        val.beginPropertyChanges();
        val.forEach((v, idx) => {
          var out = recurse(v, depth+1);
          if ( val.objectAt(idx) !== out ) {
            val.replace(idx, 1, out);
          }
        });
        val.endPropertyChanges();
        return val;
      } else if ( Resource.detectInstance(val) ) {
        // Don't include a resource we've already seen in the chain
        if ( seenObjs.indexOf(val) > 0 ) {
          return null;
        }

        seenObjs.pushObject(val);
        return val.trimValues(depth+1, seenObjs);
      } else if ( val && typeof val === 'object' ) {
        Object.keys(val).forEach(function(key) {
          // Skip keys with dots in them, like container labels
          if ( key.indexOf('.') === -1 ) {
            set(val, key, recurse(val[key], depth+1));
          }
        });
        return val;
      } else {
        return val;
      }
    }
  },
});

Resource.reopenClass({
  // Request a default sort if none is specified
  defaultSortBy: '',

  // You can provide a function here to mangle data before it is passed to store.createRecord() for purposes of evil.
  mangleIn: null,

  // You can provide a function here to mangle data after it is serialized for purposes of even more evil.
  mangleOut: null,
});

export default Resource;
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Object.extend({
  serialize:   Ember.required(),
  deserialize: Ember.required()
});

export function deserialize(obj, value, meta, container) {
  return transform("deserialize", obj, value, meta, container);
}

export function serialize(obj, value, meta, container) {
  return transform("serialize", obj, value, meta, container);
}

export function transform(kind, obj, value, meta, container) {
  var type    = meta.type;
  var options = meta.options;

  if (options[kind]) {
    return options[kind].call(obj, value);
  }

  if (!type || !container) {
    return value;
  }

  var transformer = container.lookup('transform:'+type);
  if (!transformer) {
    return value;
  }

  return transformer[kind](value, options, container);
}
<commit_msg>remove usage of Ember.required<commit_after>import Ember from 'ember';

export default Ember.Object.extend({
  serialize:   null,
  deserialize: null
});

export function deserialize(obj, value, meta, container) {
  return transform("deserialize", obj, value, meta, container);
}

export function serialize(obj, value, meta, container) {
  return transform("serialize", obj, value, meta, container);
}

export function transform(kind, obj, value, meta, container) {
  var type    = meta.type;
  var options = meta.options;

  if (options[kind]) {
    return options[kind].call(obj, value);
  }

  if (!type || !container) {
    return value;
  }

  var transformer = container.lookup('transform:'+type);
  if (!transformer) {
    return value;
  }

  return transformer[kind](value, options, container);
}
<|endoftext|>


<commit_before>export default {
	'credit-card': 'Kreditkarte',
	'direct-debit': 'ELV',
	'sepa': 'SEPA',
	'paypal': 'Paypal',
	errors: {
		internal_server_error: 'Es ist ein Fehler aufgetreten, es wurde Ihnen allerdings nichts berechnet. Bitte versuchen Sie es erneut',
		invalid_public_key: 'Ungültige Paymill API key',
		invalid_payment_data: 'Ungültige Zahlungsdaten',
		unknown_error: 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es später noch einmal',
		'3ds_cancelled': 'Bezahlung wurde vom Benutzer abgebrochen',
		field_invalid_card_number: 'Ungültige Kartennummer',
		field_invalid_card_exp_year: 'Ungültiges Gültigkeitsdatum',
		field_invalid_card_exp_month: 'Ungültiges Gültigkeitsdatum',
		field_invalid_card_exp: 'Ungültiges Gültigkeitsdatum',
		field_invalid_card_cvc: 'Ungültige CVC',
		field_invalid_card_holder: 'Bitte geben Sie den Karteninhaber an',
		field_invalid_amount_int: 'Ungültige Zahlungsbetrag',
		field_invalid_currency: 'Ungültige Währungsformat',
		field_invalid_account_number: 'Bitte geben Sie eine gültige Kontonummer ein',
		field_invalid_account_holder: 'Bitte geben Sie den Kontoinhaber an',
		field_invalid_bank_code: 'Bitte geben Sie eine gültige BLZ ein',
		field_invalid_iban: 'Bitte geben Sie eine gültige IBAN ein',
		field_invalid_bic: 'Bitte geben Sie eine gültige BIC ein',
		field_invalid_country: 'Ungültige Land',
		field_invalid_bank_data: 'Ungültige Bank Daten',
		field_invalid_checksum: 'Ungültige checksum'
	}
};
<commit_msg>Update de.js<commit_after>export default {
	'credit-card': 'Kreditkarte',
	'direct-debit': 'ELV',
	'sepa': 'SEPA',
	'paypal': 'Paypal',
	errors: {
		internal_server_error: 'Es ist ein Fehler aufgetreten, es wurde Ihnen allerdings nichts berechnet. Bitte versuchen Sie es erneut',
		invalid_public_key: 'Ungültige Paymill API key',
		invalid_payment_data: 'Ungültige Zahlungsdaten',
		unknown_error: 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es später noch einmal',
		'3ds_cancelled': 'Bezahlung wurde vom Benutzer abgebrochen',
		field_invalid_card_number: 'Ungültige Kartennummer',
		field_invalid_card_exp_year: 'Ungültiges Gültigkeitsdatum',
		field_invalid_card_exp_month: 'Ungültiges Gültigkeitsdatum',
		field_invalid_card_exp: 'Ungültiges Gültigkeitsdatum',
		field_invalid_card_cvc: 'Ungültige CVC',
		field_invalid_card_holder: 'Bitte geben Sie den Karteninhaber an',
		field_invalid_amount_int: 'Ungültiger Zahlungsbetrag',
		field_invalid_currency: 'Ungültiges Währungsformat',
		field_invalid_account_number: 'Bitte geben Sie eine gültige Kontonummer ein',
		field_invalid_account_holder: 'Bitte geben Sie den Kontoinhaber an',
		field_invalid_bank_code: 'Bitte geben Sie eine gültige BLZ ein',
		field_invalid_iban: 'Bitte geben Sie eine gültige IBAN ein',
		field_invalid_bic: 'Bitte geben Sie eine gültige BIC ein',
		field_invalid_country: 'Ungültiges Land',
		field_invalid_bank_data: 'Ungültige Bankdaten',
		field_invalid_checksum: 'Ungültige Checksumme'
	}
};
<|endoftext|>


<commit_before>// var testingApiKey=
// var testingToken =<commit_msg>Added plain object in testing.js<commit_after>var instanceIdObject = {
    appKey: '',
    deviceToken: '',
    isFocused: false,
    toValidate: false
};<|endoftext|>


<commit_before>/** Handle the creation of HTML links to documented symbols.
	@constructor
*/
function Link() {
	this.alias = "";
	this.src = "";
	this.file = "";
	this.text = "";
	this.innerName = "";
	this.classLink = false;
	this.targetName = "";

	this.target = function(targetName) {
		if (defined(targetName)) this.targetName = targetName;
		return this;
	}
	this.inner = function(inner) {
		if (defined(inner)) this.innerName = inner;
		return this;
	}
	this.withText = function(text) {
		if (defined(text)) this.text = text;
		return this;
	}
	this.toSrc = function(filename) {
		if (defined(filename)) this.src = filename;
		return this;
	}
	this.toSymbol = function(alias) {
		if(/\[\]$/.test(alias)) {
			alias = alias.replace(/\[\]$/, '');
			this.text = 'array of ' + alias + ' objects';
		}
		if (defined(alias)) this.alias = new String(alias);
		return this;
	}
	this.toClass = function(alias) {
		this.classLink = true;
		return this.toSymbol(alias);
	}
	this.toFile = function(file) {
		if (defined(file)) this.file = file;
		return this;
	}

	this.toString = function() {
		var linkString;
		var thisLink = this;

		if (this.alias) {
			linkString = this.alias.replace(/(^|[^a-z$0-9_#.:^-])([|a-z$0-9_#.:^-]+)($|[^a-z$0-9_#.:^-])/i,
				function(match, prematch, symbolName, postmatch) {
					var symbolNames = symbolName.split("|");
					var links = [];
					for (var i = 0, l = symbolNames.length; i < l; i++) {
						thisLink.alias = symbolNames[i];
						links.push(thisLink._makeSymbolLink(symbolNames[i]));
					}
					return prematch+links.join("|")+postmatch;
				}
			);
		}
		else if (this.src) {
			linkString = thisLink._makeSrcLink(this.src);
		}
		else if (this.file) {
			linkString = thisLink._makeFileLink(this.file);
		}

		return linkString;
	}
}

/** prefixed for hashes */
Link.hashPrefix = "";

/** Appended to the front of relative link paths. */
Link.base = "";

Link.symbolNameToLinkName = function(symbol) {
	var linker = "",
		ns = "";

	if (symbol.isStatic) linker = ".";
	else if (symbol.isInner) linker = "-";

	if (symbol.isEvent && !/^event:/.test(symbol.name)) {
		ns = "event:";
	}
	return Link.hashPrefix+linker+ns+symbol.name;
}

Link.getSymbol= function(alias) {
    var symbol= Link.symbolSet.getSymbol(alias);

    if (symbol)
        return symbol;

    if ('#'!==alias.charAt(0) || !Link.currentSymbol)
        return null;

    //  resolve relative name
    var container= Link.currentSymbol;

    while (container)
    {
        symbol= Link.symbolSet.getSymbol(container.alias + alias);
        if (symbol)
            return symbol;

        //  No superclass
        if (!container.augments.length)
            return null;

        container= Link.symbolSet.getSymbol(container.augments[0].desc);
    }

    return null;
}

/** Create a link to another symbol. */
Link.prototype._makeSymbolLink = function(alias) {
	var linkBase = Link.base+publish.conf.symbolsDir;
	var linkTo = Link.getSymbol(alias);
	var linkPath;
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	// if there is no symbol by that name just return the name unaltered
	if (!linkTo)
	    return this.text || alias;

	// it's a symbol in another file
	else {
		if (!linkTo.is("CONSTRUCTOR") && !linkTo.isNamespace) { // it's a method or property
			linkPath= (Link.filemap) ? Link.filemap[linkTo.memberOf] :
				      escape(linkTo.memberOf) || "_global_";
				linkPath += publish.conf.ext + "#" + Link.symbolNameToLinkName(linkTo);
		}
		else {
			linkPath = (Link.filemap)? Link.filemap[linkTo.alias] : escape(linkTo.alias);
			linkPath += publish.conf.ext;// + (this.classLink? "":"#" + Link.hashPrefix + "constructor");
		}
		linkPath = linkBase + linkPath
	}

	var linkText= this.text || alias;

	var link = {linkPath: linkPath, linkText: linkText.replace(/^#/, ''), linkInner: (this.innerName? "#" + this.innerName : "")};

	if (typeof JSDOC.PluginManager != "undefined") {
		JSDOC.PluginManager.run("onSymbolLink", link);
	}
	if (/^[A-Z].+\#/.test(link.linkText)) {
		link.linkText = link.linkText.charAt(0).toLowerCase() + link.linkText.slice(1);
		link.linkText = link.linkText.replace(/#/g, '.');
	}

	return ""+link.linkText+"";
}

/** Create a link to a source file. */
Link.prototype._makeSrcLink = function(srcFilePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	// transform filepath into a filename
	var srcFile = srcFilePath.replace(/\.\.?[\\\/]/g, "").replace(/[:\\\/]/g, "_");
	var outFilePath = Link.base + publish.conf.srcDir + srcFile + publish.conf.ext;

	if (!this.text) this.text = FilePath.fileName(srcFilePath);
	return ""+this.text+"";
}

/** Create a link to a source file. */
Link.prototype._makeFileLink = function(filePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	var outFilePath =  Link.base + filePath;

	if (!this.text) this.text = filePath;
	return ""+this.text+"";
}<commit_msg>jsdoc: support {@link Class#method(param1, param2)} -> Class#method-param1-param2.<commit_after>/** Handle the creation of HTML links to documented symbols.
	@constructor
*/
function Link() {
	this.alias = "";
	this.src = "";
	this.file = "";
	this.text = "";
	this.innerName = "";
	this.classLink = false;
	this.targetName = "";

	this.target = function(targetName) {
		if (defined(targetName)) this.targetName = targetName;
		return this;
	}
	this.inner = function(inner) {
		if (defined(inner)) this.innerName = inner;
		return this;
	}
	this.withText = function(text) {
		if (defined(text)) this.text = text;
		return this;
	}
	this.toSrc = function(filename) {
		if (defined(filename)) this.src = filename;
		return this;
	}
	this.toSymbol = function(alias) {
		// 'Class[]' to 'array of Class objects'
		if(/\[\]$/.test(alias)) {
			alias = alias.replace(/\[\]$/, '');
			this.text = 'array of ' + alias + ' objects';
		}
		if (defined(alias)) this.alias = new String(alias);
		return this;
	}
	this.toClass = function(alias) {
		this.classLink = true;
		return this.toSymbol(alias);
	}
	this.toFile = function(file) {
		if (defined(file)) this.file = file;
		return this;
	}

	this.toString = function() {
		var linkString;
		var thisLink = this;

		if (this.alias) {
			linkString = this.alias.replace(/(^|[^a-z$0-9_#.:^-])([|a-z$0-9_#.:^-]+)(\([^)]+\))*($|[^a-z$0-9_#.:^-])/i,
				function(match, prematch, symbolName, parameters, postmatch) {
					var symbolNames = symbolName.split("|");
					var links = [];
					for (var i = 0, l = symbolNames.length; i < l; i++) {
						thisLink.alias = symbolNames[i];
						links.push(thisLink._makeSymbolLink(symbolNames[i], parameters));
					}
					return prematch+links.join("|")+postmatch;
				}
			);
		}
		else if (this.src) {
			linkString = thisLink._makeSrcLink(this.src);
		}
		else if (this.file) {
			linkString = thisLink._makeFileLink(this.file);
		}

		return linkString;
	}
}

/** prefixed for hashes */
Link.hashPrefix = "";

/** Appended to the front of relative link paths. */
Link.base = "";

Link.symbolNameToLinkName = function(symbol) {
	var linker = "",
		ns = "";

	if (symbol.isStatic) linker = ".";
	else if (symbol.isInner) linker = "-";

	if (symbol.isEvent && !/^event:/.test(symbol.name)) {
		ns = "event:";
	}
	return Link.hashPrefix+linker+ns+symbol.name;
}

Link.getSymbol= function(alias) {
    var symbol= Link.symbolSet.getSymbol(alias);

    if (symbol)
        return symbol;

    if ('#'!==alias.charAt(0) || !Link.currentSymbol)
        return null;

    //  resolve relative name
    var container= Link.currentSymbol;

    while (container)
    {
        symbol= Link.symbolSet.getSymbol(container.alias + alias);
        if (symbol)
            return symbol;

        //  No superclass
        if (!container.augments.length)
            return null;

        container= Link.symbolSet.getSymbol(container.augments[0].desc);
    }

    return null;
}

/** Create a link to another symbol. */
Link.prototype._makeSymbolLink = function(alias, parameters) {
	var linkBase = Link.base+publish.conf.symbolsDir;
	var linkTo = Link.getSymbol(alias);
	var linkPath;
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";
	// if there is no symbol by that name just return the name unaltered
	if (!linkTo) {
	    return this.text || alias;
	} else {
		// it's a symbol in another file
		if (!linkTo.is("CONSTRUCTOR") && !linkTo.isNamespace) { // it's a method or property
			linkPath= (Link.filemap) ? Link.filemap[linkTo.memberOf] :
				      escape(linkTo.memberOf) || "_global_";
				linkPath += publish.conf.ext + "#" + Link.symbolNameToLinkName(linkTo);
			if (parameters) {
				linkPath += '-' + parameters.replace(/[()]+/g, '').split(', ').join('-').toLowerCase();
			}
		} else {
			linkPath = (Link.filemap)? Link.filemap[linkTo.alias] : escape(linkTo.alias);
			linkPath += publish.conf.ext;// + (this.classLink? "":"#" + Link.hashPrefix + "constructor");
		}
		linkPath = linkBase + linkPath
	}

	var linkText= (this.text || alias) + (parameters || '');

	var link = {
		linkPath: linkPath,
		linkText: linkText.replace(/^#/, ''),
		linkInner: (this.innerName? "#" + this.innerName : "")
	};

	if (typeof JSDOC.PluginManager != "undefined") {
		JSDOC.PluginManager.run("onSymbolLink", link);
	}
	if (/^[A-Z].+\#/.test(link.linkText)) {
		link.linkText = link.linkText.charAt(0).toLowerCase() + link.linkText.slice(1);
		link.linkText = link.linkText.replace(/#/g, '.');
	}

	return ""+link.linkText+"";
}

/** Create a link to a source file. */
Link.prototype._makeSrcLink = function(srcFilePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	// transform filepath into a filename
	var srcFile = srcFilePath.replace(/\.\.?[\\\/]/g, "").replace(/[:\\\/]/g, "_");
	var outFilePath = Link.base + publish.conf.srcDir + srcFile + publish.conf.ext;

	if (!this.text) this.text = FilePath.fileName(srcFilePath);
	return ""+this.text+"";
}

/** Create a link to a source file. */
Link.prototype._makeFileLink = function(filePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	var outFilePath =  Link.base + filePath;

	if (!this.text) this.text = filePath;
	return ""+this.text+"";
}<|endoftext|>


<commit_before>/* globals initPhotoSwipeFromDOM L10N */

const photoBooth = (function () {
    // vars
    const public = {},
        loader = $('#loader'),
        startPage = $('#start'),
        timeToLive = 90000,
        gallery = $('#gallery'),
        resultPage = $('#result'),
        webcamConstraints = {
            audio: false,
            video: {
                width: 720,
                height: 480,
                facingMode: 'user',
            }
        };

    let timeOut,
        nextCollageNumber = 0,
        currentCollageFile = '',
        imgFilter = 'imgPlain';

    const modal = {
        open: function (selector) {
            $(selector).addClass('modal--show');
        },
        close: function (selector) {
            if ($(selector).hasClass('modal--show')) {
                $(selector).removeClass('modal--show');

                return true;
            }

            return false;
        },
        toggle: function (selector) {
            $(selector).toggleClass('modal--show');
        },
        empty: function (selector) {
            modal.close(selector);

            $(selector).find('.modal__body').empty();
        }
    };

    public.reloadPage = function () {
        window.location.reload();
    }

    // timeOut function
    public.resetTimeOut = function () {
        timeOut = setTimeout(function () {
            public.reloadPage();
        }, timeToLive);
    }

    // reset whole thing
    public.reset = function () {
        loader.removeClass('open');
        modal.empty('#qrCode');
        $('.qrbtn').removeClass('active').attr('style', '');
        $('.loading').text('');
        gallery.removeClass('gallery--open');
        gallery.find('.gallery__inner').hide();
        $('.spinner').hide();
        $('.send-mail').hide();
        public.resetMailForm();
    }

    // init
    public.init = function () {
        public.l10n();
        public.reset();

        initPhotoSwipeFromDOM('#galimages');

        startPage.show();
    }

    public.l10n = function (elem) {
        elem = $(elem || 'body');
        elem.find('[data-l10n]').each(function () {
            const item = $(this);
            const key = item.data('l10n');
            const translation = L10N[key];

            if (!translation) {
                console.warn('No translation for: ', key);
            }

            item.html(translation || key);
        });
    }

    public.openNav = function () {
        $('#mySidenav').addClass('sidenav--open');
    }

    public.closeNav = function () {
        $('#mySidenav').removeClass('sidenav--open');
    }

    public.toggleNav = function () {
        $('#mySidenav').toggleClass('sidenav--open');
    }

    public.startVideo = function () {
        if (!navigator.mediaDevices) {
            return;
        }

        navigator.getMedia = (navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.mozGetUserMedia || false);

        if (!navigator.getMedia) {
            return;
        }

        navigator.getMedia(webcamConstraints)
            .then(function (stream) {
                $('#video').show();
                const video = $('#video').get(0);
                video.srcObject = stream;
                public.stream = stream;
            })
            .catch(function () { });
    }

    public.stopVideo = function () {
        if (public.stream) {
            const track = public.stream.getTracks()[0];
            track.stop();
            $('#video').hide();
        }
    }

    public.thrill = function (photoStyle) {
        public.closeNav();
        public.reset();

        if (currentCollageFile && nextCollageNumber) {
            photoStyle = 'collage';
        }

        if (config.previewFromCam) {
            public.startVideo();
        }

        loader.addClass('open');
        public.startCountdown(config.cntdwn_time, $('#counter'), () => {
            public.cheese(photoStyle);
        });
    }

    // Cheese
    public.cheese = function (photoStyle) {
        if (config.dev) {
            console.log(photoStyle);
        }

        $('#counter').text('');

        if (photoStyle === 'photo') {
            $('.loading').text(L10N.cheese);
        } else {
            $('.loading').text(L10N.cheeseCollage);
        }

        setTimeout(() => {
            public.takePic(photoStyle);
        }, config.cheese_time);
    }

    // take Picture
    public.takePic = function (photoStyle) {
        if (config.dev) {
            console.log('Take Picture:' + photoStyle);
        }

        if (config.previewFromCam) {
            public.stopVideo();
        }

        const processingDelay = setTimeout(() => {
            $('.spinner').show();
            $('.loading').text(photoStyle === 'photo' ? L10N.busy : L10N.busyCollage);
        }, 500);

        const data = {
            filter: imgFilter,
            style: photoStyle,
        };

        if (photoStyle === 'collage') {
            data.file = currentCollageFile;
            data.collageNumber = nextCollageNumber;
        }

        jQuery.post('api/takePic.php', data).done(function (result) {
            clearTimeout(processingDelay);

            if (result.error) {
                public.errorPic(result);
            } else if (result.success === 'collage') {
                currentCollageFile = result.file;
                nextCollageNumber = result.current + 1;

                $('.spinner').hide();
                $('.loading').empty();
                $('
').text(`${result.current + 1} / ${result.limit}`).appendTo('.loading');
                $('' + L10N.newPhoto + '').appendTo('.loading').click((ev) => {
                    ev.preventDefault();

                    public.thrill('collage');
                });
            } else {
                currentCollageFile = '';
                nextCollageNumber = 0;

                public.renderPic(result);
            }

        }).fail(function (xhr, status, result) {
            public.errorPic(result);
        });
    }

    // Show error Msg and reset
    public.errorPic = function () {
        setTimeout(function () {
            $('.spinner').hide();
            $('.loading').html(L10N.error + '' + L10N.reload + '');
        }, 1100);
    }

    // Render Picture after taking
    public.renderPic = function (result) {
        // Add QR Code Image
        const qrCodeModal = $('#qrCode');
        modal.empty(qrCodeModal);
        $('').on('load', function () {
            const body = qrCodeModal.find('.modal__body');

            $(this).appendTo(body);
            $('
').html(L10N.qrHelp).appendTo(body);
        });

        // Add Print Link
        $(document).off('click touchstart', '.printbtn');
        $(document).on('click', '.printbtn', function (e) {
            e.preventDefault();
            e.stopPropagation();

            public.printImage(result.img, () => {
                public.reloadPage();
            });
        });

        resultPage.find('.deletebtn').off('click').on('click', (ev) => {
            ev.preventDefault();

            public.deleteImage(result.img, (data) => {
                if (data.success) {
                    public.reloadPage();
                } else {
                    console.log('Error while deleting image');
                }
            })
        });

        // Add Image to gallery and slider
        public.addImage(result.img);

        // Add Image
        $('').on('load', function () {
            resultPage.css({
                'background-image': 'url(' + config.folders.images + '/' + result.img + ')'
            });
            resultPage.attr('data-img', result.img);

            startPage.fadeOut(400, function () {
                resultPage.fadeIn(400, function () {
                    setTimeout(function () {
                        loader.removeClass('open');
                    }, 400);
                    setTimeout(function () {
                        $('.resultInner').addClass('show');
                    }, 400);
                    clearTimeout(timeOut);
                    public.resetTimeOut();
                });
            });
        });
    }

    // add image to Gallery
    public.addImage = function (imageName) {
        const thumbImg = new Image();
        const bigImg = new Image();
        let thumbSize = '';
        let bigSize = '';

        let imgtoLoad = 2;

        thumbImg.onload = function () {
            thumbSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.onload = function () {
            bigSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.src = config.folders.images + '/' + imageName;
        thumbImg.src = config.folders.thumbs + '/' + imageName;

        function allLoaded() {
            const linkElement = $('').html(thumbImg);

            linkElement.attr('data-size', bigSize);
            linkElement.attr('href', config.folders.images + '/' + imageName + '?new=1');
            linkElement.attr('data-med', config.folders.thumbs + '/' + imageName);
            linkElement.attr('data-med-size', thumbSize);

            if (config.newest_first) {
                linkElement.prependTo($('#galimages'));
            } else {
                linkElement.appendTo($('#galimages'));
            }
        }
    }

    // Open Gallery Overview
    public.openGallery = function () {
        if (config.scrollbar) {
            gallery.addClass('scrollbar');
        }

        gallery.addClass('gallery--open');

        setTimeout(() => gallery.find('.gallery__inner').show(), 300);
    }

    public.resetMailForm = function () {
        $('#send-mail-form').trigger('reset');
        $('#mail-form-message').html('');
    };

    // Countdown Function
    public.startCountdown = function (start, element, cb) {
        let count = 0;
        let current = start;

        function timerFunction() {
            element.text(current);
            current--;

            element.removeClass('tick');

            if (count < start) {
                window.setTimeout(() => element.addClass('tick'), 50);
                window.setTimeout(timerFunction, 1000);
            } else {
                cb();
            }
            count++;
        }
        timerFunction();
    }

    public.printImage = function (imageSrc, cb) {
        modal.open('#print_mesg');

        setTimeout(function () {
            $.ajax({
                url: 'api/print.php?filename=' + encodeURI(imageSrc),
            }).done(function (data) {
                if (config.dev) {
                    console.log(data)
                }

                setTimeout(function () {
                    modal.close('#print_mesg');
                    cb();
                }, 5000);
            });
        }, 1000);
    }

    public.deleteImage = function (imageName, cb) {
        $.ajax({
            url: 'api/deletePhoto.php',
            method: 'POST',
            data: {
                file: imageName,
            },
            success: (data) => {
                cb(data);
            }
        });
    }

    public.toggleMailDialog = function (img) {
        const mail = $('.send-mail');

        if (mail.hasClass('mail-active')) {
            public.resetMailForm();
            mail.removeClass('mail-active').fadeOut('fast');
        } else {
            $('#mail-form-image').val(img);

            mail.addClass('mail-active').fadeIn('fast');
        }
    }

    //Filter
    $('.imageFilter').on('click', function () {
        public.toggleNav();
    });

    $('.sidenav > div').on('click', function () {
        $('.sidenav > div').removeAttr('class');

        $(this).addClass('activeSidenavBtn');

        imgFilter = $(this).attr('id');

        if (config.dev) {
            console.log('Active filter', imgFilter);
        }
    });

    // Take Picture Button
    $('.takePic, .newpic').on('click', function (e) {
        e.preventDefault();

        public.thrill('photo');
    });

    // Take Collage Button
    $('.takeCollage, .newcollage').on('click', function (e) {
        e.preventDefault();

        public.thrill('collage');
    });

    $('#mySidenav .closebtn').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
    });

    // Open Gallery Button
    $('.gallery-button').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
        public.openGallery($(this));
    });

    // Close Gallery Overview
    $('.gallery__close').on('click', function (e) {
        e.preventDefault();

        gallery.find('.gallery__inner').hide();
        gallery.removeClass('gallery--open');
    });

    $('.mailbtn').on('click touchstart', function (e) {
        e.preventDefault();
        e.stopPropagation();

        const img = resultPage.attr('data-img');

        public.toggleMailDialog(img);
    });

    $('#send-mail-form').on('submit', function (e) {
        e.preventDefault();

        const message = $('#mail-form-message');
        message.empty();

        const form = $(this);
        const oldValue = form.find('.btn').html();

        form.find('.btn').html('');

        $.ajax({
            url: 'api/sendPic.php',
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            cache: false,
            success: function (result) {
                if (result.success) {
                    message.fadeIn().html('' + L10N.mailSent + '');
                } else {
                    message.fadeIn().html('' + result.error + '');
                }
            },
            error: function () {
                message.fadeIn('fast').html('' + L10N.mailError + '');
            },
            complete: function () {
                form.find('.btn').html(oldValue);
            }
        });
    });

    $('#send-mail-close').on('click', function () {
        public.resetMailForm();
        $('.send-mail').removeClass('mail-active').fadeOut('fast');
    });

    $('#result').on('click', function () {
        if (!modal.close('#qrCode')) {
            $('.resultInner').toggleClass('show');
        }
    });

    // Show QR Code
    $('.qrbtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        modal.toggle('#qrCode');
    });

    $('.homebtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        public.reloadPage();
    });

    $('#cups-button').on('click', function (ev) {
        ev.preventDefault();

        const url = `http://${location.hostname}:631/jobs/`;
        const features = 'width=1024,height=600,left=0,top=0,screenX=0,screenY=0,resizable=NO,scrollbars=NO';

        window.open(url, 'newwin', features);
    });

    $(document).on('keypress', function (ev) {
        if (config.photo_key && parseInt(config.photo_key, 10) === ev.keyCode) {
            public.thrill('photo');
        }

        if (config.collage_key && parseInt(config.collage_key, 10) === ev.keyCode) {
            public.thrill('collage');
        }
    });

    // clear Timeout to not reset the gallery, if you clicked anywhere
    $(document).on('click', function () {
        if (!startPage.is(':visible')) {
            clearTimeout(timeOut);
            public.resetTimeOut();
        }
    });

    // Disable Right-Click
    if (!config.dev) {
        $(this).on('contextmenu', function (e) {
            e.preventDefault();
        });
    }

    return public;
})();

// Init on domready
$(function () {
    photoBooth.init();
});
<commit_msg>fix large qr code dialog<commit_after>/* globals initPhotoSwipeFromDOM L10N */

const photoBooth = (function () {
    // vars
    const public = {},
        loader = $('#loader'),
        startPage = $('#start'),
        timeToLive = 90000,
        gallery = $('#gallery'),
        resultPage = $('#result'),
        webcamConstraints = {
            audio: false,
            video: {
                width: 720,
                height: 480,
                facingMode: 'user',
            }
        };

    let timeOut,
        nextCollageNumber = 0,
        currentCollageFile = '',
        imgFilter = 'imgPlain';

    const modal = {
        open: function (selector) {
            $(selector).addClass('modal--show');
        },
        close: function (selector) {
            if ($(selector).hasClass('modal--show')) {
                $(selector).removeClass('modal--show');

                return true;
            }

            return false;
        },
        toggle: function (selector) {
            $(selector).toggleClass('modal--show');
        },
        empty: function (selector) {
            modal.close(selector);

            $(selector).find('.modal__body').empty();
        }
    };

    public.reloadPage = function () {
        window.location.reload();
    }

    // timeOut function
    public.resetTimeOut = function () {
        timeOut = setTimeout(function () {
            public.reloadPage();
        }, timeToLive);
    }

    // reset whole thing
    public.reset = function () {
        loader.removeClass('open');
        modal.empty('#qrCode');
        $('.qrbtn').removeClass('active').attr('style', '');
        $('.loading').text('');
        gallery.removeClass('gallery--open');
        gallery.find('.gallery__inner').hide();
        $('.spinner').hide();
        $('.send-mail').hide();
        public.resetMailForm();
    }

    // init
    public.init = function () {
        public.l10n();
        public.reset();

        initPhotoSwipeFromDOM('#galimages');

        startPage.show();
    }

    public.l10n = function (elem) {
        elem = $(elem || 'body');
        elem.find('[data-l10n]').each(function () {
            const item = $(this);
            const key = item.data('l10n');
            const translation = L10N[key];

            if (!translation) {
                console.warn('No translation for: ', key);
            }

            item.html(translation || key);
        });
    }

    public.openNav = function () {
        $('#mySidenav').addClass('sidenav--open');
    }

    public.closeNav = function () {
        $('#mySidenav').removeClass('sidenav--open');
    }

    public.toggleNav = function () {
        $('#mySidenav').toggleClass('sidenav--open');
    }

    public.startVideo = function () {
        if (!navigator.mediaDevices) {
            return;
        }

        navigator.getMedia = (navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.mozGetUserMedia || false);

        if (!navigator.getMedia) {
            return;
        }

        navigator.getMedia(webcamConstraints)
            .then(function (stream) {
                $('#video').show();
                const video = $('#video').get(0);
                video.srcObject = stream;
                public.stream = stream;
            })
            .catch(function () { });
    }

    public.stopVideo = function () {
        if (public.stream) {
            const track = public.stream.getTracks()[0];
            track.stop();
            $('#video').hide();
        }
    }

    public.thrill = function (photoStyle) {
        public.closeNav();
        public.reset();

        if (currentCollageFile && nextCollageNumber) {
            photoStyle = 'collage';
        }

        if (config.previewFromCam) {
            public.startVideo();
        }

        loader.addClass('open');
        public.startCountdown(config.cntdwn_time, $('#counter'), () => {
            public.cheese(photoStyle);
        });
    }

    // Cheese
    public.cheese = function (photoStyle) {
        if (config.dev) {
            console.log(photoStyle);
        }

        $('#counter').text('');

        if (photoStyle === 'photo') {
            $('.loading').text(L10N.cheese);
        } else {
            $('.loading').text(L10N.cheeseCollage);
        }

        setTimeout(() => {
            public.takePic(photoStyle);
        }, config.cheese_time);
    }

    // take Picture
    public.takePic = function (photoStyle) {
        if (config.dev) {
            console.log('Take Picture:' + photoStyle);
        }

        if (config.previewFromCam) {
            public.stopVideo();
        }

        const processingDelay = setTimeout(() => {
            $('.spinner').show();
            $('.loading').text(photoStyle === 'photo' ? L10N.busy : L10N.busyCollage);
        }, 500);

        const data = {
            filter: imgFilter,
            style: photoStyle,
        };

        if (photoStyle === 'collage') {
            data.file = currentCollageFile;
            data.collageNumber = nextCollageNumber;
        }

        jQuery.post('api/takePic.php', data).done(function (result) {
            clearTimeout(processingDelay);

            if (result.error) {
                public.errorPic(result);
            } else if (result.success === 'collage') {
                currentCollageFile = result.file;
                nextCollageNumber = result.current + 1;

                $('.spinner').hide();
                $('.loading').empty();
                $('
').text(`${result.current + 1} / ${result.limit}`).appendTo('.loading');
                $('' + L10N.newPhoto + '').appendTo('.loading').click((ev) => {
                    ev.preventDefault();

                    public.thrill('collage');
                });
            } else {
                currentCollageFile = '';
                nextCollageNumber = 0;

                public.renderPic(result);
            }

        }).fail(function (xhr, status, result) {
            public.errorPic(result);
        });
    }

    // Show error Msg and reset
    public.errorPic = function () {
        setTimeout(function () {
            $('.spinner').hide();
            $('.loading').html(L10N.error + '' + L10N.reload + '');
        }, 1100);
    }

    // Render Picture after taking
    public.renderPic = function (result) {
        // Add QR Code Image
        const qrCodeModal = $('#qrCode');
        modal.empty(qrCodeModal);
        $('').on('load', function () {
            const body = qrCodeModal.find('.modal__body');

            $(this).appendTo(body);
            $('
').css('max-width', this.width + 'px').html(L10N.qrHelp).appendTo(body);
        });

        // Add Print Link
        $(document).off('click touchstart', '.printbtn');
        $(document).on('click', '.printbtn', function (e) {
            e.preventDefault();
            e.stopPropagation();

            public.printImage(result.img, () => {
                public.reloadPage();
            });
        });

        resultPage.find('.deletebtn').off('click').on('click', (ev) => {
            ev.preventDefault();

            public.deleteImage(result.img, (data) => {
                if (data.success) {
                    public.reloadPage();
                } else {
                    console.log('Error while deleting image');
                }
            })
        });

        // Add Image to gallery and slider
        public.addImage(result.img);

        // Add Image
        $('').on('load', function () {
            resultPage.css({
                'background-image': 'url(' + config.folders.images + '/' + result.img + ')'
            });
            resultPage.attr('data-img', result.img);

            startPage.fadeOut(400, function () {
                resultPage.fadeIn(400, function () {
                    setTimeout(function () {
                        loader.removeClass('open');
                    }, 400);
                    setTimeout(function () {
                        $('.resultInner').addClass('show');
                    }, 400);
                    clearTimeout(timeOut);
                    public.resetTimeOut();
                });
            });
        });
    }

    // add image to Gallery
    public.addImage = function (imageName) {
        const thumbImg = new Image();
        const bigImg = new Image();
        let thumbSize = '';
        let bigSize = '';

        let imgtoLoad = 2;

        thumbImg.onload = function () {
            thumbSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.onload = function () {
            bigSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.src = config.folders.images + '/' + imageName;
        thumbImg.src = config.folders.thumbs + '/' + imageName;

        function allLoaded() {
            const linkElement = $('').html(thumbImg);

            linkElement.attr('data-size', bigSize);
            linkElement.attr('href', config.folders.images + '/' + imageName + '?new=1');
            linkElement.attr('data-med', config.folders.thumbs + '/' + imageName);
            linkElement.attr('data-med-size', thumbSize);

            if (config.newest_first) {
                linkElement.prependTo($('#galimages'));
            } else {
                linkElement.appendTo($('#galimages'));
            }
        }
    }

    // Open Gallery Overview
    public.openGallery = function () {
        if (config.scrollbar) {
            gallery.addClass('scrollbar');
        }

        gallery.addClass('gallery--open');

        setTimeout(() => gallery.find('.gallery__inner').show(), 300);
    }

    public.resetMailForm = function () {
        $('#send-mail-form').trigger('reset');
        $('#mail-form-message').html('');
    };

    // Countdown Function
    public.startCountdown = function (start, element, cb) {
        let count = 0;
        let current = start;

        function timerFunction() {
            element.text(current);
            current--;

            element.removeClass('tick');

            if (count < start) {
                window.setTimeout(() => element.addClass('tick'), 50);
                window.setTimeout(timerFunction, 1000);
            } else {
                cb();
            }
            count++;
        }
        timerFunction();
    }

    public.printImage = function (imageSrc, cb) {
        modal.open('#print_mesg');

        setTimeout(function () {
            $.ajax({
                url: 'api/print.php?filename=' + encodeURI(imageSrc),
            }).done(function (data) {
                if (config.dev) {
                    console.log(data)
                }

                setTimeout(function () {
                    modal.close('#print_mesg');
                    cb();
                }, 5000);
            });
        }, 1000);
    }

    public.deleteImage = function (imageName, cb) {
        $.ajax({
            url: 'api/deletePhoto.php',
            method: 'POST',
            data: {
                file: imageName,
            },
            success: (data) => {
                cb(data);
            }
        });
    }

    public.toggleMailDialog = function (img) {
        const mail = $('.send-mail');

        if (mail.hasClass('mail-active')) {
            public.resetMailForm();
            mail.removeClass('mail-active').fadeOut('fast');
        } else {
            $('#mail-form-image').val(img);

            mail.addClass('mail-active').fadeIn('fast');
        }
    }

    //Filter
    $('.imageFilter').on('click', function () {
        public.toggleNav();
    });

    $('.sidenav > div').on('click', function () {
        $('.sidenav > div').removeAttr('class');

        $(this).addClass('activeSidenavBtn');

        imgFilter = $(this).attr('id');

        if (config.dev) {
            console.log('Active filter', imgFilter);
        }
    });

    // Take Picture Button
    $('.takePic, .newpic').on('click', function (e) {
        e.preventDefault();

        public.thrill('photo');
    });

    // Take Collage Button
    $('.takeCollage, .newcollage').on('click', function (e) {
        e.preventDefault();

        public.thrill('collage');
    });

    $('#mySidenav .closebtn').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
    });

    // Open Gallery Button
    $('.gallery-button').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
        public.openGallery($(this));
    });

    // Close Gallery Overview
    $('.gallery__close').on('click', function (e) {
        e.preventDefault();

        gallery.find('.gallery__inner').hide();
        gallery.removeClass('gallery--open');
    });

    $('.mailbtn').on('click touchstart', function (e) {
        e.preventDefault();
        e.stopPropagation();

        const img = resultPage.attr('data-img');

        public.toggleMailDialog(img);
    });

    $('#send-mail-form').on('submit', function (e) {
        e.preventDefault();

        const message = $('#mail-form-message');
        message.empty();

        const form = $(this);
        const oldValue = form.find('.btn').html();

        form.find('.btn').html('');

        $.ajax({
            url: 'api/sendPic.php',
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            cache: false,
            success: function (result) {
                if (result.success) {
                    message.fadeIn().html('' + L10N.mailSent + '');
                } else {
                    message.fadeIn().html('' + result.error + '');
                }
            },
            error: function () {
                message.fadeIn('fast').html('' + L10N.mailError + '');
            },
            complete: function () {
                form.find('.btn').html(oldValue);
            }
        });
    });

    $('#send-mail-close').on('click', function () {
        public.resetMailForm();
        $('.send-mail').removeClass('mail-active').fadeOut('fast');
    });

    $('#result').on('click', function () {
        if (!modal.close('#qrCode')) {
            $('.resultInner').toggleClass('show');
        }
    });

    // Show QR Code
    $('.qrbtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        modal.toggle('#qrCode');
    });

    $('.homebtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        public.reloadPage();
    });

    $('#cups-button').on('click', function (ev) {
        ev.preventDefault();

        const url = `http://${location.hostname}:631/jobs/`;
        const features = 'width=1024,height=600,left=0,top=0,screenX=0,screenY=0,resizable=NO,scrollbars=NO';

        window.open(url, 'newwin', features);
    });

    $(document).on('keypress', function (ev) {
        if (config.photo_key && parseInt(config.photo_key, 10) === ev.keyCode) {
            public.thrill('photo');
        }

        if (config.collage_key && parseInt(config.collage_key, 10) === ev.keyCode) {
            public.thrill('collage');
        }
    });

    // clear Timeout to not reset the gallery, if you clicked anywhere
    $(document).on('click', function () {
        if (!startPage.is(':visible')) {
            clearTimeout(timeOut);
            public.resetTimeOut();
        }
    });

    // Disable Right-Click
    if (!config.dev) {
        $(this).on('contextmenu', function (e) {
            e.preventDefault();
        });
    }

    return public;
})();

// Init on domready
$(function () {
    photoBooth.init();
});
<|endoftext|>


<commit_before>const got = require('got');

const request = require('request');
const Buffer = require('Buffer');
const canonicalize = require('canon');
const crypto = require('crypto-js');
const companyCode = 88801;
const Oauth = require('client-oauth2');
const cID = '268b2069-b099-4fa2-8148-1f1c0327fe63';
const cS = 'b383c35d-3c11-4ce6-b631-8767f4c2084b';
const aK = '0dfb11cd-b140-40cd-b65a-220e9998a129';
const aS = '199505e4-9d5f-4ba9-bb96-a3ea8b2f69c1';

const auth = new Oauth({
  clientId: cID,
  clientSecret: cS,
  accessTokenUri: 'https://api.finhacks.id/api/oauth/token',
});

function getAccessToken (handleData) {

  let header = {
    Authorization: 'Basic ' + new Buffer(cID + ':' + cS).toString('base64'),
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  let body = { grant_type: 'client_credentials' };
  let options = {
    method: 'POST',
    url: 'https://api.finhacks.id/api/oauth/token',
    headers: header,
  };

  request.post(options).form(body)
    .on('response', function(response) {
      response.on('data', function(data){
        handleData(data);
      });
    })
    .on('error', function(error) {
      handleData(error);
    });
}

function createHeader (data, body){
  let method = 'post'.toUpperCase();
  console.log(method);
  let url = encodeURI('/ewallet/customers');
  console.log(url);
  let accessToken = data.access_token;
  console.log(accessToken);
  let bd = "";
  if(Object.keys(body).length != 0 && body.constructor === Object){
    bd = JSON.parse(JSON.stringify(body).replace(/\s/g,'').replace(/\r/g,'').replace(/\n/g,'').replace(/\t/g,''));
    console.log(bd);
    bd = crypto.SHA256(bd).toString();
    console.log(bd);
  }
  bd.toLowerCase();

  let dt = new Date();
  dt = dt.toISOString();
  console.log(dt);
  let str = method + ':' + url + ':' + accessToken + ':' + bd + ':' + dt;
  console.log(str);
  let hash = crypto.HmacSHA256(str, aS).toString();
  console.log(hash);
  var header = {
    'Authorization' : 'Bearer '+accessToken,
    'X-BCA-Key' : aK,
    'X-BCA-Signature' : hash,
    'X-BCA-Timestamp' : dt
  }
  console.log(header);
  return header;
}

function registerUser (req, res) {

  let body = {};
  body.CustomerName = req.body.customer_name;
  body.DateOfBirth = req.body.birth_date;
  body.PrimaryID = req.body.primary_id;
  body.MobileNumber = req.body.mobile_number;
  body.EmailAddress = req.body.email_address;
  body.IDNumber = req.body.id_number;
  body.CompanyCode = companyCode;
  body.CostumerNumber = "1111111112";
  let header = {};

  getAccessToken(function(data){
    let header = createHeader(JSON.parse(data), body);
    let options = {
      url: 'https://api.finhacks.id/ewallet/customers',
      headers: header,
      method: 'POST',
    }

    request.post(options).form(body)
      .on('response',function(response){
        response.on('data', function(data){
          res.send(data);
        })
      })
      .on('error', function(error){
        res.send(error);
      });
  });
}

module.exports = {
  getAccessToken,
  registerUser,
};
<commit_msg>checking new credentials<commit_after>const got = require('got');

const request = require('request');
const Buffer = require('Buffer');
const canonicalize = require('canon');
const crypto = require('crypto-js');
const companyCode = 88859;
const Oauth = require('client-oauth2');
const cID = '69c4c406-0ebf-4458-a4ea-9ced54e02311';
const cS = '282828c5-153a-4547-9ee5-3c43497dc0e2';
const aK = 'e3b3f613-17ce-4997-9ce8-fec989268765';
const aS = '18c837cb-b6d3-47cc-9f88-ab0caf2b8d9e';

const auth = new Oauth({
  clientId: cID,
  clientSecret: cS,
  accessTokenUri: 'https://api.finhacks.id/api/oauth/token',
});

function getAccessToken (handleData) {

  let header = {
    Authorization: 'Basic ' + new Buffer(cID + ':' + cS).toString('base64'),
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  let body = { grant_type: 'client_credentials' };
  let options = {
    method: 'POST',
    url: 'https://api.finhacks.id/api/oauth/token',
    headers: header,
  };

  request.post(options).form(body)
    .on('response', function(response) {
      response.on('data', function(data){
        handleData(data);
      });
    })
    .on('error', function(error) {
      handleData(error);
    });
}

function createHeader (data, body){
  let method = 'post'.toUpperCase();
  console.log(method);
  let url = encodeURI('/ewallet/customers');
  console.log(url);
  let accessToken = data.access_token;
  console.log(accessToken);
  let bd = "";
  if(Object.keys(body).length != 0 && body.constructor === Object){
    bd = JSON.parse(JSON.stringify(body).replace(/\s/g,'').replace(/\r/g,'').replace(/\n/g,'').replace(/\t/g,''));
    console.log(bd);
    bd = crypto.SHA256(bd).toString();
    console.log(bd);
  }
  bd.toLowerCase();

  let dt = new Date();
  dt = dt.toISOString();
  console.log(dt);
  let str = method + ':' + url + ':' + accessToken + ':' + bd + ':' + dt;
  console.log(str);
  let hash = crypto.HmacSHA256(str, aS).toString();
  console.log(hash);
  var header = {
    'Authorization' : 'Bearer '+accessToken,
    'X-BCA-Key' : aK,
    'X-BCA-Signature' : hash,
    'X-BCA-Timestamp' : dt
  }
  console.log(header);
  return header;
}

function registerUser (req, res) {

  let body = {};
  body.CustomerName = req.body.customer_name;
  body.DateOfBirth = req.body.birth_date;
  body.PrimaryID = req.body.primary_id;
  body.MobileNumber = req.body.mobile_number;
  body.EmailAddress = req.body.email_address;
  body.IDNumber = req.body.id_number;
  body.CompanyCode = companyCode;
  body.CostumerNumber = "1111111112";
  let header = {};

  getAccessToken(function(data){
    let header = createHeader(JSON.parse(data), body);
    let options = {
      url: 'https://api.finhacks.id/ewallet/customers',
      headers: header,
      method: 'POST',
    }

    request.post(options).form(body)
      .on('response',function(response){
        response.on('data', function(data){
          res.send(data);
        })
      })
      .on('error', function(error){
        res.send(error);
      });
  });
}

module.exports = {
  getAccessToken,
  registerUser,
};
<|endoftext|>


<commit_before>var childProcess = require('child_process')
var baseN = require('base-n')

var charset = process.argv[2];
var strlength = process.argv[3];
var salt = process.argv[4];

var nbCores = require('os').cpus().length;

var b36 = baseN.create({
    characters: charset
});

var max = b36.decode(charset[charset.length - 1].repeat(strlength));
var each = max / nbCores;
var limits = [];

var usedCores = 0;
var currentWorker = 0;

for (var i = 0; i < max; i=i+20000) {
	var j = i + 20000;
	if (j > max) {
		j = max;
	};
	limits.push({start: b36.encode(i), end: b36.encode(j)})
};

main(charset, strlength, salt);

function main()
{
	console.log("Init i : " + nbCores - usedCores);
	for (var i = 0; i < nbCores - usedCores; i++) {
		console.log(i);
		var worker = childProcess.fork('redis-child.js', [limits[currentWorker].start, limits[currentWorker].end, charset, strlength, salt]);
		currentWorker++;
		worker.on('close', function() {
			console.log('finished')
			currentWorker--;
			main();
        });
	};
}<commit_msg>redis strat<commit_after>var childProcess = require('child_process')
var baseN = require('base-n')

var charset = process.argv[2];
var strlength = process.argv[3];
var salt = process.argv[4];

var nbCores = require('os').cpus().length;

var b36 = baseN.create({
    characters: charset
});

var max = b36.decode(charset[charset.length - 1].repeat(strlength));
var each = max / nbCores;
var limits = [];

var usedCores = 0;
var currentWorker = 0;

for (var i = 0; i < max; i=i+20000) {
	var j = i + 20000;
	if (j > max) {
		j = max;
	};
	limits.push({start: b36.encode(i), end: b36.encode(j)})
};

main(charset, strlength, salt);

function main()
{
	console.log("Init i : ");
	console.log(nbCores - usedCores);
	for (var i = 0; i < nbCores - usedCores; i++) {
		console.log(i);
		var worker = childProcess.fork('redis-child.js', [limits[currentWorker].start, limits[currentWorker].end, charset, strlength, salt]);
		currentWorker++;
		worker.on('close', function() {
			console.log('finished')
			currentWorker--;
			main();
        });
	};
}<|endoftext|>


<commit_before>import callable from '../is/callable.js';
import ownValue from '../has/ownValue.js';
import slice from './slice.js';
import apply from './apply.js';

export default function getExpectedValue(expected, value) {
	if (callable(value) && (expected === Function || ownValue(expected, Function)) === false) {
		const args = slice(arguments, 2);
		return apply(value, args[0], args, true);
	}
	return value;
}
<commit_msg>chore: add getExpectedValue fn<commit_after>import callable from '../is/callable.js';
import ownValue from '../has/ownValue.js';
import slice from './slice.js';
import apply from './apply.js';

export default function getExpectedValue(expected, value, args) {
	if (callable(value) && (expected === Function || ownValue(expected, Function)) === false) {
		const context = args ? args[0] : null;
		return apply(value, context, args, true);
	}
	return value;
}
<|endoftext|>