<commit_before>var scl = 0.7;

var baseURL = window.location.href;
baseURL = baseURL.slice(0, baseURL.lastIndexOf("/"));
var url = baseURL + "/dat/maps_krampus.json";
tswMapper.loadViews([url]);

var selViewIndex = 0;
var selMapIndex = 0;
var selCoordIndex = 0;
var selView;
var selMap;
var selCoord;

function setup() {
  var canvas = createCanvas(1080*scl, 1080*scl);
  canvas.parent("canvas");

  refresh();
  noLoop();
}

function draw() {
}

function ring(x, y, r) {
  stroke(255, 215, 0);
  ellipse(x, y, r, r);

  stroke(0);
  ellipse(x, y, r-2, r-2);
  ellipse(x, y, r+2, r+2);
}

function populateControls(level) {
  if (level == undefined) {
    level = 0;
  }

  if (level == 0) {
    if (selView !== undefined) {
      selView.remove();
    }

    selView = createSelect();
    selView.parent("map-view");
    for(var i=0; i < tswMapper.data.views.length; i++) {
      selView.option(tswMapper.data.views[i].name);
    }
    selView.changed(selectViewEvent);
  }

  if (level <= 1) {
    if (selMap !== undefined) {
      selMap.remove();
    }
    var view = getMapView();
    selMap = createSelect();
    selMap.parent("maps");
    for(var i=0; i < view.maps.length; i++) {
      selMap.option(view.maps[i].name);
    }
    selMap.changed(selectMapEvent);
  }

  if (level <= 2) {
    if (selCoord !== undefined) {
      selCoord.remove();
    }
    var map = getMap();
    selCoord = createSelect(true);
    selCoord.parent("coords");
    for (var i=0; i < map.coordinates.length; i++) {
      selCoord.option(map.coordinates[i]);
    }
    selCoord.changed(selectCoordEvent);
  }
}

function getMapView() {
  return tswMapper.data.views[selViewIndex];
}

function getMap() {
  return getMapView().maps[selMapIndex];
}

function getMapCoord() {
  return getMap().coordinates[selCoordIndex];
}

function getMapCoords() {
  return getMap().coordinates;
}

function drawPoints() {
  var m = getMap();
  var c = getMapCoords();
  for(var i = 0; i < c.length; i++) {
    var p = c[i];
    stroke(0);
    fill(255, 0, 0);
    rectMode(CENTER);

    var x = map(p[0], m.xMax, 0, m.imgWidth, 0);
    var y = map(p[1], m.yMax, 0, 0, m.imgHeight);
    rect(x*scl, y*scl, 4, 4);
  }
}

function drawSelected() {
    noFill();
    var r = 15;
    ring(p[0]*scl, height-p[1]*scl, r);
}

function selectViewEvent() {
  var index = 0;

  var v = selView.value();
  var views = tswMapper.data.views;
  for (var i = 0; i < views.length; i++) {
    if (v == views[i].name) {
      index = i;
    }
  }
  selViewIndex = index;
  refresh(1);
}

function selectMapEvent() {
  var index = 0;

  var v = selMap.value();
  var maps = getMapView().maps;
  for (var i = 0; i < maps.length; i++) {
    if (v == maps[i].name) {
      index = i;
    }
  }
  selMapIndex = index;
  refresh(2);
}

function selectCoordEvent() {
  refresh(3);
}

function refresh(level) {
  populateControls(level);

  var i = getMap().url;
  loadImage(i, function(img) {
    image(img, 0, 0, floor(img.width*scl), floor(img.height*scl));
    drawPoints();
  });

}
<commit_msg>Fix scaling and add coordinate selection<commit_after>var scl = 0.7;

var baseURL = window.location.href;
baseURL = baseURL.slice(0, baseURL.lastIndexOf("/"));
var url = baseURL + "/dat/maps_krampus.json";
tswMapper.loadViews([url]);

var selViewIndex = 0;
var selMapIndex = 0;
var selCoordIndex = 0;
var selView;
var selMap;
var selCoord;

function setup() {
  var canvas = createCanvas(1080*scl, 1080*scl);
  canvas.parent("canvas");

  refresh();
  noLoop();
}

function draw() {
}

function ring(x, y, r) {
  stroke(255, 215, 0);
  ellipse(x, y, r, r);

  stroke(0);
  ellipse(x, y, r-2, r-2);
  ellipse(x, y, r+2, r+2);
}

function populateControls(level) {
  if (level == undefined) {
    level = 0;
  }

  if (level == 0) {
    selMapIndex = 0;
    selCoordIndex = 0;

    if (selView !== undefined) {
      selView.remove();
    }

    selView = createSelect();
    selView.parent("map-view");
    for(var i=0; i < tswMapper.data.views.length; i++) {
      selView.option(tswMapper.data.views[i].name);
    }
    selView.changed(selectViewEvent);
  }

  if (level <= 1) {
    selCoordIndex = 0;

    if (selMap !== undefined) {
      selMap.remove();
    }
    var view = getMapView();
    selMap = createSelect();
    selMap.parent("maps");
    for(var i=0; i < view.maps.length; i++) {
      selMap.option(view.maps[i].name);
    }
    selMap.changed(selectMapEvent);
  }

  if (level <= 2) {
    if (selCoord !== undefined) {
      selCoord.remove();
    }
    var map = getMap();
    selCoord = createSelect(true);
    selCoord.parent("coords");
    for (var i=0; i < map.coordinates.length; i++) {
      selCoord.option(map.coordinates[i]);
    }
    selCoord.changed(selectCoordEvent);
  }
}

function getMapView() {
  return tswMapper.data.views[selViewIndex];
}

function getMap() {
  return getMapView().maps[selMapIndex];
}

function getMapCoord() {
  return getMap().coordinates[selCoordIndex];
}

function getMapCoords() {
  return getMap().coordinates;
}

function drawPoints() {
  var m = getMap();
  var c = getMapCoords();
  for(var i = 0; i < c.length; i++) {
    var p = c[i];
    stroke(0);
    fill(255, 0, 0);
    rectMode(CENTER);

    p = scaleCoord(p, m);
    rect(p[0], p[1], 4, 4);
  }
}

function drawSelected() {
  var c = getMapCoord();
  var m = getMap();

  noFill();

  var r = 15;
  c = scaleCoord(c, m);
  ring(c[0], c[1], r);
}

function scaleCoord(coord, map) {
  var x = coord[0]*scl * (map.imgWidth/map.xMax);
  var y = coord[1]*scl * (map.imgHeight/map.yMax);
  c = [x, (map.imgHeight*scl)-y];
  return c;
}

function selectViewEvent() {
  var index = 0;

  var v = selView.value();
  var views = tswMapper.data.views;
  for (var i = 0; i < views.length; i++) {
    if (v == views[i].name) {
      index = i;
    }
  }
  selViewIndex = index;
  refresh(1);
}

function selectMapEvent() {
  var index = 0;

  var v = selMap.value();
  var maps = getMapView().maps;
  for (var i = 0; i < maps.length; i++) {
    if (v == maps[i].name) {
      index = i;
    }
  }
  selMapIndex = index;
  refresh(2);
}

function selectCoordEvent() {
  var index = 0;

  var v = selCoord.value();
  var coords = getMapCoords();
  for (var i = 0; i < coords.length; i++) {
    var coord = coords[i][0] + "," + coords[i][1];
    if (v == coord) {
      index = i;
    }
  }
  selCoordIndex = index;
  refresh(3);
}

function refresh(level) {
  background(255);

  populateControls(level);

  var i = getMap().url;
  loadImage(i, function(img) {
    image(img, 0, 0, floor(img.width*scl), floor(img.height*scl));
    drawPoints();
    drawSelected();
  });

}
<|endoftext|>


<commit_before>'use strict';

var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var request = require('request');
var path = require('path');
var fs = require('fs');
var admzip = require('adm-zip');
var glob = require('glob');
var _ = require('lodash');

module.exports = generators.Base.extend({

	constructor: function () {
		// Calling the super constructor
		generators.Base.apply(this, arguments);

		this.option('name', {desc: 'the name of your app', type: String});
		this.options.name = this.options.name || path.basename(process.cwd());
		this.options.name = _.kebabCase(this.options.name);

		this.preOptions = ['less', 'scss'];
		this.option('pre', {
			desc: 'your desired preprocessor [' + this.preOptions.join('|') + ']',
			type: String,
			defaults: this.preOptions[0]
		});

		this.jsOptions = ['JavaScript', 'TypeScript'];
		this.option('js', {
			desc: 'your desired js compiler [' + this.jsOptions.join('|') + ']',
			type: String,
			defaults: this.jsOptions[0]
		});
	},

	initializing: function () {
		// namics frontend-defaults
		this.srcZip = 'http://github.com/namics/frontend-defaults/archive/master.zip';
		this.destZip = this.templatePath('frontend-defaults.zip');
	},

	prompting: function () {
		var done = this.async();

		this.log(yosay(
			'Welcome to the awe-inspiring ' + chalk.cyan('Nitro') + ' generator!'
		));

		// check whether there is already a nitro application in place and we only have to update the application
		var json = this.fs.readJSON(this.destinationPath('package.json'), {defaults: {"new": true}});

		if (!json.new && _.indexOf(json.keywords, 'nitro') !== -1) {
			// update existing application
			this.prompt([
				{
					name: 'update',
					type: 'confirm',
					message: 'There is already a ' + chalk.cyan('Nitro') + ' application in place! Should I serve you an update?',
					default: true
				}
			], function (props) {
				this.update = props.update;

				if (!this.update) {
					return;
				}

				var config = this.config.getAll();
				if (config) {
					this.options.name = config.name || this.options.name;
					this.options.pre = config.preprocessor || this.options.pre;
					this.options.js = config.jscompiler || this.options.js;
				}

				done();
			}.bind(this));
		}
		else {
			// create new application
			this.prompt([
				{
					name: 'name',
					message: 'What\'s the name of your app?',
					default: this.options.name
				},
				{
					name: 'pre',
					type: 'list',
					message: 'What\'s your desired preprocessor?',
					choices: this.preOptions,
					default: _.indexOf(this.preOptions, this.options.pre) || 0
				},
				{
					name: 'js',
					type: 'list',
					message: 'What\'s your desired javascript compiler?',
					choices: this.jsOptions,
					default: _.indexOf(this.jsOptions, this.options.js) || 0
				}
			], function (props) {
				this.options.name = props.name;
				this.options.pre = props.pre;
				this.options.js = props.js;

				this.config.set('name', this.options.name);
				this.config.set('preprocessor', this.options.pre);
				this.config.set('jscompiler', this.options.js);

				this.config.save();

				done();
			}.bind(this));
		}
	},

	configuring: {
		download: function () {
			var self = this;
			var done = this.async();

			this.log('Download ' + chalk.cyan(this.srcZip));

			var dl = request
				.get(this.srcZip)
				.on('error', function (err) {
					self.log(chalk.red(err));
				})
				.pipe(fs.createWriteStream(this.destZip));

			dl.on('finish', function () {
				done();
			});
		},
		extract: function () {
			var done = this.async();

			this.log('Extracting frontend-defaults templates');
			var zip = new admzip(this.destZip);

			try {
				// extract entrys
				zip.extractEntryTo('frontend-defaults-master/editorconfig/frontend.editorconfig', this.sourceRoot(), false, true);
				zip.extractEntryTo('frontend-defaults-master/gitignore/nitro.gitignore', this.sourceRoot(), false, true);
				zip.extractEntryTo('frontend-defaults-master/gitattributes/.gitattributes', this.sourceRoot(), false, true);
				zip.extractEntryTo('frontend-defaults-master/jshintrc/.jshintrc', this.sourceRoot(), false, true);

				// rename files
				fs.renameSync(this.templatePath('frontend.editorconfig'), this.templatePath('.editorconfig'));
				fs.renameSync(this.templatePath('nitro.gitignore'), this.templatePath('.gitignore'));
			}
			catch (e) {
				this.log(chalk.red(e.message));
			}

			// remove zip
			fs.unlinkSync(this.destZip);

			done();
		}
	},

	writing: {
		app: function () {
			this.log('Scaffolding your app');

			var files = glob.sync('**/*', {cwd: this.sourceRoot(), nodir: true, dot: true});

			var tplFiles = [
				// files to process with copyTpl
				'package.json',
				'config.json',
				'gulpfile.js',
				'gulp/compile-css.js',
				'gulp/compile-js.js',
				'gulp/utils.js',
				'gulp/watch-assets.js',
				'.jshintignore'
			];
			var ignores = [
				// files to ignore
				'.DS_Store',
				'.npmignore',
				'frontend-defaults.zip'
			];
			var typeScriptFiles = [
				// files only for this.options.js==='TypeScript'
				'tsd.json',
				'gulp/compile-ts.js'
			];

			var data = {
				name: this.options.name,
				options: this.options
			};

			files.forEach(function (file) {
				// exclude ignores
				if (_.indexOf(ignores, file) !== -1) {
					return;
				}

				// TypeScript only Files
				if (this.options.js !== 'TypeScript') {
					if (_.indexOf(typeScriptFiles, file) !== -1) {
						return;
					}
				}

				// ignore everything under assets, components and views
				if (this.update) {
					if (_.startsWith(file, 'assets') ||
						_.startsWith(file, 'components') ||
						_.startsWith(file, 'views')) {
						return;
					}
				}

				// exclude unecessary preprocessor files
				var ext = path.extname(file).substring(1);

				if (_.indexOf(this.preOptions, ext) !== -1 && this.options.pre !== ext) {
					return;
				}

				if ((_.startsWith(file, 'project') || _.startsWith(file, 'components')) && (ext === 'js' || ext === 'ts') && (this.options.js === 'JavaScript' && ext !== 'js' || this.options.js === 'TypeScript' && ext !== 'ts')) {
					return;
				}

				if (_.indexOf(tplFiles, file) !== -1) {
					this.fs.copyTpl(this.templatePath(file), this.destinationPath(file), data);
					return;
				}

				this.fs.copy(this.templatePath(file), this.destinationPath(file));
			}, this);

		}
	},

	install: function () {
		this.installDependencies({
			skipInstall: this.options['skip-install']
		});

		if (this.options.js === 'TypeScript') {
			var that = this;
			this.spawnCommand('tsd', ['reinstall']).on('close', function () {
				that.spawnCommand('tsd', ['rebundle']);
			});
		}
	},

	end: function () {
		this.log(chalk.green('All done – have fun'));
	}
});
<commit_msg>remember user inputs for later reruns of yo:nitro<commit_after>'use strict';

var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var request = require('request');
var path = require('path');
var fs = require('fs');
var admzip = require('adm-zip');
var glob = require('glob');
var _ = require('lodash');

module.exports = generators.Base.extend({

	constructor: function () {
		// Calling the super constructor
		generators.Base.apply(this, arguments);

		this.option('name', {desc: 'the name of your app', type: String});
		this.options.name = this.options.name || path.basename(process.cwd());
		this.options.name = _.kebabCase(this.options.name);

		this.preOptions = ['less', 'scss'];
		this.option('pre', {
			desc: 'your desired preprocessor [' + this.preOptions.join('|') + ']',
			type: String,
			defaults: this.preOptions[0]
		});

		this.jsOptions = ['JavaScript', 'TypeScript'];
		this.option('js', {
			desc: 'your desired js compiler [' + this.jsOptions.join('|') + ']',
			type: String,
			defaults: this.jsOptions[0]
		});
	},

	initializing: function () {
		// namics frontend-defaults
		this.srcZip = 'http://github.com/namics/frontend-defaults/archive/master.zip';
		this.destZip = this.templatePath('frontend-defaults.zip');
	},

	prompting: function () {
		var done = this.async();

		this.log(yosay(
			'Welcome to the awe-inspiring ' + chalk.cyan('Nitro') + ' generator!'
		));

		// check whether there is already a nitro application in place and we only have to update the application
		var json = this.fs.readJSON(this.destinationPath('package.json'), {defaults: {"new": true}});

		if (!json.new && _.indexOf(json.keywords, 'nitro') !== -1) {
			// update existing application
			this.prompt([
				{
					name: 'update',
					type: 'confirm',
					message: 'There is already a ' + chalk.cyan('Nitro') + ' application in place! Should I serve you an update?',
					default: true
				}
			], function (props) {
				this.update = props.update;

				if (!this.update) {
					return;
				}

				var config = this.config.getAll();
				if (config) {
					this.options.name = config.name || this.options.name;
					this.options.pre = config.preprocessor || this.options.pre;
					this.options.js = config.jscompiler || this.options.js;
				}

				done();
			}.bind(this));
		}
		else {
			// create new application
			this.prompt([
				{
					name: 'name',
					message: 'What\'s the name of your app?',
					default: this.options.name
				},
				{
					name: 'pre',
					type: 'list',
					message: 'What\'s your desired preprocessor?',
					choices: this.preOptions,
					default: _.indexOf(this.preOptions, this.options.pre) || 0,
					store: true
				},
				{
					name: 'js',
					type: 'list',
					message: 'What\'s your desired javascript compiler?',
					choices: this.jsOptions,
					default: _.indexOf(this.jsOptions, this.options.js) || 0,
					store: true
				}
			], function (props) {
				this.options.name = props.name;
				this.options.pre = props.pre;
				this.options.js = props.js;

				this.config.set('name', this.options.name);
				this.config.set('preprocessor', this.options.pre);
				this.config.set('jscompiler', this.options.js);

				this.config.save();

				done();
			}.bind(this));
		}
	},

	configuring: {
		download: function () {
			var self = this;
			var done = this.async();

			this.log('Download ' + chalk.cyan(this.srcZip));

			var dl = request
				.get(this.srcZip)
				.on('error', function (err) {
					self.log(chalk.red(err));
				})
				.pipe(fs.createWriteStream(this.destZip));

			dl.on('finish', function () {
				done();
			});
		},
		extract: function () {
			var done = this.async();

			this.log('Extracting frontend-defaults templates');
			var zip = new admzip(this.destZip);

			try {
				// extract entrys
				zip.extractEntryTo('frontend-defaults-master/editorconfig/frontend.editorconfig', this.sourceRoot(), false, true);
				zip.extractEntryTo('frontend-defaults-master/gitignore/nitro.gitignore', this.sourceRoot(), false, true);
				zip.extractEntryTo('frontend-defaults-master/gitattributes/.gitattributes', this.sourceRoot(), false, true);
				zip.extractEntryTo('frontend-defaults-master/jshintrc/.jshintrc', this.sourceRoot(), false, true);

				// rename files
				fs.renameSync(this.templatePath('frontend.editorconfig'), this.templatePath('.editorconfig'));
				fs.renameSync(this.templatePath('nitro.gitignore'), this.templatePath('.gitignore'));
			}
			catch (e) {
				this.log(chalk.red(e.message));
			}

			// remove zip
			fs.unlinkSync(this.destZip);

			done();
		}
	},

	writing: {
		app: function () {
			this.log('Scaffolding your app');

			var files = glob.sync('**/*', {cwd: this.sourceRoot(), nodir: true, dot: true});

			var tplFiles = [
				// files to process with copyTpl
				'package.json',
				'config.json',
				'gulpfile.js',
				'gulp/compile-css.js',
				'gulp/compile-js.js',
				'gulp/utils.js',
				'gulp/watch-assets.js',
				'.jshintignore'
			];
			var ignores = [
				// files to ignore
				'.DS_Store',
				'.npmignore',
				'frontend-defaults.zip'
			];
			var typeScriptFiles = [
				// files only for this.options.js==='TypeScript'
				'tsd.json',
				'gulp/compile-ts.js'
			];

			var data = {
				name: this.options.name,
				options: this.options
			};

			files.forEach(function (file) {
				// exclude ignores
				if (_.indexOf(ignores, file) !== -1) {
					return;
				}

				// TypeScript only Files
				if (this.options.js !== 'TypeScript') {
					if (_.indexOf(typeScriptFiles, file) !== -1) {
						return;
					}
				}

				// ignore everything under assets, components and views
				if (this.update) {
					if (_.startsWith(file, 'assets') ||
						_.startsWith(file, 'components') ||
						_.startsWith(file, 'views')) {
						return;
					}
				}

				// exclude unecessary preprocessor files
				var ext = path.extname(file).substring(1);

				if (_.indexOf(this.preOptions, ext) !== -1 && this.options.pre !== ext) {
					return;
				}

				if ((_.startsWith(file, 'project') || _.startsWith(file, 'components')) && (ext === 'js' || ext === 'ts') && (this.options.js === 'JavaScript' && ext !== 'js' || this.options.js === 'TypeScript' && ext !== 'ts')) {
					return;
				}

				if (_.indexOf(tplFiles, file) !== -1) {
					this.fs.copyTpl(this.templatePath(file), this.destinationPath(file), data);
					return;
				}

				this.fs.copy(this.templatePath(file), this.destinationPath(file));
			}, this);

		}
	},

	install: function () {
		this.installDependencies({
			skipInstall: this.options['skip-install']
		});

		if (this.options.js === 'TypeScript') {
			var that = this;
			this.spawnCommand('tsd', ['reinstall']).on('close', function () {
				that.spawnCommand('tsd', ['rebundle']);
			});
		}
	},

	end: function () {
		this.log(chalk.green('All done – have fun'));
	}
});
<|endoftext|>


<commit_before>var pos;

function setup(){
    var myCanvas = createCanvas(windowWidth, windowHeight*0.5);
    myCanvas.parent('myContainer');
    background(255);
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight);
    background(256);
}

//function mouseWheel(event) {
//    //event.delta can be +1 or -1 depending
//    //on the wheel/scroll direction
//    //move the square one pixel up or down
//    pos += event.delta;
//
//    //uncomment to block page scrolling
//    //return false;
//}

var noiseScale=0.02;

function draw() {
    background(255);
    for (var x=0; x < windowWidth; x++) {
        var noiseVal = noise((pos+x)*noiseScale,
            pos*noiseScale);
        stroke(noiseVal*255*1.5,244,244);
        line(x, pos+noiseVal*80, x, windowHeight);
    }
}

function getScrollTop(){
    pos = $(window).scrollTop()*0.01;
}

$(window).on("load scroll", getScrollTop);<commit_msg>update<commit_after>var pos;

function setup(){
    var myCanvas = createCanvas(windowWidth, windowHeight*0.5);
    myCanvas.parent('myContainer');
    background(255);
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight);
    background(256);
}

//function mouseWheel(event) {
//    //event.delta can be +1 or -1 depending
//    //on the wheel/scroll direction
//    //move the square one pixel up or down
//    pos += event.delta;
//
//    //uncomment to block page scrolling
//    //return false;
//}

var noiseScale=0.02;

function draw() {
    background(255);
    for (var x=0; x < windowWidth; x++) {
        var noiseVal = noise((pos+x)*noiseScale,
            pos*noiseScale);
        stroke(noiseVal*255*1.5,244,244);
        line(x, pos+noiseVal*80, x, windowHeight);
    }
}

function getScrollTop(){
    pos = $(window).scrollTop()*0.01;
    draw();
}

$(window).on("load scroll", getScrollTop);<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import net from 'net';
import Root from './containers/Root';
import { configureStore, history } from './store/configureStore';
import './app.global.scss';

import { changeCoin } from './helpers/global';

const store = configureStore();
console.log('process.env', process.env);

let isFirstTime = false;

/*
  case1: disable 20
  case2: disable 50
  case3: disable 100
  default: disable 500
*/
class Server {
  canReceiveCoin;
  baht1;
  baht5;
  baht10;
  limitBanknote;
  constructor(mode) {
    this.canReceiveCoin = false;
    switch (mode) {
      case 1:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 1;
        break;
      case 2:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 2;
        break;
      case 3:
        this.baht1 = 5;
        this.baht5 = 5;
        this.baht10 = 5;
        break;
      default:
        this.baht1 = 10;
        this.baht5 = 10;
        this.baht10 = 10;
        break;
    }
    this.limitBanknote = 500;
  }
  getCanReceiveCoin() {
    return this.canReceiveCoin;
  }
  setCanReceiveCoin(canReceiveCoin) {
    this.canReceiveCoin = canReceiveCoin;
  }
  getCoinOneBaht() {
    return this.baht1;
  }
  getCoinFiveBaht() {
    return this.baht5;
  }
  getCoinTenBaht() {
    return this.baht10;
  }
  addCoinOneBaht(number) {
    this.baht1 += number;
  }
  addCoinFiveBaht(number) {
    this.baht5 += number;
  }
  addCoinTenBaht(number) {
    this.baht10 += number;
  }
  minusCoinOneBaht(number) {
    this.baht1 += number;
  }
  minusCoinFiveBaht(number) {
    this.baht5 += number;
  }
  minusCoinTenBaht(number) {
    this.baht10 += number;
  }
  canChange(changeCoins) {
    const minimumExistingCoin = 3;
    // {baht1: 0, baht5: 1, baht10: 4}
    if (changeCoins.baht1 > 0 && this.getCoinOneBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht5 > 0 && this.getCoinFiveBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht10 > 0 && this.getCoinTenBaht() <= minimumExistingCoin) return false;
    return true;
  }
  getLimitBanknote() {
    return this.limitBanknote;
  }
  setLimitBanknote(banknoteValue) {
    this.limitBanknote = banknoteValue;
  }
  verifyCanReceiveBanknote(banknoteValue) {
    if (banknoteValue >= this.getLimitBanknote()) return false;
    return true;
  }
}

const serverLog = 'background: blue; color: #fff';

if (process.env.NODE_ENV !== 'production') {
  console.log('development:createServer at 127.0.0.1:1337');
  const server = net.createServer(socket => {
    const sv = new Server(4);
    console.log('%c Init Server:', serverLog, sv);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 0,
        }),
      );
    }, 500);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 1,
        }),
      );
    }, 2000);

    // socket.pipe(socket);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 0,
    //       sensor: 'temp',
    //       msg: {
    //         temp: 4.3,
    //       },
    //     }),
    //   );
    // }, 20000);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 2,
    //       msg: 50,
    //     }),
    //   );
    // }, 10000);
    socket.on('data', data => {
      // ======================================================
      // Received data from client.write
      // ======================================================
      const dataChunk = data.toString('utf8');
      console.log('%c Server: Received: ', serverLog, dataChunk);
      const objectData = JSON.parse(dataChunk);
      // ======================================================
      // Declare Protocols
      // ======================================================
      // ======================================================
      // DROP PRODUCT
      // ======================================================
      if (objectData.action === 1 && objectData.msg !== 'failed') {
        console.log('%c Server: Drop product', serverLog, data);
        const successPercent = Math.floor(((Math.random() * 10))) + 1;
        console.log('successPercent', successPercent);
        if (successPercent <= 10 && !isFirstTime) {
          // isFirstTime = true;
          setTimeout(() => {
            socket.write(
              JSON.stringify({
                action: 1,
                result: 'success',
                description: 'Item XX delivered',
              }),
            );
          }, 5000);
        } else {
          isFirstTime = false;
          setTimeout(() => {
            socket.write(
              JSON.stringify({
                action: 1,
                result: 'fail',
                description: 'Item delivered failed',
              }),
            );
          }, 5000);
        }
      }
      // ======================================================
      // CASH CHANGE
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'coin') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash Change', serverLog, Number(objectData.msg), changeCoin(Number(objectData.msg)));
          const changeCoins = changeCoin(Number(objectData.msg));
          if (sv.canChange(changeCoins)) {
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'success',
                description: 'cash change completed',
              }),
            );
          } else {
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'fail',
                description: 'cash change failed',
              }),
            );
          }
        } else {
          console.error('Server cannot change cash because Money Box is enable');
        }
      }
      // ======================================================
      // CASH REMAINING
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'remain') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash remaining', serverLog, sv);
          socket.write(
            JSON.stringify({
              action: 2,
              result: 'success',
              remain: {
                baht1: sv.getCoinOneBaht(),
                baht5: sv.getCoinFiveBaht(),
                baht10: sv.getCoinTenBaht(),
              },
            }),
          );
        } else {
          console.error('Server cannot show remaining because Money Box is enable');
        }
      }
      // ======================================================
      // RESET TAIKO
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'bill' && objectData.msg === '01') {
        // reset TAIKO
        socket.write(
          JSON.stringify({
            action: 2,
            msg: '01',
            result: 'success',
            description: 'taiko reset completed'
          }),
        );
      }
      // ======================================================
      // ENABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '020') {
        // enable money box
        const success = {
          action: 2,
          msg: '020',
          result: 'success',
          description: 'Disable Off.'
        };
        const failed = {
          action: 2,
          msg: '020',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 4;
        if (isSuccess) sv.setCanReceiveCoin(true);
        socket.write(
          JSON.stringify(isSuccess ? success : failed),
        );
      }
      // ======================================================
      // DISABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '021') {
        // disable money box
        const success = {
          action: 2,
          msg: '021',
          result: 'success',
          description: 'Disable On.'
        };
        const failed = {
          action: 2,
          msg: '021',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 4;
        if (isSuccess) sv.setCanReceiveCoin(false);
        socket.write(
          JSON.stringify(isSuccess ? success : failed),
        );
      }
      if (objectData.action === 2 && objectData.mode === 'limit') {
        const success = {
          action: 2,
          result: 'success',
          description: `Cash is now limit to ${objectData.msg}`
        };
        sv.setLimitBanknote(Number(objectData.msg));
        // const failed = {
        //   action: 2,
        //   msg: '021',
        //   result: 'failed',
        //   description: 'failed please try again'
        // };
        // const isSuccess = true; // _.random(1, 5) <= 4;
        socket.write(
          // JSON.stringify(isSuccess ? success : failed),
          JSON.stringify(success),
        );
      }
      // ======================================================
      // INSERT COIN
      // ======================================================
      if (objectData.action === 999) {
        if (sv.getCanReceiveCoin()) {
          const insertedValue = Number(objectData.msg);
          const canReceiveBanknote = sv.verifyCanReceiveBanknote(insertedValue);
          if (canReceiveBanknote) {
            if (insertedValue === 1) {
              sv.addCoinOneBaht(1);
            } else if (insertedValue === 5) {
              sv.addCoinFiveBaht(1);
            } else if (insertedValue === 10) {
              sv.addCoinTenBaht(1);
            }
            socket.write(
              JSON.stringify({
                action: 2,
                msg: insertedValue,
              }),
            );
          } else {
            // คืนเงิน
            console.log('Cannot receive this banknote', insertedValue);
          }
        } else {
          // MONEY BOX IS DISABLE
          console.log('Cannot receive money because money box is disable');
        }
      }
    });
    socket.on('error', err => {
      console.error(err);
    });
  });
  // server.listen(8080, '192.168.1.41');
  server.listen(1337, '127.0.0.1');
}
render(
  <AppContainer>
    <Root store={store} history={history} />
  </AppContainer>,
  document.getElementById('root'),
);

if (module.hot) {
  module.hot.accept('./containers/Root', () => {
    const NextRoot = require('./containers/Root'); // eslint-disable-line global-require
    render(
      <AppContainer>
        <NextRoot store={store} history={history} />
      </AppContainer>,
      document.getElementById('root'),
    );
  });
}

export default store;
<commit_msg>Inc failed rate of en/dis money box<commit_after>import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import net from 'net';
import Root from './containers/Root';
import { configureStore, history } from './store/configureStore';
import './app.global.scss';

import { changeCoin } from './helpers/global';

const store = configureStore();
console.log('process.env', process.env);

let isFirstTime = false;

/*
  case1: disable 20
  case2: disable 50
  case3: disable 100
  default: disable 500
*/
class Server {
  canReceiveCoin;
  baht1;
  baht5;
  baht10;
  limitBanknote;
  constructor(mode) {
    this.canReceiveCoin = false;
    switch (mode) {
      case 1:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 1;
        break;
      case 2:
        this.baht1 = 1;
        this.baht5 = 1;
        this.baht10 = 2;
        break;
      case 3:
        this.baht1 = 5;
        this.baht5 = 5;
        this.baht10 = 5;
        break;
      default:
        this.baht1 = 10;
        this.baht5 = 10;
        this.baht10 = 10;
        break;
    }
    this.limitBanknote = 500;
  }
  getCanReceiveCoin() {
    return this.canReceiveCoin;
  }
  setCanReceiveCoin(canReceiveCoin) {
    this.canReceiveCoin = canReceiveCoin;
  }
  getCoinOneBaht() {
    return this.baht1;
  }
  getCoinFiveBaht() {
    return this.baht5;
  }
  getCoinTenBaht() {
    return this.baht10;
  }
  addCoinOneBaht(number) {
    this.baht1 += number;
  }
  addCoinFiveBaht(number) {
    this.baht5 += number;
  }
  addCoinTenBaht(number) {
    this.baht10 += number;
  }
  minusCoinOneBaht(number) {
    this.baht1 += number;
  }
  minusCoinFiveBaht(number) {
    this.baht5 += number;
  }
  minusCoinTenBaht(number) {
    this.baht10 += number;
  }
  canChange(changeCoins) {
    const minimumExistingCoin = 3;
    // {baht1: 0, baht5: 1, baht10: 4}
    if (changeCoins.baht1 > 0 && this.getCoinOneBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht5 > 0 && this.getCoinFiveBaht() <= minimumExistingCoin) return false;
    if (changeCoins.baht10 > 0 && this.getCoinTenBaht() <= minimumExistingCoin) return false;
    return true;
  }
  getLimitBanknote() {
    return this.limitBanknote;
  }
  setLimitBanknote(banknoteValue) {
    this.limitBanknote = banknoteValue;
  }
  verifyCanReceiveBanknote(banknoteValue) {
    if (banknoteValue >= this.getLimitBanknote()) return false;
    return true;
  }
}

const serverLog = 'background: blue; color: #fff';

if (process.env.NODE_ENV !== 'production') {
  console.log('development:createServer at 127.0.0.1:1337');
  const server = net.createServer(socket => {
    const sv = new Server(4);
    console.log('%c Init Server:', serverLog, sv);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 0,
        }),
      );
    }, 500);
    setTimeout(() => {
      socket.write(
        JSON.stringify({
          action: 4,
          initialized: 1,
        }),
      );
    }, 2000);

    // socket.pipe(socket);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 0,
    //       sensor: 'temp',
    //       msg: {
    //         temp: 4.3,
    //       },
    //     }),
    //   );
    // }, 20000);
    // setInterval(() => {
    //   socket.write(
    //     JSON.stringify({
    //       action: 2,
    //       msg: 50,
    //     }),
    //   );
    // }, 10000);
    socket.on('data', data => {
      // ======================================================
      // Received data from client.write
      // ======================================================
      const dataChunk = data.toString('utf8');
      console.log('%c Server: Received: ', serverLog, dataChunk);
      const objectData = JSON.parse(dataChunk);
      // ======================================================
      // Declare Protocols
      // ======================================================
      // ======================================================
      // DROP PRODUCT
      // ======================================================
      if (objectData.action === 1 && objectData.msg !== 'failed') {
        console.log('%c Server: Drop product', serverLog, data);
        const successPercent = Math.floor(((Math.random() * 10))) + 1;
        console.log('successPercent', successPercent);
        if (successPercent <= 10 && !isFirstTime) {
          // isFirstTime = true;
          setTimeout(() => {
            socket.write(
              JSON.stringify({
                action: 1,
                result: 'success',
                description: 'Item XX delivered',
              }),
            );
          }, 5000);
        } else {
          isFirstTime = false;
          setTimeout(() => {
            socket.write(
              JSON.stringify({
                action: 1,
                result: 'fail',
                description: 'Item delivered failed',
              }),
            );
          }, 5000);
        }
      }
      // ======================================================
      // CASH CHANGE
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'coin') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash Change', serverLog, Number(objectData.msg), changeCoin(Number(objectData.msg)));
          const changeCoins = changeCoin(Number(objectData.msg));
          if (sv.canChange(changeCoins)) {
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'success',
                description: 'cash change completed',
              }),
            );
          } else {
            socket.write(
              JSON.stringify({
                action: 2,
                result: 'fail',
                description: 'cash change failed',
              }),
            );
          }
        } else {
          console.error('Server cannot change cash because Money Box is enable');
        }
      }
      // ======================================================
      // CASH REMAINING
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'remain') {
        if (!sv.getCanReceiveCoin()) {
          console.log('%c Server: Cash remaining', serverLog, sv);
          socket.write(
            JSON.stringify({
              action: 2,
              result: 'success',
              remain: {
                baht1: sv.getCoinOneBaht(),
                baht5: sv.getCoinFiveBaht(),
                baht10: sv.getCoinTenBaht(),
              },
            }),
          );
        } else {
          console.error('Server cannot show remaining because Money Box is enable');
        }
      }
      // ======================================================
      // RESET TAIKO
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'bill' && objectData.msg === '01') {
        // reset TAIKO
        socket.write(
          JSON.stringify({
            action: 2,
            msg: '01',
            result: 'success',
            description: 'taiko reset completed'
          }),
        );
      }
      // ======================================================
      // ENABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '020') {
        // enable money box
        const success = {
          action: 2,
          msg: '020',
          result: 'success',
          description: 'Disable Off.'
        };
        const failed = {
          action: 2,
          msg: '020',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 3;
        if (isSuccess) sv.setCanReceiveCoin(true);
        socket.write(
          JSON.stringify(isSuccess ? success : failed),
        );
      }
      // ======================================================
      // DISABLE MONEY BOX
      // ======================================================
      if (objectData.action === 2 && objectData.mode === 'both' && objectData.msg === '021') {
        // disable money box
        const success = {
          action: 2,
          msg: '021',
          result: 'success',
          description: 'Disable On.'
        };
        const failed = {
          action: 2,
          msg: '021',
          result: 'failed',
          description: 'failed please try again'
        };
        const isSuccess = _.random(1, 5) <= 3;
        if (isSuccess) sv.setCanReceiveCoin(false);
        socket.write(
          JSON.stringify(isSuccess ? success : failed),
        );
      }
      if (objectData.action === 2 && objectData.mode === 'limit') {
        const success = {
          action: 2,
          result: 'success',
          description: `Cash is now limit to ${objectData.msg}`
        };
        sv.setLimitBanknote(Number(objectData.msg));
        // const failed = {
        //   action: 2,
        //   msg: '021',
        //   result: 'failed',
        //   description: 'failed please try again'
        // };
        // const isSuccess = true; // _.random(1, 5) <= 4;
        socket.write(
          // JSON.stringify(isSuccess ? success : failed),
          JSON.stringify(success),
        );
      }
      // ======================================================
      // INSERT COIN
      // ======================================================
      if (objectData.action === 999) {
        if (sv.getCanReceiveCoin()) {
          const insertedValue = Number(objectData.msg);
          const canReceiveBanknote = sv.verifyCanReceiveBanknote(insertedValue);
          if (canReceiveBanknote) {
            if (insertedValue === 1) {
              sv.addCoinOneBaht(1);
            } else if (insertedValue === 5) {
              sv.addCoinFiveBaht(1);
            } else if (insertedValue === 10) {
              sv.addCoinTenBaht(1);
            }
            socket.write(
              JSON.stringify({
                action: 2,
                msg: insertedValue,
              }),
            );
          } else {
            // คืนเงิน
            console.log('Cannot receive this banknote', insertedValue);
          }
        } else {
          // MONEY BOX IS DISABLE
          console.log('Cannot receive money because money box is disable');
        }
      }
    });
    socket.on('error', err => {
      console.error(err);
    });
  });
  // server.listen(8080, '192.168.1.41');
  server.listen(1337, '127.0.0.1');
}
render(
  <AppContainer>
    <Root store={store} history={history} />
  </AppContainer>,
  document.getElementById('root'),
);

if (module.hot) {
  module.hot.accept('./containers/Root', () => {
    const NextRoot = require('./containers/Root'); // eslint-disable-line global-require
    render(
      <AppContainer>
        <NextRoot store={store} history={history} />
      </AppContainer>,
      document.getElementById('root'),
    );
  });
}

export default store;
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var fs = require('fs-extra');
var path = require('path');
var cc = require('change-case');

module.exports = yeoman.generators.Base.extend({

  settings: function () {
    this.settings = {
      phpNamespace: cc.pascalCase(this.appname),
      phpClassName: cc.pascalCase(this.appname) + 'Command', // PHP file and classname (with the 'Command' suffix)
      commandNamespace: cc.paramCase(this.appname), // command namespace, e.g. foobar:example (foobar)
      commandName: cc.paramCase('example'), // command name, e.g. foobar:example (example)
      appName: cc.titleCase(this.appname), // app name used in composer and app settings
      appVersion: '1.0', // app version used in composer and app settings
      entrypointName: cc.paramCase(this.appname), // app entry point / php executable
    };
  },

  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  install: function () {
    this.installDependencies();
  }
});
<commit_msg>commented away for now<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var fs = require('fs-extra');
var path = require('path');
var cc = require('change-case');

module.exports = yeoman.generators.Base.extend({

  settings: function () {
    this.settings = {
      phpNamespace: cc.pascalCase(this.appname),
      phpClassName: cc.pascalCase(this.appname) + 'Command', // PHP file and classname (with the 'Command' suffix)
      commandNamespace: cc.paramCase(this.appname), // command namespace, e.g. foobar:example (foobar)
      commandName: cc.paramCase('example'), // command name, e.g. foobar:example (example)
      appName: cc.titleCase(this.appname), // app name used in composer and app settings
      appVersion: '1.0', // app version used in composer and app settings
      entrypointName: cc.paramCase(this.appname), // app entry point / php executable
    };
  },

  // prompting: function () {
  //   var done = this.async();

  //   // Have Yeoman greet the user.
  //   this.log(yosay(
  //     'Welcome to the slick ' + chalk.red('SymfonyConsoleScaffolding') + ' generator!'
  //   ));

  //   var prompts = [{
  //     type: 'confirm',
  //     name: 'someOption',
  //     message: 'Would you like to enable this option?',
  //     default: true
  //   }];

  //   this.prompt(prompts, function (props) {
  //     this.props = props;
  //     // To access props later use this.props.someOption;

  //     done();
  //   }.bind(this));
  // },

  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  install: function () {
    this.installDependencies();
  }
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var mv = require('mv');
var async = require('async');
var mkdirp = require('mkdirp');
var absorb = require('absorb');
var path = require('path');
var util = require('util');
var yeoman = require('yeoman-generator');
var pathInstall = '';

var Generator = module.exports = function Generator(args, options) {
  yeoman.generators.Base.apply(this, arguments);
};

util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.askFor = function askFor(argument) {
    var cb = this.async();
    var options = ['yes', 'no'];
    var prompts = [{
        type: 'list',
        name: 'install',
        message: 'Would you like to install a frontsize theme?',
        choices: options
    },{
        when: function (response) {
            return response.install == 'yes';
        },
        type: 'input',
        name: 'path',
        message: 'Where do you want to install frontsize theme? (Ex: css/frontsize/your_theme_name)',
        defaults: 'css/frontsize'
    }];

    this.prompt(prompts, function (props) {
        this.pathInstall = props.path;
        cb();
    }.bind(this));
};

Generator.prototype.install = function downloadFiles() {
    console.info('download');
    this.bowerInstall('frontsize-sass', { save: true });
};

Generator.prototype.end = function moveFiles() {
    console.info('move');
    var here = this;
    var directory = 'bower_components';
    var pattern = /\/$/;
    if (fs.existsSync('./.bowerrc')) {
        var obj = JSON.parse(fs.readFileSync('./.bowerrc', 'utf8'));
        if(obj.directory !== undefined){
            directory = obj.directory;
        }
    }
    directory = directory.replace(pattern, '');

    //check if package.json exists in root
    if (fs.existsSync('./package.json')) {
        var dependenciesFrontsize = '';
        var dependenciesRoot = '';

        var packageJsonFrontsize = JSON.parse(fs.readFileSync(directory + '/frontsize-sass/package.json', 'utf8'));
        if(packageJsonFrontsize.dependencies !== undefined){
            dependenciesFrontsize = packageJsonFrontsize.dependencies;
        }
        var packageJsonRoot = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
        if(packageJsonRoot.dependencies !== undefined){
            dependenciesRoot = packageJsonRoot.dependencies;
        }

        if(dependenciesRoot != ''){
            packageJsonRoot.dependencies = absorb(dependenciesRoot, dependenciesFrontsize);
        }
        else{
            packageJsonRoot.dependencies = dependenciesFrontsize;
        }

        fs.writeFile('./package.json', JSON.stringify(packageJsonRoot, null, 2), function(err) {
            if(err) {
                return console.log(err);
            }
        });
    }
    else{
        fs.createReadStream(directory + '/frontsize-sass/package.json').pipe(fs.createWriteStream('./package.json'));
    }

    //quando inserisco il path devo verificare che non esista e lo creo, se esiste gia la cartella theme al suo interno dare errore
    if(fs.exists(here.pathInstall)){
        return console.log('Path already exist!');
    }
    else{
        //create directory
        mkdirp(here.pathInstall);

        if(here.pathInstall.substr(here.pathInstall.length - 1) != '/'){
            here.pathInstall = here.pathInstall + '/';
        }

        //move themes directory
        mv(directory + '/frontsize-sass/themes/default/', here.pathInstall, {mkdirp: true}, function(err) {
            if((err != undefined) && (err != null)){
                return console.log('Error moving theme files! ' + err);
            }
            else{
                mv(directory + '/frontsize-sass/compile.scss', here.pathInstall + 'compile.scss', function(err) {
                    if((err != undefined) && (err != null)){
                        return console.log('Error moving file compile.scss! ' + err);
                    }
                    else{
                        mv(directory + '/frontsize-sass/gulpfile.js', 'gulpfile.js', function(err) {
                            if((err != undefined) && (err != null)){
                                return console.log('Error moving file gulpfile.js! ' + err);
                            }
                            else{
                                mv(directory + '/frontsize-sass/frontsize.yml.dist', 'frontsize.yml', function(err) {
                                    if((err != undefined) && (err != null)){
                                        return console.log('Error moving file frontsize.yml! ' + err);
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    }

    /*
    /target/path/themes/nome/ --> DONE
    /target/path/compile.scss
    /gulpfile.js
    /frontsize.yml
    /package.json DONE
    */
};
<commit_msg>removed some lines<commit_after>'use strict';

var fs = require('fs');
var mv = require('mv');
var async = require('async');
var mkdirp = require('mkdirp');
var absorb = require('absorb');
var path = require('path');
var util = require('util');
var yeoman = require('yeoman-generator');
var pathInstall = '';

var Generator = module.exports = function Generator(args, options) {
  yeoman.generators.Base.apply(this, arguments);
};

util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.askFor = function askFor(argument) {
    var cb = this.async();
    var options = ['yes', 'no'];
    var prompts = [{
        type: 'list',
        name: 'install',
        message: 'Would you like to install a frontsize theme?',
        choices: options
    },{
        when: function (response) {
            return response.install == 'yes';
        },
        type: 'input',
        name: 'path',
        message: 'Where do you want to install frontsize theme? (Ex: css/frontsize/your_theme_name)',
        defaults: 'css/frontsize'
    }];

    this.prompt(prompts, function (props) {
        this.pathInstall = props.path;
        cb();
    }.bind(this));
};

Generator.prototype.install = function downloadFiles() {
    console.info('download');
    this.bowerInstall('frontsize-sass', { save: true });
};

Generator.prototype.end = function moveFiles() {
    console.info('move');
    var here = this;
    var directory = 'bower_components';
    var pattern = /\/$/;
    if (fs.existsSync('./.bowerrc')) {
        var obj = JSON.parse(fs.readFileSync('./.bowerrc', 'utf8'));
        if(obj.directory !== undefined){
            directory = obj.directory;
        }
    }
    directory = directory.replace(pattern, '');

    //check if package.json exists in root
    if (fs.existsSync('./package.json')) {
        var dependenciesFrontsize = '';
        var dependenciesRoot = '';

        var packageJsonFrontsize = JSON.parse(fs.readFileSync(directory + '/frontsize-sass/package.json', 'utf8'));
        if(packageJsonFrontsize.dependencies !== undefined){
            dependenciesFrontsize = packageJsonFrontsize.dependencies;
        }
        var packageJsonRoot = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
        if(packageJsonRoot.dependencies !== undefined){
            dependenciesRoot = packageJsonRoot.dependencies;
        }

        if(dependenciesRoot != ''){
            packageJsonRoot.dependencies = absorb(dependenciesRoot, dependenciesFrontsize);
        }
        else{
            packageJsonRoot.dependencies = dependenciesFrontsize;
        }

        fs.writeFile('./package.json', JSON.stringify(packageJsonRoot, null, 2), function(err) {
            if(err) {
                return console.log(err);
            }
        });
    }
    else{
        fs.createReadStream(directory + '/frontsize-sass/package.json').pipe(fs.createWriteStream('./package.json'));
    }

    //quando inserisco il path devo verificare che non esista e lo creo, se esiste gia la cartella theme al suo interno dare errore
    if(fs.exists(here.pathInstall)){
        return console.log('Path already exist!');
    }
    else{
        //create directory
        mkdirp(here.pathInstall);

        if(here.pathInstall.substr(here.pathInstall.length - 1) != '/'){
            here.pathInstall = here.pathInstall + '/';
        }

        //move themes directory
        mv(directory + '/frontsize-sass/themes/default/', here.pathInstall, {mkdirp: true}, function(err) {
            if((err != undefined) && (err != null)){
                return console.log('Error moving theme files! ' + err);
            }
            else{
                mv(directory + '/frontsize-sass/compile.scss', here.pathInstall + 'compile.scss', function(err) {
                    if((err != undefined) && (err != null)){
                        return console.log('Error moving file compile.scss! ' + err);
                    }
                    else{
                        mv(directory + '/frontsize-sass/gulpfile.js', 'gulpfile.js', function(err) {
                            if((err != undefined) && (err != null)){
                                return console.log('Error moving file gulpfile.js! ' + err);
                            }
                            else{
                                mv(directory + '/frontsize-sass/frontsize.yml.dist', 'frontsize.yml', function(err) {
                                    if((err != undefined) && (err != null)){
                                        return console.log('Error moving file frontsize.yml! ' + err);
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    }
};
<|endoftext|>


<commit_before>/**
 * Swipe navigation
 */
;(function() {
  'use strict';

  function setupSlider(slider) {
    var firstSlide = slider.querySelector('ul > li:first-of-type');
    var slides = slider.querySelectorAll('ul > li');
    var radios = Array.prototype.slice.call(slider.querySelectorAll('input'));
    var active;
    var touchStartX;
    var touchStartY;
    var deltaX;
    var deltaY;
    var scrolling;

    function onTouchstart(event) {
      var touch = event.touches ? event.touches[0] : event;
      touchStartX = touch.pageX;
      touchStartY = touch.pageY;
      deltaX = 0;
      deltaY = 0;
      scrolling = undefined;

      active = radios
        .map(function(el) {
          return el.checked;
        })
        .indexOf(true);

      // Add event listeners needed during drag
      slider.addEventListener('touchmove', onTouchmove);
      slider.addEventListener('touchend', onTouchend);
    }

    function onTouchmove(event) {
      var touch = event.touches ? event.touches[0] : event;
      deltaX = touch.pageX - touchStartX;
      deltaY = touch.pageY - touchStartY;

      if (typeof scrolling === 'undefined') {
        scrolling = Math.abs(deltaX) < Math.abs(deltaY);
      }

      if (!scrolling) {
        event.preventDefault();
        Array.prototype.forEach.call(
          slides,
          function(slide) {
            slide.style.transition = 'none'; // Disable transitions during dragging
            slide.style.transform = 'translate3d(' + (deltaX - firstSlide.offsetWidth * active) + 'px' + ', 0, 0)';
          }
        );
      }
    }

    function onTouchend(event) {
      var perPage = Math.round(firstSlide.parentNode.clientWidth / firstSlide.offsetWidth);

      if (!scrolling && Math.abs(deltaX) > firstSlide.offsetWidth / 4) {
        var next = Math.max(0, Math.min(radios.length - perPage, deltaX > 0
          ? active - (active % perPage || perPage) // Next page to the left
          : active - active % perPage + perPage // Next page to the right
        ));
        radios[next].checked = true;
      }
      Array.prototype.forEach.call(
        slides,
        function(slide) {
          slide.style.transition = '';
          slide.style.transform = '';
        }
      );

      // Remove event listeners that are only needed during drag
      slider.removeEventListener('touchmove', onTouchmove);
      slider.removeEventListener('touchend', onTouchend);
    }

    slider.addEventListener('touchstart', onTouchstart);
  }

  /**
   * Add swipe navigation to all CSS-Sliders
   */
  document.addEventListener('DOMContentLoaded', function() {
    Array.prototype.forEach.call(
      document.querySelectorAll('.css-slider'),
      setupSlider
    );
  });
}());
<commit_msg>Port the script to ES6 and fix some edge cases<commit_after>function setupSlider(slider) {
  const firstSlide = slider.querySelector('ul > li:first-of-type');
  const slides = slider.querySelectorAll('ul > li');
  const radios = Array.prototype.slice.call(slider.querySelectorAll('input'));
  const dragListeners = {};
  let touchStartX;
  let touchStartY;
  let deltaX;
  let deltaY;
  let scrollingChecked;

  function getActive() {
    return radios
      .map(el => el.checked)
      .indexOf(true);
  }

  function setActive(index) {
    radios[index].checked = true;
  }

  function onTouchstart(event) {
    const touch = event.touches ? event.touches[0] : event;
    touchStartX = touch.pageX;
    touchStartY = touch.pageY;
    deltaX = 0;
    deltaY = 0;
    scrollingChecked = false;

    // Add event listeners needed during drag
    Object.keys(dragListeners).forEach(eventName =>
      slider.addEventListener(eventName, dragListeners[eventName]));
  }

  function onTouchmove(event) {
    const touch = event.touches ? event.touches[0] : event;
    deltaX = touch.pageX - touchStartX;
    deltaY = touch.pageY - touchStartY;

    if (!scrollingChecked) {
      scrollingChecked = true;
      if (Math.abs(deltaX) < Math.abs(deltaY)) {
        Object.keys(dragListeners).forEach(eventName =>
          slider.removeEventListener(eventName, dragListeners[eventName]));

        return;
      }

      slider.classList.add('moving'); // eslint-disable-line no-param-reassign

      // Disable transitions during swiping
      slides.forEach((slide) => {
        slide.style.transition = 'none'; // eslint-disable-line no-param-reassign
      });
    }

    event.preventDefault();

    const offset = Math.max(0, Math.min(
      slides.length - (firstSlide.parentNode.clientWidth / firstSlide.offsetWidth),
      getActive() + (deltaX / -firstSlide.offsetWidth)
    ));

    slides.forEach((slide) => {
      slide.style.transform = `translate3d(${firstSlide.offsetWidth * -offset}px, 0, 0)`; // eslint-disable-line no-param-reassign
    });
  }

  dragListeners.touchmove = onTouchmove;

  function onTouchend() {
    const perPage = Math.round(firstSlide.parentNode.clientWidth / firstSlide.offsetWidth);

    if (Math.abs(deltaX) > firstSlide.offsetWidth / 4) {
      const active = getActive();
      const next = Math.max(0, Math.min(radios.length - perPage, deltaX > 0
        ? active - (active % perPage || perPage) // Next page to the left
        : active - ((active % perPage) + perPage))); // Next page to the right
      setActive(next);
    }

    slider.classList.remove('moving'); // eslint-disable-line no-param-reassign

    slides.forEach((slide) => {
      slide.style.transition = ''; // eslint-disable-line no-param-reassign
      slide.style.transform = ''; // eslint-disable-line no-param-reassign
    });

    // Remove event listeners that are only needed during drag
    Object.keys(dragListeners).forEach(eventName =>
      slider.removeEventListener(eventName, dragListeners[eventName]));
  }

  dragListeners.touchend = onTouchend;

  slider.addEventListener('touchstart', onTouchstart);
}

/**
 * Add swipe navigation to all CSS-Sliders
 */
document.addEventListener('DOMContentLoaded', () => Array.prototype.forEach.call(
  document.querySelectorAll('.css-slider'),
  setupSlider
));
<|endoftext|>


<commit_before>
'use strict';

// Modules
var express         = require('express');
var logger          = require('morgan');
var body_parser     = require('body-parser');
var method_override = require('method-override');

// Custom Modules
var errors = require('./errors.js');

// New Express App
var app = express();

// Set Port
app.set('port', 8888);

// Log Requests
app.use(logger({ format: ':date :remote-addr :method :status :url' })); // 'dev'

// Accept Method Overrides
// in order to be compatible
// with limited clients/browsers
app.use(method_override('_method'));

// Parse POST/PUT Body
app.use(body_parser.json());

// Routes
require('./routes.js')(app);
require('./boilerplate.routes.js')(app);

// Handle Errors
app.use(errors.not_found);
app.use(errors.server_error);

// Export App
module.exports = app;
<commit_msg>Changing default port from 8888 to more-common 3000<commit_after>
'use strict';

// Modules
var express         = require('express');
var logger          = require('morgan');
var body_parser     = require('body-parser');
var method_override = require('method-override');

// Custom Modules
var errors = require('./errors.js');

// New Express App
var app = express();

// Set Port
app.set('port', 3000);

// Log Requests
app.use(logger({ format: ':date :remote-addr :method :status :url' })); // 'dev'

// Accept Method Overrides
// in order to be compatible
// with limited clients/browsers
app.use(method_override('_method'));

// Parse POST/PUT Body
app.use(body_parser.json());

// Routes
require('./routes.js')(app);
require('./boilerplate.routes.js')(app);

// Handle Errors
app.use(errors.not_found);
app.use(errors.server_error);

// Export App
module.exports = app;
<|endoftext|>


<commit_before>var access_token = "";
var img_url = "";
var first_name = "";
var id = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    /* TODO */
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {
  FB.api('/me?field=id,first_name,location', function(response) {
    first_name = response.first_name;
    id = response.id;
    $('#title').text("Hi " + first_name + ". Insert your health profile!");
  });

  FB.api("/me/picture?type=normal&height=120&width=120&redirect=false", function(response) {
    img_url = response.data.url;
    $('#fb-image').css('background-image', 'url(' + response.data.url + ')');
  });
}

function send_request(obj) {

  var weight_obj = {"measureValue": "70", "measureType":"weight"};
  var height_obj = {"measureValue": "180", "measureType":"height"};
  var url_w = "http://95.85.59.245:8086/dbservice/person/facebook";
  var url_h = "http://95.85.59.245:8086/dbservice/person/facebook";

  console.log(JSON.stringify(weight_obj));

  $.ajax({
      type: 'POST',
      url: url_w + "?callback=?&token=" + access_token,
      data: JSON.stringify(weight_obj),
      success: function(data) { alert('data: ' + data); },
      contentType: "application/json",
      dataType: 'json'
  });

  // $.ajax({
  //     type: "POST",
  //     url: url_w,
  //     data: JSON.stringify(weight_obj),
  //     contentType: "application/json; charset=utf-8",
  //     dataType: "json",
  //     success: function(data) {
  //       console.log(data);
  //     },
  //     failure: function(errMsg) {
  //       console.log(errMsg);
  //     }
  // });

  // $.ajax({
  //     type: "POST",
  //     url: url_h,
  //     data: JSON.stringify(height_obj),
  //     contentType: "application/json; charset=utf-8",
  //     dataType: "json",
  //     success: function(data) {
  //       console.log(data);
  //     },
  //     failure: function(errMsg) {
  //       console.log(errMsg);
  //     }
  // });

  // $.getJSON("https://restindirectorservice.herokuapp.com/project-director/weather?callback=?&token=" + access_token, function(response_p1){

  //   console.log(response_p1);

  //   act1 = response_p1.result[0].activityplan;
  //   act2 = response_p1.result[1].activityplan;
  //   act3 = response_p1.result[2].activityplan;

  //   weather1 = response_p1.result[0].weather;
  //   weather2 = response_p1.result[1].weather;
  //   weather3 = response_p1.result[2].weather;

  //   $.getJSON("https://restindirectorservice.herokuapp.com/project-director/food?callback=?&token=" + access_token, function(response_p2){

  //     console.log(response_p2);

  //     bg = response_p2.result.foodPhoto.url;
  //     suggested_food = response_p2.result.suggestedFood.name;

  //     $('#form').hide();
  //     $('.shadow_overlay').show();
  //     $('#flickr_bg').css('background-image', 'url("'+ bg +'")');
  //     $('#quote').text(act1.phrase);
  //     $('.motivational_quote').show();
  //     $('#title').text(suggested_food);
  //     $('.subtitle').hide();
  //     $('.center').addClass('results');
  //     $('.scroll_down').show();

  //     $('#block-day-1 .wi').addClass('wi-'+weather1.weather.toLowerCase());
  //     $('#block-day-2 .wi').addClass('wi-'+weather2.weather.toLowerCase());
  //     $('#block-day-3 .wi').addClass('wi-'+weather3.weather.toLowerCase());

  //     $('#block-day-1 .calendar').text(act1.activity);
  //     $('#block-day-2 .calendar').text(act2.activity);
  //     $('#block-day-3 .calendar').text(act3.activity);
  //     $('#second').show();

  //   });
  // });
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<commit_msg>social.js updated<commit_after>var access_token = "";
var img_url = "";
var first_name = "";
var id = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    /* TODO */
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {
  FB.api('/me?field=id,first_name,location', function(response) {
    first_name = response.first_name;
    id = response.id;
    $('#title').text("Hi " + first_name + ". Insert your health profile!");
  });

  FB.api("/me/picture?type=normal&height=120&width=120&redirect=false", function(response) {
    img_url = response.data.url;
    $('#fb-image').css('background-image', 'url(' + response.data.url + ')');
  });
}

function send_request(obj) {

  var weight_obj = {"measureValue": "70", "measureType":"weight"};
  var height_obj = {"measureValue": "180", "measureType":"height"};
  var url_w = "http://95.85.59.245:8088/dbservice/person/facebook";
  var url_h = "http://95.85.59.245:8088/dbservice/person/facebook";

  console.log(JSON.stringify(weight_obj));

  $.ajax({
      type: 'POST',
      url: url_w + "?callback=?&token=" + access_token,
      crossDomain: true,
      data: JSON.stringify(weight_obj),
      success: function(data) { alert('data: ' + data); },
      contentType: "application/json",
      dataType: 'json'
  });

  // $.ajax({
  //     type: "POST",
  //     url: url_w,
  //     data: JSON.stringify(weight_obj),
  //     contentType: "application/json; charset=utf-8",
  //     dataType: "json",
  //     success: function(data) {
  //       console.log(data);
  //     },
  //     failure: function(errMsg) {
  //       console.log(errMsg);
  //     }
  // });

  // $.ajax({
  //     type: "POST",
  //     url: url_h,
  //     data: JSON.stringify(height_obj),
  //     contentType: "application/json; charset=utf-8",
  //     dataType: "json",
  //     success: function(data) {
  //       console.log(data);
  //     },
  //     failure: function(errMsg) {
  //       console.log(errMsg);
  //     }
  // });

  // $.getJSON("https://restindirectorservice.herokuapp.com/project-director/weather?callback=?&token=" + access_token, function(response_p1){

  //   console.log(response_p1);

  //   act1 = response_p1.result[0].activityplan;
  //   act2 = response_p1.result[1].activityplan;
  //   act3 = response_p1.result[2].activityplan;

  //   weather1 = response_p1.result[0].weather;
  //   weather2 = response_p1.result[1].weather;
  //   weather3 = response_p1.result[2].weather;

  //   $.getJSON("https://restindirectorservice.herokuapp.com/project-director/food?callback=?&token=" + access_token, function(response_p2){

  //     console.log(response_p2);

  //     bg = response_p2.result.foodPhoto.url;
  //     suggested_food = response_p2.result.suggestedFood.name;

  //     $('#form').hide();
  //     $('.shadow_overlay').show();
  //     $('#flickr_bg').css('background-image', 'url("'+ bg +'")');
  //     $('#quote').text(act1.phrase);
  //     $('.motivational_quote').show();
  //     $('#title').text(suggested_food);
  //     $('.subtitle').hide();
  //     $('.center').addClass('results');
  //     $('.scroll_down').show();

  //     $('#block-day-1 .wi').addClass('wi-'+weather1.weather.toLowerCase());
  //     $('#block-day-2 .wi').addClass('wi-'+weather2.weather.toLowerCase());
  //     $('#block-day-3 .wi').addClass('wi-'+weather3.weather.toLowerCase());

  //     $('#block-day-1 .calendar').text(act1.activity);
  //     $('#block-day-2 .calendar').text(act2.activity);
  //     $('#block-day-3 .calendar').text(act3.activity);
  //     $('#second').show();

  //   });
  // });
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ace ' + chalk.red('Drupal Package') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'name',
        message: 'Your project name?',
        default : this.appname // Default to current folder name
      }
    ];

    this.prompt(prompts, function (props) {
      this.projectName = props.name;
      done();
    }.bind(this));
  },

  scaffoldFolders: function(){
    this.mkdir("test");
    this.mkdir("src");
    this.mkdir("src/modules");
    this.mkdir("src/features");
    this.mkdir("src/profiles");
    this.mkdir("src/sites");
    this.mkdir("src/sites/default");
    this.mkdir("src/static");
    this.mkdir("src/themes");
  },

  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
      this.fs.copyTpl(
        this.templatePath('_Gruntconfig.json'),
        this.destinationPath('Gruntconfig.json'),
        { projectName: this.projectName }
      );
      this.fs.copy(
        this.templatePath('_gruntfile.js'),
        this.destinationPath('gruntfile.js')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
      this.fs.copy(
        this.templatePath('_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('_project.make'),
        this.destinationPath('src/project.make')
      );
    },

    profile: function () {
      this.mkdir("src/profiles/" + this.projectName);
      this.fs.copyTpl(
        this.templatePath('profile/info'),
        this.destinationPath('src/profiles/' + this.projectName + '/' + this.projectName + '.info'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/install'),
        this.destinationPath('src/profiles/' + this.projectName + '/' + this.projectName + '.install'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/profile'),
        this.destinationPath('src/profiles/' + this.projectName + '/' + this.projectName + '.profile'),
      { projectName: this.projectName }
      );
    },

    tasks: function () {
      this.bulkDirectory('tasks', 'tasks');
    },

    theme: function() {
      this.bulkDirectory('src/sass', 'sass');
      this.bulkDirectory("theme", "src/themes/" + this.projectName);

      this.mkdir("src/themes/" + this.projectName + 'preprocess/');
      this.fs.copyTpl(
        this.templatePath('theme_tpl/preprocess/_page.preprocess.inc'),
        this.destinationPath('src/themes/' + this.projectName + '/preprocess/page.preprocess.inc'),
      { projectName: this.projectName }
      );
      this.fs.copy(
        this.templatePath('theme_tpl/preprocess/README.md'),
        this.destinationPath('src/themes/' + this.projectName + '/preprocess/README.md')
      );

      this.mkdir("src/themes/" + this.projectName + 'process/');
      this.fs.copyTpl(
        this.templatePath('theme_tpl/process/_page.process.inc'),
        this.destinationPath('src/themes/' + this.projectName + '/process/page.process.inc'),
      { projectName: this.projectName }
      );
      this.fs.copy(
        this.templatePath('theme_tpl/process/README.md'),
        this.destinationPath('src/themes/' + this.projectName + '/process/README.md')
      );

      this.fs.copyTpl(
        this.templatePath('theme_tpl/info'),
        this.destinationPath('src/themes/' + this.projectName + '/' + this.projectName + '.info'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_template.php'),
        this.destinationPath('src/profiles/' + this.projectName + '/template.php'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_theme-settings.php'),
        this.destinationPath('src/profiles/' + this.projectName + '/theme-settings.php'),
      { projectName: this.projectName }
      );

    }

  },

  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }
});
<commit_msg>Fixed process and preprocess path.<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ace ' + chalk.red('Drupal Package') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'name',
        message: 'Your project name?',
        default : this.appname // Default to current folder name
      }
    ];

    this.prompt(prompts, function (props) {
      this.projectName = props.name;
      done();
    }.bind(this));
  },

  scaffoldFolders: function(){
    this.mkdir("test");
    this.mkdir("src");
    this.mkdir("src/modules");
    this.mkdir("src/features");
    this.mkdir("src/profiles");
    this.mkdir("src/sites");
    this.mkdir("src/sites/default");
    this.mkdir("src/static");
    this.mkdir("src/themes");
  },

  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
      this.fs.copyTpl(
        this.templatePath('_Gruntconfig.json'),
        this.destinationPath('Gruntconfig.json'),
        { projectName: this.projectName }
      );
      this.fs.copy(
        this.templatePath('_gruntfile.js'),
        this.destinationPath('gruntfile.js')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
      this.fs.copy(
        this.templatePath('_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('_project.make'),
        this.destinationPath('src/project.make')
      );
    },

    profile: function () {
      this.mkdir("src/profiles/" + this.projectName);
      this.fs.copyTpl(
        this.templatePath('profile/info'),
        this.destinationPath('src/profiles/' + this.projectName + '/' + this.projectName + '.info'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/install'),
        this.destinationPath('src/profiles/' + this.projectName + '/' + this.projectName + '.install'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/profile'),
        this.destinationPath('src/profiles/' + this.projectName + '/' + this.projectName + '.profile'),
      { projectName: this.projectName }
      );
    },

    tasks: function () {
      this.bulkDirectory('tasks', 'tasks');
    },

    theme: function() {
      this.bulkDirectory('src/sass', 'sass');
      this.bulkDirectory("theme", "src/themes/" + this.projectName);

      this.mkdir("src/themes/" + this.projectName + '/preprocess/');
      this.fs.copyTpl(
        this.templatePath('theme_tpl/preprocess/_page.preprocess.inc'),
        this.destinationPath('src/themes/' + this.projectName + '/preprocess/page.preprocess.inc'),
      { projectName: this.projectName }
      );
      this.fs.copy(
        this.templatePath('theme_tpl/preprocess/README.md'),
        this.destinationPath('src/themes/' + this.projectName + '/preprocess/README.md')
      );

      this.mkdir("src/themes/" + this.projectName + '/process/');
      this.fs.copyTpl(
        this.templatePath('theme_tpl/process/_page.process.inc'),
        this.destinationPath('src/themes/' + this.projectName + '/process/page.process.inc'),
      { projectName: this.projectName }
      );
      this.fs.copy(
        this.templatePath('theme_tpl/process/README.md'),
        this.destinationPath('src/themes/' + this.projectName + '/process/README.md')
      );

      this.fs.copyTpl(
        this.templatePath('theme_tpl/info'),
        this.destinationPath('src/themes/' + this.projectName + '/' + this.projectName + '.info'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_template.php'),
        this.destinationPath('src/profiles/' + this.projectName + '/template.php'),
      { projectName: this.projectName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_theme-settings.php'),
        this.destinationPath('src/profiles/' + this.projectName + '/theme-settings.php'),
      { projectName: this.projectName }
      );

    }

  },

  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }
});
<|endoftext|>


<commit_before>var access_token = "";
var img_url = "";
var first_name = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {

  FB.api('/me?field=id,first_name,location', function(response) {
    first_name = response.first_name;
    $('#title').text("Hi " + first_name + ". Insert your health profile!");
  });

  FB.api("/me/picture?type=normal&height=120&width=120&redirect=false", function(response) {
    img_url = response.data.url;
    $('#fb-image').css('background-image', 'url(' + response.data.url + ')');
  });

  // $.getJSON("http://127.0.0.1:9091/project-director/weather?callback=?&token=" + access_token, function(result){
  //   //response data are now in the result variable
  //   console.log(result);
  //   // alert("ID: " + result.info.id);
  //   // alert("First name: "+ result.info.first_name);
  //   // alert("Location: "+ result.info.location);
  // });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "and because it is cloudy",
    "and because i am sad",
    "and because i am happy");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  // $.ajax({
  //   crossDomain: true,
  //   type:'POST',
  //   dataType: 'jsonp',
  //   url: "http://127.0.0.1:8000/project-director/facebook",
  //   data: JSON.stringify(myObject),
  //   success: function(data)
  //   {
  //     var obj = jQuery.parseJSON(data);
  //     alert(obj.id);
  //     alert(obj.fist_name);
  //     alert(obj.image_url);
  //     // $('body').append(data);
  //     // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
  //     //   $('#form-send-message').addClass('form-send-errors')
  //     // }
  //     // else {
  //     //   $('#form-send-message').addClass('form-send-success');
  //     // }
  //   }//,
  //   // error: function(error) {
  //   //   alert(error);
  //   // }
  // });

  $.getJSON("http://127.0.0.1:9091/project-director/facebook?callback=?&token=" + access_token, function(result){
    //response data are now in the result variable
    console.log(result);
    // var obj = jQuery.parseJSON(result);
    // console.log("parsed");
    // console.log(result.info);
    // console.log(result.info.first_name);
    // console.log(result.image.image_url);
  });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<commit_msg>submit button works<commit_after>var access_token = "";
var img_url = "";
var first_name = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {

  FB.api('/me?field=id,first_name,location', function(response) {
    first_name = response.first_name;
    $('#title').text("Hi " + first_name + ". Insert your health profile!");
  });

  FB.api("/me/picture?type=normal&height=120&width=120&redirect=false", function(response) {
    img_url = response.data.url;
    $('#fb-image').css('background-image', 'url(' + response.data.url + ')');
  });

  // $.getJSON("http://127.0.0.1:9091/project-director/weather?callback=?&token=" + access_token, function(result){
  //   //response data are now in the result variable
  //   console.log(result);
  //   // alert("ID: " + result.info.id);
  //   // alert("First name: "+ result.info.first_name);
  //   // alert("Location: "+ result.info.location);
  // });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "and because it is cloudy",
    "and because i am sad",
    "and because i am happy");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  // $.ajax({
  //   crossDomain: true,
  //   type:'POST',
  //   dataType: 'jsonp',
  //   url: "http://127.0.0.1:8000/project-director/facebook",
  //   data: JSON.stringify(myObject),
  //   success: function(data)
  //   {
  //     var obj = jQuery.parseJSON(data);
  //     alert(obj.id);
  //     alert(obj.fist_name);
  //     alert(obj.image_url);
  //     // $('body').append(data);
  //     // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
  //     //   $('#form-send-message').addClass('form-send-errors')
  //     // }
  //     // else {
  //     //   $('#form-send-message').addClass('form-send-success');
  //     // }
  //   }//,
  //   // error: function(error) {
  //   //   alert(error);
  //   // }
  // });

  $.getJSON("http://127.0.0.1:9091/project-director/weather?callback=?&token=" + access_token, function(result){
    //response data are now in the result variable
    console.log(result);
    // var obj = jQuery.parseJSON(result);
    // console.log("parsed");
    // console.log(result.info);
    // console.log(result.info.first_name);
    // console.log(result.image.image_url);
  });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<|endoftext|>


<commit_before>/* exported Log */

/* Magic Mirror
 * Socket Connection
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var MMSocket = function(moduleName) {

	var self = this;

	if (typeof moduleName !== "string") {
		throw new Error("Please set the module name for the MMSocket.");
	}

	self.moduleName = moduleName;

	self.socket = io("http://localhost:8080");
	self.socket.on("notification", function(data) {
		MM.sendNotification(data.notification, data.payload, Socket);
	});

	return {
		sendMessage: function(notification, payload, sender) {
			Log.log("Send socket message: " + notification);
			self.socket.emit("notification", {
				notification: notification,
				sender: sender,
				payload: payload
			});
		}
	};
};
<commit_msg>Update socket.js<commit_after>/* exported Log */

/* Smart Mirror
 * Socket Connection
*/

var MMSocket = function(moduleName) {

	var self = this;

	if (typeof moduleName !== "string") {
		throw new Error("Please set the module name for the MMSocket.");
	}

	self.moduleName = moduleName;

	self.socket = io("http://localhost:8080");
	self.socket.on("notification", function(data) {
		MM.sendNotification(data.notification, data.payload, Socket);
	});

	return {
		sendMessage: function(notification, payload, sender) {
			Log.log("Send socket message: " + notification);
			self.socket.emit("notification", {
				notification: notification,
				sender: sender,
				payload: payload
			});
		}
	};
};
<|endoftext|>