<commit_before>var http = require('http'),
    fs = require("fs"),
    zip = require("node-zip"),
    less = require("less"),
    util = require("util"),
    qs = require('querystring'),
    resolvePath = require('path').resolve

http.createServer(function (req, res) {
    res.writeHead(200, {
            'Content-Type': 'application/zip',
            'Cache-Control': 'no-cache',
            'Content-Disposition': 'attachment; filename=bootstrap.zip'
    })
   var data = ''
   req.on("data", function(chunk) {
        data += chunk
    })
    req.on("end", function() {
        var post = qs.parse(data)
        var archive = new BootstrapZipBuilder()
        for (var variable in post) {
            if (variable[0] == "@"){
                archive.setVariable(variable, post[variable])
            }
        }

        if(post.css) {
          post.css = (post.css.constructor == Array ? post.css : [post.css])
          for(var i=0; i<post.css.length; i++){
            archive.addLessCss(post.css[i])
          }
          archive.generateSingleCSS()
        }

        if(post.js) {
          post.js = (post.js.constructor == Array ? post.js : [post.js])
          for(var i=0; i<post.js.length; i++) {
              archive.addJavascript(post.js[i])
          }
        }

        var buffer = archive.generate({base64:true,compression:'STORE'})
        //fs.writeFileSync('teste.zip', buffer, 'base64')
        res.write(buffer)
        res.end()
    })

}).listen(1337, '0.0.0.0')
console.log('Server running...')

BootstrapZipBuilder = function(){
    this.pathBootstrap = resolvePath(__dirname + '/../../')
    this.variables = fs.readFileSync(this.pathBootstrap + '/lib/variables.less', 'utf-8')
    this.mixins = fs.readFileSync(this.pathBootstrap + '/lib/mixins.less', 'utf-8')
    this.cssContent = this.variables + this.mixins
}
BootstrapZipBuilder.prototype = new JSZip()
BootstrapZipBuilder.prototype.addLessCss = function(name){
    this.cssContent += this.readCSSLess(name)
    console.log('css file: ' + name + '.css')
}
BootstrapZipBuilder.prototype.generateSingleCSS = function() {
  var self = this
  parser.parse(this.cssContent, function (e, tree) {
      if (e) { return console.log(e) }
      try {
        var css = tree.toCSS({ compress: false })
        self.file('bootstrap.css', new Buffer(css, "utf8"))
        console.log('bootstrap.css generated')

        css = tree.toCSS({ compress: true })
        self.file('bootstrap.min.css', new Buffer(css, "utf8"))
        console.log('bootstrap.min.css generated')
      } catch(e) {
        console.log(e)
      }
  })
}
BootstrapZipBuilder.prototype.addJavascript = function(name){
    var content = this.readJavascript(name)
    this.add( name, new Buffer(content, "utf8") )
}
BootstrapZipBuilder.prototype.setVariable = function(name, value){
        this.variables += ( name + ": " + value + ";\n" )
}
BootstrapZipBuilder.prototype.readJavascript = function(name){
    console.log('js file: ' + name)
    return fs.readFileSync( this.pathBootstrap + '/js/'+ name + '.js', 'utf-8' )
}
BootstrapZipBuilder.prototype.readCSSLess = function(name){
    return fs.readFileSync( this.pathBootstrap + '/lib/'+ name + '.less', 'utf-8' )
}

var parser = new(less.Parser)({
        paths: [resolvePath(__dirname + '/../../lib')]
})
<commit_msg>zip file download corrected<commit_after>var http = require('http'),
    fs = require("fs"),
    zip = require("node-zip"),
    less = require("less"),
    util = require("util"),
    qs = require('querystring'),
    resolvePath = require('path').resolve

http.createServer(function (req, res) {
    res.writeHead(200, {
            'Content-Type': 'application/zip',
            'Cache-Control': 'no-cache',
            'Content-Disposition': 'attachment; filename=bootstrap.zip'
    })
   var data = ''
   req.on("data", function(chunk) {
        data += chunk
    })
    req.on("end", function() {
        var post = qs.parse(data)
        var archive = new BootstrapZipBuilder()
        for (var variable in post) {
            if (variable[0] == "@"){
                archive.setVariable(variable, post[variable])
            }
        }

        if(post.css) {
          post.css = (post.css.constructor == Array ? post.css : [post.css])
          for(var i=0; i<post.css.length; i++){
            archive.addLessCss(post.css[i])
          }
          archive.generateSingleCSS()
        }

        if(post.js) {
          post.js = (post.js.constructor == Array ? post.js : [post.js])
          for(var i=0; i<post.js.length; i++) {
              archive.addJavascript(post.js[i])
          }
        }

        var zipfile = archive.generate({base64:true,compression:'STORE'})
        res.write(new Buffer(zipfile, 'base64'))
        res.end()
    })

}).listen(1337, '0.0.0.0')
console.log('Server running...')

BootstrapZipBuilder = function(){
    this.pathBootstrap = resolvePath(__dirname + '/../../')
    this.variables = fs.readFileSync(this.pathBootstrap + '/lib/variables.less', 'utf-8')
    this.mixins = fs.readFileSync(this.pathBootstrap + '/lib/mixins.less', 'utf-8')
    this.cssContent = this.variables + this.mixins
}
BootstrapZipBuilder.prototype = new JSZip()
BootstrapZipBuilder.prototype.addLessCss = function(name){
    this.cssContent += this.readCSSLess(name)
    console.log('css file: ' + name + '.css')
}
BootstrapZipBuilder.prototype.generateSingleCSS = function() {
  var self = this
  parser.parse(this.cssContent, function (e, tree) {
      if (e) { return console.log(e) }
      try {
        var css = tree.toCSS({ compress: false })
        self.file('bootstrap.css', css)
        console.log('bootstrap.css generated')

        css = tree.toCSS({ compress: true })
        self.file('bootstrap.min.css', css)
        console.log('bootstrap.min.css generated')
      } catch(e) {
        console.log(e)
      }
  })
}
BootstrapZipBuilder.prototype.addJavascript = function(name){
    var content = this.readJavascript(name)
    this.file(name + '.js', content)
}
BootstrapZipBuilder.prototype.setVariable = function(name, value){
        this.variables += ( name + ": " + value + ";\n" )
}
BootstrapZipBuilder.prototype.readJavascript = function(name){
    console.log('js file: ' + name + '.js')
    return fs.readFileSync(this.pathBootstrap + '/js/'+ name + '.js', 'utf-8')
}
BootstrapZipBuilder.prototype.readCSSLess = function(name){
    return fs.readFileSync(this.pathBootstrap + '/lib/'+ name + '.less', 'utf-8')
}

var parser = new(less.Parser)({
        paths: [resolvePath(__dirname + '/../../lib')]
})
<|endoftext|>


<commit_before>/*
 * Module dependencies.
 */

var CLI = require('../../lib/cli'),
    cli,
    stdout;

/*
 * Specification: phonegap help build.
 */

describe('phonegap help build', function() {
    beforeEach(function() {
        cli = new CLI();
        spyOn(process.stdout, 'write');
        stdout = process.stdout.write;
    });

    describe('$ phonegap help', function() {
        it('should include the command', function() {
            cli.argv({ _: ['help'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/\n\s+build <platform>.*\n/i);
        });
    });

    describe('$ phonegap build', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap help build', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['help', 'build'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap build help', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build', 'help'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap build --help', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build'], help: true });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap build -h', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build'], h: true });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });
});

/*
 * Specification: phonegap build <platform>.
 */

describe('phonegap create <path>', function() {
    beforeEach(function() {
        cli = new CLI();
        spyOn(process.stdout, 'write');
        //spyOn(cli.phonegap, 'build');
        spyOn(cli.remote, 'build');
    });

    describe('$ phonegap build android', function() {
        it('should try to build the android project', function() {
            cli.argv({ _: ['build', 'android'] });
            expect(cli.remote.build).toHaveBeenCalledWith(
                { _: ['remote', 'build', 'android'] },
                jasmine.any(Function)
            );
        });
    });
});
<commit_msg>[spec] Update build spec description.<commit_after>/*
 * Module dependencies.
 */

var CLI = require('../../lib/cli'),
    cli,
    stdout;

/*
 * Specification: phonegap help build.
 */

describe('phonegap help build', function() {
    beforeEach(function() {
        cli = new CLI();
        spyOn(process.stdout, 'write');
        stdout = process.stdout.write;
    });

    describe('$ phonegap help', function() {
        it('should include the command', function() {
            cli.argv({ _: ['help'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/\n\s+build <platform>.*\n/i);
        });
    });

    describe('$ phonegap build', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap help build', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['help', 'build'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap build help', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build', 'help'] });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap build --help', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build'], help: true });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });

    describe('$ phonegap build -h', function() {
        it('should output usage info', function() {
            cli.argv({ _: ['build'], h: true });
            expect(stdout.mostRecentCall.args[0]).toMatch(/usage: [\S]+ build <platform>/i);
        });
    });
});

/*
 * Specification: phonegap build <platform>.
 */

describe('phonegap build <platform>', function() {
    beforeEach(function() {
        cli = new CLI();
        spyOn(process.stdout, 'write');
        //spyOn(cli.phonegap, 'build');
        spyOn(cli.remote, 'build');
    });

    describe('$ phonegap build android', function() {
        it('should try to build the android project', function() {
            cli.argv({ _: ['build', 'android'] });
            expect(cli.remote.build).toHaveBeenCalledWith(
                { _: ['remote', 'build', 'android'] },
                jasmine.any(Function)
            );
        });
    });
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/tsubscription',function(req,res,next){
  res.json(req.body);
});

module.exports = router;
<commit_msg>Log request<commit_after>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/tsubscription',function(req,res,next){
  console.log("Received request!");
  console.log(req.body);
  res.json(req.body);
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const defaultPageSize = 3;

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

const queryTertuliasPaged = 'SELECT * FROM (' + queryTertulias + ') AS tbl' +
' ORDER BY nextEventDate DESC, name' +
' OFFSET ((@pageNr - 1) * @pageSize) ROWS FETCH NEXT @pageSize ROWS ONLY';

const queryTertuliaX = 'SELECT DISTINCT' +
	' tr_id, tr_name, tr_subject, ' + // Tertulia
	' lo_name, lo_address, lo_zip, lo_city, lo_country, lo_latitude, lo_longitude, ' + // Location
	' sc_type, _Schedule.nv_name AS schedule, _Schedule.nv_description AS description,' + // Schedule
	' tr_is_private, ' +
	' _Member.nv_name AS nv_name' + // Role
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN Members    ON mb_tertulia = tr_id' +
' INNER JOIN Users      ON mb_user = us_id' +
' INNER JOIN EnumValues AS _Member ON mb_role = _Member.nv_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid' +
' AND tr_id = @tertulia';

const queryPublicTertulias = 'SELECT ' +
	' tr_id, tr_name, tr_subject, ' + // Tertulia
	' lo_name, lo_address, lo_zip, lo_city, lo_country, lo_latitude, lo_longitude, ' + // Location
	' sc_type, _Schedule.nv_name AS schedule, _Schedule.nv_description AS description' + // Schedule
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND tr_is_private = 0';

const queryPublicTertuliaX = 'SELECT' +
	' tr_id, tr_name, tr_subject, ' + // Tertulia
	' lo_name, lo_address, lo_zip, lo_city, lo_country, lo_latitude, lo_longitude, ' + // Location
	' sc_type, _Schedule.nv_name AS schedule, _Schedule.nv_description AS description' + // Schedule
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND tr_is_private = 0' +
' AND tr_id = @tertulia';

const queryScheduleMonthlyW = 'SELECT mw_id, mw_dow, mw_weeknr, mw_is_fromstart, mw_skip' +
' FROM MonthlyW' +
' INNER JOIN Schedules  ON mw_schedule = sc_id' +
' INNER JOIN Tertulias  ON sc_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid' +
' AND tr_id = @tertulia';

module.exports = function (configuration) {
    var router = express.Router();

	var completeError = function(err, res) {
	    if (err) {
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

    router.get('/', (req, res, next) => {
    	var pageNr = 1;
    	var pageSize = defaultPageSize;
		req.selectedQuery = queryTertuliasPaged;
		req.pageSize = pageSize;
		req.pageNr = pageNr;
	    req.paramsT = { 'sid': sql.NVarChar, 'pageNr': sql.Int, 'pageSize': sql.Int }; // String -> sql.NVarChar; Number -> sql.Int; Boolean -> sql.Bit; Date -> sql.DateTime; Buffer -> sql.VarBinary; sql.Table -> sql.TVP
	    req.paramsV = { 'sid': req.azureMobile.user.id, 'pageNr': pageNr, 'pageSize': pageSize };
	    req.t_links = '{ "details": { "href": "tertulias/:tertulia" } }';
	    goGetTertulias(req, res, next);
	});

    router.get('/public', (req, res, next) => {
		req.selectedQuery = queryPublicTertulias;
	    req.t_links = '{ "details": { "href": "tertulias/public/:tertulia" } }';
	    goGet(req, res, next);
	});

    router.get('/:tertulia', (req, res, next) => {
		req.selectedQuery = queryTertuliaX;
	    req.paramsT = { sid: sql.NVarChar, tertulia: sql.NVarChar };
	    req.paramsV = { sid: req.azureMobile.user.id, tertulia: req.params.tertulia };
	    req.t_links = '{ ' +
	    	'"self":      { "href": "tertulias/:tertulia" }, ' +
	    	'"edit":      { "href": "tertulias/:tertulia/edit" }, ' +
	    	'"location":  { "href": "tertulias/:tertulia/location" }, ' +
	    	'"schedule":  { "href": "tertulias/:tertulia/schedule" }, ' +
	    	'"members":   { "href": "tertulias/:tertulia/members" }, ' +
	    	'"messages":  { "href": "tertulias/:tertulia/messages" }, ' +
	    	'"events":    { "href": "tertulias/:tertulia/events" }, ' +
	    	'"nextevent": { "href": "tertulias/:tertulia/nextevent" } ' +
    	'}';
	    goGet(req, res, next);
	});

    router.get('/public/:tertulia', (req, res, next) => {
		req.selectedQuery = queryPublicTertuliaX;
	    req.paramsT = {};
	    req.paramsV = {};
	    req.t_links = '{ ' +
	    	'"self":      { "href": "tertulias/public/:tertulia" }, ' +
	    	'"subscribe": { "href": "tertulias/public/:tertulia/subscribe" }, ' +
	    	'"location":  { "href": "tertulias/public/:tertulia/location" }, ' +
	    	'"schedule":  { "href": "tertulias/public/:tertulia/schedule" }, ' +
	    	'"events":    { "href": "tertulias/public/:tertulia/events" }, ' +
	    	'"nextevent": { "href": "tertulias/public/:tertulia/nextevent" } ' +
    	'}';
	    goGet(req, res, next);
	});

    router.get('/public/:tertulia/subscribe', (req, res, next) => {
		req.selectedQuery = queryTertuliaX;
	    req.paramsT = {};
	    req.paramsV = {};
	    req.t_links = '{ ' +
	    	'"self":      { "href": "tertulias/public/:tertulia/subscribe" } ' +
    	'}';
	    goGet(req, res, next);
	});

	var goGetTertulias = function(req, res, next) {
		var selectedQuery = req.selectedQuery;
	    var paramsT = req.paramsT;
	    var paramsV = req.paramsV;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsT) preparedStatement.input(key, paramsT[key]);
	        preparedStatement.prepare(selectedQuery, function(err) {
	            if (err) { completeError(err, res); return; }
	            preparedStatement.execute(paramsV,
	                function(err, recordset, affected) {
	                    if (err) { completeError(err, res); return; }
	                    res.type('application/json');
	                    recordset.forEach(function(elem) {
	                    	if (typeof req.t_links !== typeof undefined)
		                    	elem['_links'] = JSON.parse(req.t_links.replace(/:tertulia/g, elem.tr_id));
	                    });
	                    preparedStatement.unprepare();
	                    console.log(recordset);
	                    var result = {
	                    	tertulias: recordset,
	                    	page: {
                    			offset: req.pageNr,
                    			size: req.pageSize,
                    			itemsCount: recordset.length
	                    	},
	                    	links: {
	                    		self: {
	                    			href: source
                    			},
                    			add: {
                    				tag: 'ADD_TERTULIA',
                    				method: 'POST',
	                    			href: source
                    			},
								subscribe: {
                    				tag: 'SUBSCRIBE_TERTULIA',
                    				method: 'POST',
	                    			href: source + '/publicsearch'
                    			},
								nextPage: {
                    				tag: 'NEXT_PAGE',
                    				method: 'GET',
	                    			href: '/tertulias/page/' + (1 + req.pageNr)
                    			},
								previousPage: {
                    				tag: 'PREVIOUS_PAGE',
                    				method: 'GET',
	                    			href: '/tertulias/page/' + (0 + req.pageNr - 1)
                    			},
							}
	                    };
	                    console.log(result);
	                    res.json(result);
	                    next();
	                }
	            );
	        });
	    });
	}

	var goGet = function(req, res, next) {
		var selectedQuery = req.selectedQuery;
	    var paramsT = req.paramsT;
	    var paramsV = req.paramsV;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsT) preparedStatement.input(key, paramsT[key]);
	        preparedStatement.prepare(selectedQuery, function(err) {
	            if (err) { completeError(err, res); return; }
	            preparedStatement.execute(paramsV,
	                function(err, recordset, affected) {
	                    if (err) { completeError(err, res); return; }
	                    res.type('application/json');
	                    recordset.forEach(function(elem) {
	                    	if (typeof req.t_links !== typeof undefined)
		                    	elem['_links'] = JSON.parse(req.t_links.replace(/:tertulia/g, elem.tr_id));
	                    });
	                    preparedStatement.unprepare();
	                    res.json(recordset);
	                    next();
	                }
	            );
	        });
	    });
	}

	router.post('/', (req, res, next) => {
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
			new sql.Request()
			.input('name', sql.NVarChar(40), req.body.tr_name)
			.input('subject', sql.NVarChar(80), req.body.tr_subject)
			.input('userSid', sql.NVarChar(40), req.azureMobile.user.id)
			.input('weekDay', sql.NVarChar(20), 'Tuesday')
			.input('weekNr', sql.Int, 1)
			.input('fromStart', sql.BIT, 1)
			.input('skip', sql.Int, 0)
			.input('locationName', sql.NVarChar(40), req.body.lo_name)
			.input('locationAddress', sql.NVarChar(80), req.body.lo_address)
			.input('locationZip', sql.NVarChar(40), req.body.lo_zip)
			.input('locationCity', sql.NVarChar(40), req.body.lo_city)
			.input('locationCountry', sql.NVarChar(40), req.body.lo_country)
			.input('locationLatitude', sql.NVarChar(12), req.body.lo_latitude)
			.input('locationLongitude', sql.NVarChar(12), req.body.lo_longitude)
			.input('isPrivate', sql.Int, req.body.tr_is_private ? 1 : 0)
			.execute('sp_insertTertulia_MonthlyW_sid')
			.then((recordsets) => {
				console.log(recordsets);
				console.log('len: ' + recordsets.length);
				//console.log('r1: ' + recordsets[0][0][ErrorNumber]);
				//console.log('r2: ' + recordsets[0][ErrorNumber]);
				//console.log('r2: ' + recordsets[0]);
				if (recordsets.length == 0) {
					console.log('sending 201');
					res.status(201)	// 201: Created
						.type('application/json')
						.json( { result: 'Ok' } );
					return;
				} else {
					console.log('sending 409');
					res.status(409)	// 409: Conflict, 422: Unprocessable Entity (WebDAV; RFC 4918)
						.type('application/json')
						.json( { result: 'Duplicate' } );
					return;
				}
				next();
			})
			.catch(function(err) {
				console.log('catch 1');
				console.log(err);
				next();
			});
		})
		.catch(function(err) {
			console.log('catch 2');
			console.log(err);
			next();
		});
	})

    return router;

}
<commit_msg>wip save<commit_after>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const defaultPageSize = 3;

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

const queryTertuliasPaged = 'SELECT * FROM (' + queryTertulias + ') AS tbl' +
' ORDER BY nextEventDate DESC, name' +
' OFFSET ((@pageNr - 1) * @pageSize) ROWS FETCH NEXT @pageSize ROWS ONLY';

const queryTertuliaX = 'SELECT DISTINCT' +
	' tr_id, tr_name, tr_subject, ' + // Tertulia
	' lo_name, lo_address, lo_zip, lo_city, lo_country, lo_latitude, lo_longitude, ' + // Location
	' sc_type, _Schedule.nv_name AS schedule, _Schedule.nv_description AS description,' + // Schedule
	' tr_is_private, ' +
	' _Member.nv_name AS nv_name' + // Role
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN Members    ON mb_tertulia = tr_id' +
' INNER JOIN Users      ON mb_user = us_id' +
' INNER JOIN EnumValues AS _Member ON mb_role = _Member.nv_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid' +
' AND tr_id = @tertulia';

const queryPublicTertulias = 'SELECT ' +
	' tr_id, tr_name, tr_subject, ' + // Tertulia
	' lo_name, lo_address, lo_zip, lo_city, lo_country, lo_latitude, lo_longitude, ' + // Location
	' sc_type, _Schedule.nv_name AS schedule, _Schedule.nv_description AS description' + // Schedule
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND tr_is_private = 0';

const queryPublicTertuliaX = 'SELECT' +
	' tr_id, tr_name, tr_subject, ' + // Tertulia
	' lo_name, lo_address, lo_zip, lo_city, lo_country, lo_latitude, lo_longitude, ' + // Location
	' sc_type, _Schedule.nv_name AS schedule, _Schedule.nv_description AS description' + // Schedule
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND tr_is_private = 0' +
' AND tr_id = @tertulia';

const queryScheduleMonthlyW = 'SELECT mw_id, mw_dow, mw_weeknr, mw_is_fromstart, mw_skip' +
' FROM MonthlyW' +
' INNER JOIN Schedules  ON mw_schedule = sc_id' +
' INNER JOIN Tertulias  ON sc_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid' +
' AND tr_id = @tertulia';

module.exports = function (configuration) {
    var router = express.Router();

	var completeError = function(err, res) {
	    if (err) {
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

    router.get('/', (req, res, next) => {
    	var pageNr = 1;
    	var pageSize = defaultPageSize;
		req.selectedQuery = queryTertuliasPaged;
		req.pageSize = pageSize;
		req.pageNr = pageNr;
	    req.paramsT = { 'sid': sql.NVarChar, 'pageNr': sql.Int, 'pageSize': sql.Int }; // String -> sql.NVarChar; Number -> sql.Int; Boolean -> sql.Bit; Date -> sql.DateTime; Buffer -> sql.VarBinary; sql.Table -> sql.TVP
	    req.paramsV = { 'sid': req.azureMobile.user.id, 'pageNr': pageNr, 'pageSize': pageSize };
	    req.t_links = '{ "details": { "href": "tertulias/:tertulia" } }';
	    goGetTertulias(req, res, next);
	});

    router.get('/public', (req, res, next) => {
		req.selectedQuery = queryPublicTertulias;
	    req.t_links = '{ "details": { "href": "tertulias/public/:tertulia" } }';
	    goGet(req, res, next);
	});

    router.get('/:tertulia', (req, res, next) => {
		req.selectedQuery = queryTertuliaX;
	    req.paramsT = { sid: sql.NVarChar, tertulia: sql.NVarChar };
	    req.paramsV = { sid: req.azureMobile.user.id, tertulia: req.params.tertulia };
	    req.t_links = '{ ' +
	    	'"self":      { "href": "tertulias/:tertulia" }, ' +
	    	'"edit":      { "href": "tertulias/:tertulia/edit" }, ' +
	    	'"location":  { "href": "tertulias/:tertulia/location" }, ' +
	    	'"schedule":  { "href": "tertulias/:tertulia/schedule" }, ' +
	    	'"members":   { "href": "tertulias/:tertulia/members" }, ' +
	    	'"messages":  { "href": "tertulias/:tertulia/messages" }, ' +
	    	'"events":    { "href": "tertulias/:tertulia/events" }, ' +
	    	'"nextevent": { "href": "tertulias/:tertulia/nextevent" } ' +
    	'}';
	    goGet(req, res, next);
	});

    router.get('/public/:tertulia', (req, res, next) => {
		req.selectedQuery = queryPublicTertuliaX;
	    req.paramsT = {};
	    req.paramsV = {};
	    req.t_links = '{ ' +
	    	'"self":      { "href": "tertulias/public/:tertulia" }, ' +
	    	'"subscribe": { "href": "tertulias/public/:tertulia/subscribe" }, ' +
	    	'"location":  { "href": "tertulias/public/:tertulia/location" }, ' +
	    	'"schedule":  { "href": "tertulias/public/:tertulia/schedule" }, ' +
	    	'"events":    { "href": "tertulias/public/:tertulia/events" }, ' +
	    	'"nextevent": { "href": "tertulias/public/:tertulia/nextevent" } ' +
    	'}';
	    goGet(req, res, next);
	});

    router.get('/public/:tertulia/subscribe', (req, res, next) => {
		req.selectedQuery = queryTertuliaX;
	    req.paramsT = {};
	    req.paramsV = {};
	    req.t_links = '{ ' +
	    	'"self":      { "href": "tertulias/public/:tertulia/subscribe" } ' +
    	'}';
	    goGet(req, res, next);
	});

	var goGetTertulias = function(req, res, next) {
		var selectedQuery = req.selectedQuery;
	    var paramsT = req.paramsT;
	    var paramsV = req.paramsV;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsT) preparedStatement.input(key, paramsT[key]);
	        preparedStatement.prepare(selectedQuery, function(err) {
	            if (err) { completeError(err, res); return; }
	            preparedStatement.execute(paramsV,
	                function(err, recordset, affected) {
	                    if (err) { completeError(err, res); return; }
	                    res.type('application/json');
	                    recordset.forEach(function(elem) {
	                    	if (typeof req.t_links !== typeof undefined)
		                    	elem['_links'] = JSON.parse(req.t_links.replace(/:tertulia/g, elem.tr_id));
	                    });
	                    preparedStatement.unprepare();
	                    var source = '/tertulias';
	                    console.log(req.Url);
	                    var result = {
	                    	tertulias: recordset,
	                    	page: {
                    			offset: req.pageNr,
                    			size: req.pageSize,
                    			itemsCount: recordset.length
	                    	},
	                    	links: {
	                    		self: {
	                    			href: source
                    			},
                    			add: {
                    				tag: 'ADD_TERTULIA',
                    				method: 'POST',
	                    			href: source
                    			},
								subscribe: {
                    				tag: 'SUBSCRIBE_TERTULIA',
                    				method: 'POST',
	                    			href: source + '/publicsearch'
                    			},
								nextPage: {
                    				tag: 'NEXT_PAGE',
                    				method: 'GET',
	                    			href: '/tertulias/page/' + (1 + req.pageNr)
                    			},
								previousPage: {
                    				tag: 'PREVIOUS_PAGE',
                    				method: 'GET',
	                    			href: '/tertulias/page/' + (0 + req.pageNr - 1)
                    			},
							}
	                    };
	                    console.log(result);
	                    res.json(result);
	                    next();
	                }
	            );
	        });
	    });
	}

	var goGet = function(req, res, next) {
		var selectedQuery = req.selectedQuery;
	    var paramsT = req.paramsT;
	    var paramsV = req.paramsV;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsT) preparedStatement.input(key, paramsT[key]);
	        preparedStatement.prepare(selectedQuery, function(err) {
	            if (err) { completeError(err, res); return; }
	            preparedStatement.execute(paramsV,
	                function(err, recordset, affected) {
	                    if (err) { completeError(err, res); return; }
	                    res.type('application/json');
	                    recordset.forEach(function(elem) {
	                    	if (typeof req.t_links !== typeof undefined)
		                    	elem['_links'] = JSON.parse(req.t_links.replace(/:tertulia/g, elem.tr_id));
	                    });
	                    preparedStatement.unprepare();
	                    res.json(recordset);
	                    next();
	                }
	            );
	        });
	    });
	}

	router.post('/', (req, res, next) => {
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
			new sql.Request()
			.input('name', sql.NVarChar(40), req.body.tr_name)
			.input('subject', sql.NVarChar(80), req.body.tr_subject)
			.input('userSid', sql.NVarChar(40), req.azureMobile.user.id)
			.input('weekDay', sql.NVarChar(20), 'Tuesday')
			.input('weekNr', sql.Int, 1)
			.input('fromStart', sql.BIT, 1)
			.input('skip', sql.Int, 0)
			.input('locationName', sql.NVarChar(40), req.body.lo_name)
			.input('locationAddress', sql.NVarChar(80), req.body.lo_address)
			.input('locationZip', sql.NVarChar(40), req.body.lo_zip)
			.input('locationCity', sql.NVarChar(40), req.body.lo_city)
			.input('locationCountry', sql.NVarChar(40), req.body.lo_country)
			.input('locationLatitude', sql.NVarChar(12), req.body.lo_latitude)
			.input('locationLongitude', sql.NVarChar(12), req.body.lo_longitude)
			.input('isPrivate', sql.Int, req.body.tr_is_private ? 1 : 0)
			.execute('sp_insertTertulia_MonthlyW_sid')
			.then((recordsets) => {
				console.log(recordsets);
				console.log('len: ' + recordsets.length);
				//console.log('r1: ' + recordsets[0][0][ErrorNumber]);
				//console.log('r2: ' + recordsets[0][ErrorNumber]);
				//console.log('r2: ' + recordsets[0]);
				if (recordsets.length == 0) {
					console.log('sending 201');
					res.status(201)	// 201: Created
						.type('application/json')
						.json( { result: 'Ok' } );
					return;
				} else {
					console.log('sending 409');
					res.status(409)	// 409: Conflict, 422: Unprocessable Entity (WebDAV; RFC 4918)
						.type('application/json')
						.json( { result: 'Duplicate' } );
					return;
				}
				next();
			})
			.catch(function(err) {
				console.log('catch 1');
				console.log(err);
				next();
			});
		})
		.catch(function(err) {
			console.log('catch 2');
			console.log(err);
			next();
		});
	})

    return router;

}
<|endoftext|>


<commit_before>import React from "react";

import { Pipeline, Values } from "sajari-react/controllers";
import { Response, Results, Summary, Paginator } from "sajari-react/ui/results";
import AutocompleteDropdown from "sajari-react/ui/text/AutocompleteDropdown";

import "sajari-react/ui/text/AutocompleteInput.css";
import "sajari-react/ui/text/AutocompleteDropdown.css";
import "sajari-react/ui/results/Results.css";
import "sajari-react/ui/results/Paginator.css";

const project = "sajariptyltd";
const collection = "sajari-com";
const autocompletePipeline = new Pipeline(project, collection, "autocomplete");
const websitePipeline = new Pipeline(project, collection, "website");
const autocompleteValues = new Values();
const websiteValues = new Values();

const App = () =>

    <AutocompleteDropdown
      values={autocompleteValues}
      pipeline={autocompletePipeline}
      suggestionAmount={10}
      submit={query => {
        websiteValues.set({ q: query, "q.override": true });
        websitePipeline.search(websiteValues.get());
      }}
    />
    <Response pipeline={websitePipeline}>

      <Results pipeline={websitePipeline} />
      <Paginator values={websiteValues} pipeline={websitePipeline} />
    </Response>

;

export default App;
<commit_msg>example: add control options to autocomplete search example<commit_after>import React from "react";

import { Pipeline, Values } from "sajari-react/controllers";
import { Response, Results, Summary, Paginator } from "sajari-react/ui/results";
import AutocompleteDropdown from "sajari-react/ui/text/AutocompleteDropdown";

import "sajari-react/ui/text/AutocompleteInput.css";
import "sajari-react/ui/text/AutocompleteDropdown.css";
import "sajari-react/ui/results/Results.css";
import "sajari-react/ui/results/Paginator.css";

const project = "sajariptyltd";
const collection = "sajari-com";
const autocompletePipeline = new Pipeline(project, collection, "autocomplete");
const websitePipeline = new Pipeline(project, collection, "website");
const autocompleteValues = new Values();
const websiteValues = new Values();

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { autocomplete: true, instant: false };
  }

  update = query => {
    if (this.state.instant && !this.state.autocomplete) {
      websiteValues.set({ q: query, "q.override": undefined });
      if (query) {
        websitePipeline.search(websiteValues.get());
        return;
      }
      websitePipeline.clearResponse(websiteValues.get());
      return;
    }
  };

  submit = query => {
    if (query) {
      websiteValues.set({ q: query, "q.override": true });
      websitePipeline.search(websiteValues.get());
      return;
    }
    websitePipeline.clearResponse();
  };

  render() {
    const { autocomplete, instant } = this.state;

    const valuesForAutocomplete = instant ? websiteValues : autocompleteValues;
    const pipelineForAutocomplete = instant
      ? websitePipeline
      : autocompletePipeline;

    const suggestionAmount = autocomplete ? 5 : 0;
    const searchAutocomplete =
      (autocomplete || instant) && !(instant && !autocomplete);
    const showCompletion = instant;

    return (

          Autocomplete
          <input
            type="checkbox"
            checked={autocomplete}
            onChange={() => this.setState({ autocomplete: !autocomplete })}
          />

          Instant
          <input
            type="checkbox"
            checked={instant}
            onChange={() => this.setState({ instant: !instant })}
          />

        <AutocompleteDropdown
          values={valuesForAutocomplete}
          pipeline={pipelineForAutocomplete}
          suggestionAmount={suggestionAmount}
          handleUpdate={this.update}
          handleSubmit={this.submit}
          search={searchAutocomplete}
          showCompletion={showCompletion}
        />
        <Response pipeline={websitePipeline}>

          <Results pipeline={websitePipeline} />
          <Paginator values={websiteValues} pipeline={websitePipeline} />
        </Response>

    );
  }
}

export default App;
<|endoftext|>


<commit_before>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

const queryPublicTertulias = 'SELECT' +
' TOP 25' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' lo_name       AS location' +
//' lo_latitude   AS latitude,' +
//' lo_longitude  AS longitude,' +
//' lo_geography.STDistance('POINT(38.7762 -9.171391)') AS Distance' +
' FROM Tertulias' +
' INNER JOIN Locations ON tr_location = lo_id' +
' WHERE tr_is_cancelled = 0' +
' AND tr_is_private = 0' +
' AND tr_id NOT IN (SELECT mb_tertulia FROM Tertulias INNER JOIN Members ON mb_tertulia = tr_id INNER JOIN Users ON mb_user = us_id WHERE us_sid = @sid)' +
' ORDER BY lo_geography.STDistance(\'POINT(38.7640613 -9.1123113)\')';

const queryTertuliaDetails = 'SELECT DISTINCT' +
	' tr_id                    AS id,' + // Tertulia
	' tr_name                  AS name,' +
	' tr_subject               AS subject,' +
	' lo_name                  AS location,' + // Location
	' lo_address               AS address,' +
	' lo_zip                   AS zip,' +
	' lo_city                  AS city,' +
	' lo_country               AS country,' +
	' lo_latitude              AS latitude,' +
	' lo_longitude             AS longitude,' +
	' sc_type                  AS scheduleId,' + // Schedule
	' _Schedule.nv_name        AS scheduleName,' +
	' _Schedule.nv_description AS scheduleDescription,' +
	' tr_is_private            AS private, ' +  // Private
	' _Member.nv_name          AS role' + // Role
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN Members    ON mb_tertulia = tr_id' +
' INNER JOIN Users      ON mb_user = us_id' +
' INNER JOIN EnumValues AS _Member ON mb_role = _Member.nv_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND (us_sid = @sid OR tr_is_private = 0)' +
' AND tr_id = @tertulia';

/* { 'SQL types': {
	'String': 'sql.NVarChar', 'Number': 'sql.Int', 'Boolean': 'sql.Bit', 'Date': 'sql.DateTime', 'Buffer': 'sql.VarBinary', 'sql.Table': 'sql.TVP'
} } */
module.exports = function (configuration) {
    var router = express.Router();

    router.get('/', (req, res, next) => {
		var route = '/tertulias';
		req['tertulias'] = {};
		req.tertulias['resultsTag'] = 'tertulias';
		req.tertulias['query'] = queryTertulias;
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar };
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id };
	    req.tertulias['jsonType'] = "array";
	    req.tertulias['links'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '" }, ' +
			'{ "rel": "create", "method": "POST", "href": "' + route + '" }, ' +
			'{ "rel": "searchPublic", "method": "GET", "href": "' + route + '/publicsearch" } ' +
		']';
	    req.tertulias['itemLinks'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '/:id" }, ' +
			'{ "rel": "update", "method": "PUT", "href": "' + route + '/:id" }, ' +
			'{ "rel": "delete", "method": "DELETE", "href": "' + route + '/:id" }, ' +
			'{ "rel": "unsubscribe", "method": "DELETE", "href": "' + route + '/:id/unsubscribe" } ' +
		']';
	    goGet(req, res, next);
	});

    router.get('/publicSearch', (req, res, next) => {
		console.log('in /publicsearch');
		var route = '/tertulias';
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
    		console.log(req.query);
			new sql.Request()
	    	.input('sid', sql.NVarChar(40), req.azureMobile.user.id)
	    	.input('query', sql.NVarChar, req.query.query)
	    	.input('latitude', sql.NVarChar, req.query.latitude)
	    	.input('longitude', sql.Int, parseFloat(req.query.longitude))
	    	.query('SELECT TOP 25' +
		    		' tr_id AS id,' +
		    		' tr_name AS name,' +
		    		' tr_subject AS subject,' +
		    		' lo_name AS location' +
	    		' FROM Tertulias' +
	    			' INNER JOIN Locations ON tr_location = lo_id' +
	    		' WHERE tr_is_cancelled = 0 AND tr_is_private = 0' +
		    		' AND tr_id NOT IN' +
		    			' (SELECT mb_tertulia FROM Tertulias' +
		    			' INNER JOIN Members ON mb_tertulia = tr_id' +
		    			' INNER JOIN Users ON mb_user = us_id WHERE us_sid = @sid)' +
				' ORDER BY lo_geography.STDistance(\'POINT( @latitude -9.1123113 )\')')
	    	.then(function(recordset) {
                var links = '[ { "rel": "self", "method": "GET", "href": "' + route + '/publicSearch" } ]';
                var itemLinks = '[ ' +
            	    	'{ "rel": "self", "method": "GET", "href": "' + route + '/:id" }, ' +
						'{ "rel": "subscribe", "method": "POST", "href": "' + route + '/:id/subscribe" }' +
					']';
                res.type('application/json');
                recordset.forEach(function(elem) {
                	elem['links'] = JSON.parse(itemLinks.replace(/:id/g, elem.id));
        		});
                var results = {};
            	results['tertulias'] = recordset;
                results['links'] = JSON.parse(links);
	    		console.log(results);
                res.json(results);
                res.sendStatus(200);
                return next();
            })
	    });
	});
/*
		var route = '/tertulias';
		req['tertulias'] = {};
		req.tertulias['resultsTag'] = 'tertulias';
		req.tertulias['query'] = queryPublicTertulias;
	    req.tertulias['paramsTypes'] = {
	    	'sid': sql.NVarChar
	    	, 'query': sql.NVarChar
	    	, 'latitude': sql.Int
	    	, 'longitude': sql.Int
	    };
	    var latitude = parseFloat(req.query.latitude);
	    var longitude = parseFloat(req.query.longitude);
	    req.tertulias['paramsValues'] = {
	    	'sid': req.azureMobile.user.id
	    	, 'query': req.query.query
	    	, 'latitude': parseFloat(req.query.latitude)
	    	, 'longitude': parseFloat(req.query.longitude)
	    };
	    req.tertulias['jsonType'] = "array";
	    req.tertulias['links'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '/publicSearch" }' +
		']';
	    req.tertulias['itemLinks'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '/:id" }, ' +
			'{ "rel": "subscribe", "method": "POST", "href": "' + route + '/:id/subscribe" }' +
		']';
	    goGet(req, res, next);
	});
	*/

	router.get('/:tr_id', (req, res, next) => {
		console.log('in /:tr_id');
		var tr_id = req.params.tr_id;

		if (isNaN(tr_id))
			return next();

		var route = '/tertulias/' + tr_id;
		req['tertulias'] = {};
		req.tertulias['resultsTag'] = 'tertulia';
		req.tertulias['query'] = queryTertuliaDetails;
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar, 'tertulia': sql.Int };
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id, 'tertulia': tr_id };
	    req.tertulias['jsonType'] = "object";
	    req.tertulias['links'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '" }, ' +
			'{ "rel": "update", "method": "PATCH", "href": "' + route + '" }, ' +
			'{ "rel": "delete", "method": "DELETE", "href": "' + route + '" }, ' +
			'{ "rel": "subscribe", "method": "POST", "href": "' + route + '/subscribe" }, ' +
			'{ "rel": "unsubscribe", "method": "DELETE", "href": "' + route + '/unsubscribe" } ' +
		']';
	    goGet(req, res, next);
	});

	router.post('/', (req, res, next) => {
		console.log('in /');
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
			new sql.Request()
			.input('name', sql.NVarChar(40), req.body.name)
			.input('subject', sql.NVarChar(80), req.body.subject)
			.input('locationName', sql.NVarChar(40), req.body.location)
			.input('locationAddress', sql.NVarChar(80), req.body.address)
			.input('locationZip', sql.NVarChar(40), req.body.zip)
			.input('locationCity', sql.NVarChar(40), req.body.city)
			.input('locationCountry', sql.NVarChar(40), req.body.country)
			.input('locationLatitude', sql.NVarChar(12), req.body.latitude)
			.input('locationLongitude', sql.NVarChar(12), req.body.longitude)
			.input('weekDay', sql.NVarChar(20), 'Tuesday')
			.input('weekNr', sql.Int, 1)
			.input('fromStart', sql.BIT, 1)
			.input('skip', sql.Int, 0)
			.input('isPrivate', sql.Int, req.body.isPrivate ? 1 : 0)
			.input('userSid', sql.NVarChar(40), req.azureMobile.user.id)
			.execute('sp_insertTertulia_MonthlyW_sid')
			.then((recordsets) => {
				if (recordsets.length == 0) {
					res.status(201)	// 201: Created
						.type('application/json')
						.json( { result: 'Ok' } );
					return next();
				} else {
					res.status(409)	// 409: Conflict, 422: Unprocessable Entity (WebDAV; RFC 4918)
						.type('application/json')
						.json( { result: 'Duplicate' } );
					return next('409');
				}
				next();
			})
			.catch(function(err) {
				next(err);
			});
		})
		.catch(function(err) {
			return next(err);
		});
	});

	router.post('/:tr_id/subscribe', (req, res, next) => {
		console.log('in /:tr_id/subscribe');
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
			new sql.Request()
			.input('sid', sql.NVarChar(40), req.azureMobile.user.id)
			.input('tertulia', sql.Int, req.params.tr_id)
			.execute('spSubscribe')
			.then((recordset) => {
				console.log(recordset.returnValue);
				if (recordset.returnValue = 1) {
					res.sendStatus(200);
				} else {
					res.sendStatus(409);
				}
				return next();
			})
			.catch(function(err) {
				console.log('catch1');
				console.log(err);
				next(err);
			});
		})
		.catch(function(err) {
			console.log('catch');
			console.log(err);
			return next(err);
		});
	});

	var completeError = function(err, res) {
	    if (err) {
	    	console.log("Error:");
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

	var goGet = function(req, res, next) {
		console.log('in GoGet');
		var query = req.tertulias.query;
		var resultsTag = req.tertulias.resultsTag;
	    var paramsTypes = req.tertulias.paramsTypes;
	    var paramsValues = req.tertulias.paramsValues;
	    var links = req.tertulias.links;
	    var itemLinks = req.tertulias.itemLinks;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsTypes)
	        	preparedStatement.input(key, paramsTypes[key]);
	        preparedStatement.prepare(query, function(err) {
	            if (err) {
	            	completeError(err, res);
	            	return next(err);
	            }
	            preparedStatement.execute(paramsValues,
	                function(err, recordset, affected) {
	                    if (err) {
	                    	completeError(err, res);
	                    	return next(err);
	                    }
	                    res.type('application/json');
                    	if (typeof itemLinks !== typeof undefined) {
		                    recordset.forEach(function(elem) {
		                    	elem['links'] = JSON.parse(itemLinks.replace(/:id/g, elem.id));
                    		});
	                    };
	                    preparedStatement.unprepare();
	                    var results = {};
	                    if (req.tertulias.jsonType == "array")
	                    	results[resultsTag] = recordset;
	                    else
	                    	results[resultsTag] = recordset.length == 0 ? {} : recordset[0];
	                    results['links'] = JSON.parse(links);
	                    res.json(results);
	                    return next();
	                }
	            );
	        });
	    });
	};

    return router;

}
<commit_msg>wip save<commit_after>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

const queryPublicTertulias = 'SELECT' +
' TOP 25' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' lo_name       AS location' +
//' lo_latitude   AS latitude,' +
//' lo_longitude  AS longitude,' +
//' lo_geography.STDistance('POINT(38.7762 -9.171391)') AS Distance' +
' FROM Tertulias' +
' INNER JOIN Locations ON tr_location = lo_id' +
' WHERE tr_is_cancelled = 0' +
' AND tr_is_private = 0' +
' AND tr_id NOT IN (SELECT mb_tertulia FROM Tertulias INNER JOIN Members ON mb_tertulia = tr_id INNER JOIN Users ON mb_user = us_id WHERE us_sid = @sid)' +
' ORDER BY lo_geography.STDistance(\'POINT(38.7640613 -9.1123113)\')';

const queryTertuliaDetails = 'SELECT DISTINCT' +
	' tr_id                    AS id,' + // Tertulia
	' tr_name                  AS name,' +
	' tr_subject               AS subject,' +
	' lo_name                  AS location,' + // Location
	' lo_address               AS address,' +
	' lo_zip                   AS zip,' +
	' lo_city                  AS city,' +
	' lo_country               AS country,' +
	' lo_latitude              AS latitude,' +
	' lo_longitude             AS longitude,' +
	' sc_type                  AS scheduleId,' + // Schedule
	' _Schedule.nv_name        AS scheduleName,' +
	' _Schedule.nv_description AS scheduleDescription,' +
	' tr_is_private            AS private, ' +  // Private
	' _Member.nv_name          AS role' + // Role
' FROM Tertulias' +
' INNER JOIN Locations  ON tr_location = lo_id' +
' INNER JOIN Schedules  ON tr_schedule = sc_id' +
' INNER JOIN Members    ON mb_tertulia = tr_id' +
' INNER JOIN Users      ON mb_user = us_id' +
' INNER JOIN EnumValues AS _Member ON mb_role = _Member.nv_id' +
' INNER JOIN EnumValues AS _Schedule ON sc_type = _Schedule.nv_id' +
' WHERE tr_is_cancelled = 0 AND (us_sid = @sid OR tr_is_private = 0)' +
' AND tr_id = @tertulia';

/* { 'SQL types': {
	'String': 'sql.NVarChar', 'Number': 'sql.Int', 'Boolean': 'sql.Bit', 'Date': 'sql.DateTime', 'Buffer': 'sql.VarBinary', 'sql.Table': 'sql.TVP'
} } */
module.exports = function (configuration) {
    var router = express.Router();

    router.get('/', (req, res, next) => {
		var route = '/tertulias';
		req['tertulias'] = {};
		req.tertulias['resultsTag'] = 'tertulias';
		req.tertulias['query'] = queryTertulias;
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar };
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id };
	    req.tertulias['jsonType'] = "array";
	    req.tertulias['links'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '" }, ' +
			'{ "rel": "create", "method": "POST", "href": "' + route + '" }, ' +
			'{ "rel": "searchPublic", "method": "GET", "href": "' + route + '/publicsearch" } ' +
		']';
	    req.tertulias['itemLinks'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '/:id" }, ' +
			'{ "rel": "update", "method": "PUT", "href": "' + route + '/:id" }, ' +
			'{ "rel": "delete", "method": "DELETE", "href": "' + route + '/:id" }, ' +
			'{ "rel": "unsubscribe", "method": "DELETE", "href": "' + route + '/:id/unsubscribe" } ' +
		']';
	    goGet(req, res, next);
	});

    router.get('/publicSearch', (req, res, next) => {
		console.log('in /publicsearch');
		var route = '/tertulias';
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
    		console.log(req.query);
			new sql.Request()
	    	.input('sid', sql.NVarChar(40), req.azureMobile.user.id)
	    	.input('query', sql.NVarChar, req.query.query)
	    	.input('latitude', sql.NVarChar, req.query.latitude)
	    	.input('longitude', sql.Int, parseFloat(req.query.longitude))
	    	.query('SELECT TOP 25' +
		    		' tr_id AS id,' +
		    		' tr_name AS name,' +
		    		' tr_subject AS subject,' +
		    		' lo_name AS location' +
	    		' FROM Tertulias' +
	    			' INNER JOIN Locations ON tr_location = lo_id' +
	    		' WHERE tr_is_cancelled = 0 AND tr_is_private = 0' +
		    		' AND tr_id NOT IN' +
		    			' (SELECT mb_tertulia FROM Tertulias' +
		    			' INNER JOIN Members ON mb_tertulia = tr_id' +
		    			' INNER JOIN Users ON mb_user = us_id WHERE us_sid = @sid)' +
				' ORDER BY lo_geography.STDistance(\'POINT( 38.11 -9.1123113 )\')')
	    	.then(function(recordset) {
                var links = '[ { "rel": "self", "method": "GET", "href": "' + route + '/publicSearch" } ]';
                var itemLinks = '[ ' +
            	    	'{ "rel": "self", "method": "GET", "href": "' + route + '/:id" }, ' +
						'{ "rel": "subscribe", "method": "POST", "href": "' + route + '/:id/subscribe" }' +
					']';
                res.type('application/json');
                recordset.forEach(function(elem) {
                	elem['links'] = JSON.parse(itemLinks.replace(/:id/g, elem.id));
        		});
                var results = {};
            	results['tertulias'] = recordset;
                results['links'] = JSON.parse(links);
	    		console.log(results);
                res.json(results);
                res.sendStatus(200);
                return next();
            })
	    });
	});

	router.get('/:tr_id', (req, res, next) => {
		console.log('in /:tr_id');
		var tr_id = req.params.tr_id;

		if (isNaN(tr_id))
			return next();

		var route = '/tertulias/' + tr_id;
		req['tertulias'] = {};
		req.tertulias['resultsTag'] = 'tertulia';
		req.tertulias['query'] = queryTertuliaDetails;
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar, 'tertulia': sql.Int };
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id, 'tertulia': tr_id };
	    req.tertulias['jsonType'] = "object";
	    req.tertulias['links'] = '[ ' +
			'{ "rel": "self", "method": "GET", "href": "' + route + '" }, ' +
			'{ "rel": "update", "method": "PATCH", "href": "' + route + '" }, ' +
			'{ "rel": "delete", "method": "DELETE", "href": "' + route + '" }, ' +
			'{ "rel": "subscribe", "method": "POST", "href": "' + route + '/subscribe" }, ' +
			'{ "rel": "unsubscribe", "method": "DELETE", "href": "' + route + '/unsubscribe" } ' +
		']';
	    goGet(req, res, next);
	});

	router.post('/', (req, res, next) => {
		console.log('in /');
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
			new sql.Request()
			.input('name', sql.NVarChar(40), req.body.name)
			.input('subject', sql.NVarChar(80), req.body.subject)
			.input('locationName', sql.NVarChar(40), req.body.location)
			.input('locationAddress', sql.NVarChar(80), req.body.address)
			.input('locationZip', sql.NVarChar(40), req.body.zip)
			.input('locationCity', sql.NVarChar(40), req.body.city)
			.input('locationCountry', sql.NVarChar(40), req.body.country)
			.input('locationLatitude', sql.NVarChar(12), req.body.latitude)
			.input('locationLongitude', sql.NVarChar(12), req.body.longitude)
			.input('weekDay', sql.NVarChar(20), 'Tuesday')
			.input('weekNr', sql.Int, 1)
			.input('fromStart', sql.BIT, 1)
			.input('skip', sql.Int, 0)
			.input('isPrivate', sql.Int, req.body.isPrivate ? 1 : 0)
			.input('userSid', sql.NVarChar(40), req.azureMobile.user.id)
			.execute('sp_insertTertulia_MonthlyW_sid')
			.then((recordsets) => {
				if (recordsets.length == 0) {
					res.status(201)	// 201: Created
						.type('application/json')
						.json( { result: 'Ok' } );
					return next();
				} else {
					res.status(409)	// 409: Conflict, 422: Unprocessable Entity (WebDAV; RFC 4918)
						.type('application/json')
						.json( { result: 'Duplicate' } );
					return next('409');
				}
				next();
			})
			.catch(function(err) {
				next(err);
			});
		})
		.catch(function(err) {
			return next(err);
		});
	});

	router.post('/:tr_id/subscribe', (req, res, next) => {
		console.log('in /:tr_id/subscribe');
	    sql.connect(util.sqlConfiguration)
	    .then(function() {
			new sql.Request()
			.input('sid', sql.NVarChar(40), req.azureMobile.user.id)
			.input('tertulia', sql.Int, req.params.tr_id)
			.execute('spSubscribe')
			.then((recordset) => {
				console.log(recordset.returnValue);
				if (recordset.returnValue = 1) {
					res.sendStatus(200);
				} else {
					res.sendStatus(409);
				}
				return next();
			})
			.catch(function(err) {
				console.log('catch1');
				console.log(err);
				next(err);
			});
		})
		.catch(function(err) {
			console.log('catch');
			console.log(err);
			return next(err);
		});
	});

	var completeError = function(err, res) {
	    if (err) {
	    	console.log("Error:");
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

	var goGet = function(req, res, next) {
		console.log('in GoGet');
		var query = req.tertulias.query;
		var resultsTag = req.tertulias.resultsTag;
	    var paramsTypes = req.tertulias.paramsTypes;
	    var paramsValues = req.tertulias.paramsValues;
	    var links = req.tertulias.links;
	    var itemLinks = req.tertulias.itemLinks;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsTypes)
	        	preparedStatement.input(key, paramsTypes[key]);
	        preparedStatement.prepare(query, function(err) {
	            if (err) {
	            	completeError(err, res);
	            	return next(err);
	            }
	            preparedStatement.execute(paramsValues,
	                function(err, recordset, affected) {
	                    if (err) {
	                    	completeError(err, res);
	                    	return next(err);
	                    }
	                    res.type('application/json');
                    	if (typeof itemLinks !== typeof undefined) {
		                    recordset.forEach(function(elem) {
		                    	elem['links'] = JSON.parse(itemLinks.replace(/:id/g, elem.id));
                    		});
	                    };
	                    preparedStatement.unprepare();
	                    var results = {};
	                    if (req.tertulias.jsonType == "array")
	                    	results[resultsTag] = recordset;
	                    else
	                    	results[resultsTag] = recordset.length == 0 ? {} : recordset[0];
	                    results['links'] = JSON.parse(links);
	                    res.json(results);
	                    return next();
	                }
	            );
	        });
	    });
	};

    return router;

}
<|endoftext|>


<commit_before>/**
 * Copyright 2013 massimocorner.com
 * @author      Massimo Foti (massimo@massimocorner.com)
 * @require     luga.js
 */

"use strict";
if(typeof(luga) === "undefined") {
	throw("Unable to find luga.js");
}
luga.namespace("luga.validator");

luga.validator.CONST = {
	FORM_SELECTOR: "form[data-luga-validate]",
	ATTRIBUTES: {
		VALIDATE: "data-luga-validate",
		BLOCK_SUBMIT: "data-luga-blocksubmit"
	}
};

/**
 * Form validator widget
 *
 * @param options.formNode:          Root node for widget (DOM reference). Required
 * @param options.blocksubmit:       Disable submit buttons if the form isn't valid.
 *                                   This prevents multiple submits but also prevents the value of the submit buttons from being passed as part of the HTTP request.
 *                                   Set this options to false to keep the submit buttons enabled. Optional
 */
luga.validator.form = function(options) {

	this.options = {
		blocksubmit: jQuery(options.formNode).attr(luga.validator.CONST.ATTRIBUTES.BLOCK_SUBMIT) || true
	};
	jQuery.extend(this.options, options);
	var self = this;
	self.validators = [];

	// Execute multiple validators. Returns an array of validators containing errors
	// Returns and empty array if no errors
	this.executeValidators = function() {
		var validatedFields = {};
		// Store all the field validators that contains errors
		var activeValidators = [];
		// Validate all the fields
		for(var i=0; i<self.validators.length; i++) {
			if(self.validators[i].validate) {
				if(validatedFields[self.validators[i].name]) {
					// Already validated checkbox or radio, skip it
					continue;
				}
				if(self.validators[i].validate()) {
					activeValidators[activeValidators.length] = self.validators[i];
				}
				// Keep track of already validated fields (to skip already validated checkboxes or radios)
				validatedFields[self.validators[i].name] = true;
			}
		}
		return activeValidators;
	};

	this.isValid = function() {
		var activeValidators = this.executeValidators();
		return activeValidators.length === 0;
	};

};<commit_msg>Minor changes to comments<commit_after>/**
 * Copyright 2013 massimocorner.com
 * @author      Massimo Foti (massimo@massimocorner.com)
 * @require     luga.js
 */

"use strict";
if(typeof(luga) === "undefined") {
	throw("Unable to find luga.js");
}
luga.namespace("luga.validator");

luga.validator.CONST = {
	FORM_SELECTOR: "form[data-luga-validate]",
	ATTRIBUTES: {
		VALIDATE: "data-luga-validate",
		BLOCK_SUBMIT: "data-luga-blocksubmit"
	}
};

/**
 * Form validator widget
 *
 * @param options.formNode:          Root node for widget (DOM reference). Required
 * @param options.blocksubmit:       Disable submit buttons if the form isn't valid.
 *                                   This prevents multiple submits but also prevents the value of the submit buttons from being passed as part of the HTTP request.
 *                                   Set this options to false to keep the submit buttons enabled. Optional
 */
luga.validator.form = function(options) {

	this.options = {
		blocksubmit: jQuery(options.formNode).attr(luga.validator.CONST.ATTRIBUTES.BLOCK_SUBMIT) || true
	};
	jQuery.extend(this.options, options);
	var self = this;
	self.validators = [];

	// Execute multiple validators. Returns an array of field validators that are in invalid state
	// Returns and empty array if no errors
	this.executeValidators = function() {
		// Keep track of already validated fields (to skip already validated checkboxes or radios)
		var validatedFields = {};
		// Store all the invalid field validators
		var activeValidators = [];
		// Validate all the fields
		for(var i=0; i<self.validators.length; i++) {
			if(self.validators[i].validate) {
				if(validatedFields[self.validators[i].name]) {
					// Already validated checkbox or radio, skip it
					continue;
				}
				if(self.validators[i].validate()) {
					activeValidators[activeValidators.length] = self.validators[i];
				}
				validatedFields[self.validators[i].name] = true;
			}
		}
		return activeValidators;
	};

	this.isValid = function() {
		var activeValidators = this.executeValidators();
		return activeValidators.length === 0;
	};

};<|endoftext|>


<commit_before>/**
 * [mainForm main menu form]
 * @return {[type]} [description]
 */
function mainForm() {
	var fields = [{
		text: 'New Game',
		type: 'button',
		callback: function() {
			console.log('click')
			selectMap(mainMenu);
		}
	}];

	var mainMenu = new Form(fields);
	mainMenu.render();
}

/**
* [select map menu form]
*/
function selectMap(previous) {
	previous.hide();
	var fields = [{
		text: 'back',
		type: 'button',
		callback: function() {
			newGame.hide();
			mainForm();
		}
	}, {
		text: 'next',
		type: 'button',
		callback: function() {
			selectPlayers(newGame);
		}
	}, {
		text: 'map',
		type: 'select',
		options: ['forrest', 'dungeon']
	}];

	var newGame = new Form(100, 100, fields);
	newGame.render();
}

/**
* [select map menu form]
*/
function selectPlayers(previous) {
	previous.hide();

	var fields = [{
		text: 'Start Game',
		type: 'button',
		callback: function() {
			startGame.hide();
			alert(startGame.getValue('numberOfPlayers'));
		}
	}, {
		text: 'Number of Players',
		type: 'range',
		id: 'numberOfPlayers',
		min: 1,
		max: 4
	}];

	var startGame = new Form(200, 200, fields);
	startGame.render();
}

mainForm();<commit_msg>started plugging maploader into UI<commit_after>/**
 * [mainForm main menu form]
 * @return {[type]} [description]
 */
function mainForm() {
	var fields = [{
		text: 'New Game',
		type: 'button',
		callback: function() {
			console.log('click')
			selectMap(mainMenu);
		}
	}];

	var mainMenu = new Form(fields);
	mainMenu.render();
}

/**
* [select map menu form]
*/
function selectMap(previous) {
	previous.hide();
	var fields = [{
		text: 'back',
		type: 'button',
		callback: function() {
			newGame.hide();
			mainForm();
		}
	}, {
		text: 'next',
		type: 'button',
		callback: function() {
			console.log('next thing');
			console.log(newGame.getValue('mapname'))
			console.log('named')
			selectPlayers(newGame);
		}
	}, {
		text: 'map',
		type: 'select',
		options: ['forrest', 'dungeon'],
		id: 'mapname'
	}];

	var newGame = new Form(100, 100, fields);
	newGame.render();
}

/**
* [select map menu form]
*/
function selectPlayers(previous) {
	previous.hide();

	var fields = [{
		text: 'Start Game',
		type: 'button',
		callback: function() {
			startGame.hide();
			alert(startGame.getValue('numberOfPlayers'));
		}
	}, {
		text: 'Number of Players',
		type: 'range',
		id: 'numberOfPlayers',
		min: 1,
		max: 4
	}];
	console.log("this is a new game")
	var startGame = new Form(200, 200, fields);
	startGame.render();
}

mainForm();<|endoftext|>


<commit_before>// Canvas.js
'use strict';

import React from 'react';
import d3 from 'd3';
import {toDownloadLinks} from './SvgConverter';
import {CURSOR_LAYER_RELATIVE_TOP, SVG_BACKGROUND_COLOR, GRID_SIZE} from './Constant';

const line = d3.svg.line()
    .x(d => d[0])
    .y(d => d[1]);

export default class Canvas extends React.Component {

    static get propTypes() {
        return {
            width: React.PropTypes.number,
            height: React.PropTypes.number,
            dataset: React.PropTypes.array,
            style: React.PropTypes.object,
            renderGrid: React.PropTypes.bool,
            renderDownloadMenu: React.PropTypes.bool
        };
    }

    static get contextTypes() {
        return {
            emitter: React.PropTypes.object
        };
    }

    closeDownload(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.context.emitter.emit('close.download.menu');
    }

    componentDidMount() {
        let svg = d3.select(this.refs.canvasLayer).append('svg')
            .attr('width', this.props.width)
            .attr('height', this.props.height);

        if (this.props.style && this.props.style.backgroundColor) {
            svg.attr('style', 'background: ' + this.props.style.backgroundColor);
        } else {
            svg.attr('style', 'background: ' + SVG_BACKGROUND_COLOR);
        }

        let that = this;
        d3.select(this.refs.cursorLayer).on('mousemove.canvas', function() {
            const point = [d3.event.offsetX, d3.event.offsetY + 24 - CURSOR_LAYER_RELATIVE_TOP];
            that.context.emitter.emit('mousemove.canvas', point);
        });
        d3.select(this.refs.cursorLayer).on('click', function() {
            that.context.emitter.emit('close.download.menu');
            const point = [d3.event.offsetX, d3.event.offsetY + 24 - CURSOR_LAYER_RELATIVE_TOP];
            that.context.emitter.emit('click.canvas', point);
        });

        this.drawWhiteboardCanvas();
        this.createDownloadLinks();
    }

    componentDidUpdate() {
        this.drawWhiteboardCanvas();
        this.createDownloadLinks();
    }

    render() {
        let wrapperStyle = {
            position: 'relative',
            width: this.props.width,
            height: this.props.height
        };
        let menuLayerStyle = {
            position: 'absolute',
            top: 0,
            zIndex: this.props.renderDownloadMenu ? 3000 : 1000,
            width: this.props.width,
            height: this.props.height,
            backgroundColor: this.props.renderDownloadMenu ? 'rgba(0, 0, 0, 0.1)' : 'rgba(255, 255, 255, 0)'
        };
        let cursorLayerStyle = {
            position: 'absolute',
            top: -CURSOR_LAYER_RELATIVE_TOP,
            zIndex: 2000,
            width: this.props.width,
            height: this.props.height,
            cursor: 'url(css/ic_edit_' + this.props.strokeColor + '_24px.svg), default'
        };
        let canvasLayerStyle = {
            position: 'absolute',
            top: 0,
            width: this.props.width,
            height: this.props.height
        };
        return (

{this.renderDownloadMenu()}

        );
    }

    renderDownloadMenu() {
        if (this.props.renderDownloadMenu) {
            let menuDialogStyle = {
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                margin: 'auto',
                padding: 10,
                width: 200,
                height: 120,
                backgroundColor: 'rgb(255, 255, 255)'
            };
            return (

                         this.closeDownload(ev)}>[X]

                        [Save as SVG]

                        [Save as PNG]

                        [Save as JPEG]

            );
        }
    }

    drawWhiteboardCanvas() {
        let svg = d3.select('svg');
        svg.selectAll('path').remove();

        if (this.props.renderGrid) {
            let xCount = this.props.width / GRID_SIZE;
            for (var x = 0; x < xCount; x++) {
                svg.append('path')
                    .datum([[x * GRID_SIZE, 0], [x * GRID_SIZE, this.props.height]])
                    .classed('line', true)
                    .attr('d', line)
                    .attr('fill', 'none')
                    .attr('stroke', 'gray')
                    .attr('stroke-width', 1);
            }

            let yCount = this.props.height / GRID_SIZE;
            for (var y = 0; y < yCount; y++) {
                svg.append('path')
                    .datum([[0, y * GRID_SIZE], [this.props.width, y * GRID_SIZE]])
                    .classed('line', true)
                    .attr('d', line)
                    .attr('fill', 'none')
                    .attr('stroke', 'gray')
                    .attr('stroke-width', 1);
            }
        }

        for (var i = 0; i < this.props.dataset.length; i++) {
            var d = this.props.dataset[i];
            if (d.values.length <= 1) {
                continue;
            }
            svg.append('path')
                .datum(d.values)
                .classed('line', true)
                .attr('d', line)
                .attr('fill', 'none')
                .attr('stroke', d.strokeColor)
                .attr('stroke-width', d.strokeWidth);
        }
    }

    createDownloadLinks() {
        if (this.props.renderDownloadMenu) {
            let svg = d3.select('svg');
            let svgLink = d3.select(this.refs.svgLink);
            let pngLink = d3.select(this.refs.pngLink);
            let jpegLink = d3.select(this.refs.jpegLink);
            toDownloadLinks(svg, svgLink, pngLink, jpegLink);
        }
    }

}
<commit_msg>Remove unnecessary event<commit_after>// Canvas.js
'use strict';

import React from 'react';
import d3 from 'd3';
import {toDownloadLinks} from './SvgConverter';
import {CURSOR_LAYER_RELATIVE_TOP, SVG_BACKGROUND_COLOR, GRID_SIZE} from './Constant';

const line = d3.svg.line()
    .x(d => d[0])
    .y(d => d[1]);

export default class Canvas extends React.Component {

    static get propTypes() {
        return {
            width: React.PropTypes.number,
            height: React.PropTypes.number,
            dataset: React.PropTypes.array,
            style: React.PropTypes.object,
            renderGrid: React.PropTypes.bool,
            renderDownloadMenu: React.PropTypes.bool
        };
    }

    static get contextTypes() {
        return {
            emitter: React.PropTypes.object
        };
    }

    closeDownload(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.context.emitter.emit('close.download.menu');
    }

    componentDidMount() {
        let svg = d3.select(this.refs.canvasLayer).append('svg')
            .attr('width', this.props.width)
            .attr('height', this.props.height);

        if (this.props.style && this.props.style.backgroundColor) {
            svg.attr('style', 'background: ' + this.props.style.backgroundColor);
        } else {
            svg.attr('style', 'background: ' + SVG_BACKGROUND_COLOR);
        }

        let that = this;
        d3.select(this.refs.cursorLayer).on('mousemove.canvas', function() {
            const point = [d3.event.offsetX, d3.event.offsetY + 24 - CURSOR_LAYER_RELATIVE_TOP];
            that.context.emitter.emit('mousemove.canvas', point);
        });
        d3.select(this.refs.cursorLayer).on('click', function() {
            const point = [d3.event.offsetX, d3.event.offsetY + 24 - CURSOR_LAYER_RELATIVE_TOP];
            that.context.emitter.emit('click.canvas', point);
        });

        this.drawWhiteboardCanvas();
        this.createDownloadLinks();
    }

    componentDidUpdate() {
        this.drawWhiteboardCanvas();
        this.createDownloadLinks();
    }

    render() {
        let wrapperStyle = {
            position: 'relative',
            width: this.props.width,
            height: this.props.height
        };
        let menuLayerStyle = {
            position: 'absolute',
            top: 0,
            zIndex: this.props.renderDownloadMenu ? 3000 : 1000,
            width: this.props.width,
            height: this.props.height,
            backgroundColor: this.props.renderDownloadMenu ? 'rgba(0, 0, 0, 0.1)' : 'rgba(255, 255, 255, 0)'
        };
        let cursorLayerStyle = {
            position: 'absolute',
            top: -CURSOR_LAYER_RELATIVE_TOP,
            zIndex: 2000,
            width: this.props.width,
            height: this.props.height,
            cursor: 'url(css/ic_edit_' + this.props.strokeColor + '_24px.svg), default'
        };
        let canvasLayerStyle = {
            position: 'absolute',
            top: 0,
            width: this.props.width,
            height: this.props.height
        };
        return (

{this.renderDownloadMenu()}

        );
    }

    renderDownloadMenu() {
        if (this.props.renderDownloadMenu) {
            let menuDialogStyle = {
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                margin: 'auto',
                padding: 10,
                width: 200,
                height: 120,
                backgroundColor: 'rgb(255, 255, 255)'
            };
            return (

                         this.closeDownload(ev)}>[X]

                        [Save as SVG]

                        [Save as PNG]

                        [Save as JPEG]

            );
        }
    }

    drawWhiteboardCanvas() {
        let svg = d3.select('svg');
        svg.selectAll('path').remove();

        if (this.props.renderGrid) {
            let xCount = this.props.width / GRID_SIZE;
            for (var x = 0; x < xCount; x++) {
                svg.append('path')
                    .datum([[x * GRID_SIZE, 0], [x * GRID_SIZE, this.props.height]])
                    .classed('line', true)
                    .attr('d', line)
                    .attr('fill', 'none')
                    .attr('stroke', 'gray')
                    .attr('stroke-width', 1);
            }

            let yCount = this.props.height / GRID_SIZE;
            for (var y = 0; y < yCount; y++) {
                svg.append('path')
                    .datum([[0, y * GRID_SIZE], [this.props.width, y * GRID_SIZE]])
                    .classed('line', true)
                    .attr('d', line)
                    .attr('fill', 'none')
                    .attr('stroke', 'gray')
                    .attr('stroke-width', 1);
            }
        }

        for (var i = 0; i < this.props.dataset.length; i++) {
            var d = this.props.dataset[i];
            if (d.values.length <= 1) {
                continue;
            }
            svg.append('path')
                .datum(d.values)
                .classed('line', true)
                .attr('d', line)
                .attr('fill', 'none')
                .attr('stroke', d.strokeColor)
                .attr('stroke-width', d.strokeWidth);
        }
    }

    createDownloadLinks() {
        if (this.props.renderDownloadMenu) {
            let svg = d3.select('svg');
            let svgLink = d3.select(this.refs.svgLink);
            let pngLink = d3.select(this.refs.pngLink);
            let jpegLink = d3.select(this.refs.jpegLink);
            toDownloadLinks(svg, svgLink, pngLink, jpegLink);
        }
    }

}
<|endoftext|>


<commit_before>$(function () {

    display_control();
    slider_control();

    $('body').bind('click', function (e) {
        var $target = $(e.target);
        if ($target.closest('.btn_menu').length > 0) {
            $('.area_sidebar').show();
            $('.area_popup').hide();
            $('body').css('overflow', 'hidden');
        } else if ($target.closest('.btn_search').length > 0) {
            $('.area_sidebar').hide();
            $('.area_popup').show();
            $('body').css('overflow', 'hidden');
        } else if ($target.closest('.inner_sidebar').length == 0 && $target.closest('.area_popup').length == 0) {
            $('.area_sidebar').hide();
            $('.area_popup').hide();
            $('body').css('overflow', '');
        }
    });

    $('.btn_close').on('click', function () {
        $('.area_sidebar').hide();
        $('.area_popup').hide();
        $('body').css('overflow', '');
    });
});

function slider_control() {
    $('#main .type_featured .slide_zone').each(function (i) {
        var id = 'featured_slide' + i;
        $(this).closest('.type_featured').attr('id', id);

        $(this).slick({
            arrows: true,
            dots: true,
            infinite: true,
            speed: 500,
            fade: true,
            appendArrows: $('#' + id + ' .box_arrow'),
            appendDots: $('#' + id + ' .inner_main_slide'),
            prevArrow: $('#' + id + ' .box_arrow .btn_prev'),
            nextArrow: $('#' + id + ' .box_arrow .btn_next'),
            dotsClass: 'slide_page slick-dots thema_apply',
            customPaging: function (slider, i) {
                return $('<button type="button" class="ico_circle"/>').text(i + 1);
            },
            cssEase: 'linear',
            responsive: [{
                breakpoint: 1439,
                settings: {
                    fade: false,
                },
            }],
        });
    });
}

function display_control() {
    var $location = $(location),
        pathname = $location.attr('pathname'),
        href = $location.attr('href'),
        parts = pathname.split('/');

    // 검색어 삭제
    $('.btn_search_del').click(function () {
        $('.inp_search').val('');
    });

    // 박스 헤더
    if ($('#main .area_cover').children(':first-child').hasClass('type_featured')) {
        $('#wrap').addClass('white');
    } else if ($('#main .area_cover').length > 0) {
        $('#main .area_cover').addClass('cover_margin');
    }

    /* 검색 리스크가 있을 경우 처리 */
    if ($('.category_search_list').length != false) {
        /* 컨텐츠 출력 영역 숨김 - 목록 표현을 검색 리스트로 대체 */
        $('.category_index_list').hide();

        /* 검색 리스트 처리 - 글 목록에서 썸네일, 카테고리 정보 참조 */
        $('.category_search_list .item_category').each(function (i) {
            var href = $(this).find('.link_category').attr('href'),
                $category_index_item = $('.category_index_list').find('[href="' + href + '"]'),
                thumbnail_full_path = $category_index_item.find('.item-thumbnail').css('background-image'),
                thumbnail_path = window.TistoryBlog.url + pathname;
            if (thumbnail_full_path != undefined) {
                thumbnail_path = thumbnail_full_path.replace(/^url\(['"](.+)['"]\)/, '$1');
            }
            if (thumbnail_path) {
                $(this).find('.link_category').data('thumbnail', thumbnail_path).css({
                    'background-image': 'url(' + thumbnail_path + ')',
                });
                $(this).find('.item-thumbnail').data('thumbnail', thumbnail_path).css({
                    'background-image': 'url(' + thumbnail_path + ')',
                });
            } else {
                $(this).find('.item-thumbnail').addClass('no_img');
            }

            $(this).find('.summary').text($category_index_item.find('.summary').text());
        });
    }

    // 리스트 관련해서 섬네일 없는 경우 no-img class 추가
    $('.item-thumbnail').each(function (i) {
        var $o = $(this),
            thumbnail_path = $o.css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
            base_path = window.TistoryBlog.url + pathname;

        if (thumbnail_path == base_path || thumbnail_path == href) {
            $o.addClass('no-img');
        }
    });
    $('.category_search_list .item_category').each(function (i) {
        var $o = $(this),
            thumbnail_path = $o.css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
            base_path = window.TistoryBlog.url + pathname;
        if (thumbnail_path == base_path) {
            $o.addClass('no-img');
        }
    });
    $('.category_search_list .link_category').each(function (i) {
        var $o = $(this),
            thumbnail_path = $o.css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
            base_path = window.TistoryBlog.url + pathname;
        if (thumbnail_path == base_path) {
            $o.addClass('no-img');
        }
    });

    // 글 출력이 있는 경우
    if ($('.area_view').length != false) {
        var seoImage = $('meta[property="og:image"]').attr('content');
        if (seoImage != undefined && seoImage != false) {
            $('.area_view .article_header .inner_header').css({
                'background-image': 'url(' + seoImage + ')',
            });
            $('.area_view .article_header').addClass('type_article_header_cover');

        } else {
            $('.area_view .article_header').addClass('type_article_header_common');
        }
        if ($('#main > .area_cover:first-child > .type_featured:first-child, .type_article_header_cover').length) {
            $('#wrap').addClass('white');
        }
    }

    // 로그인, 로그아웃 버튼 처리
    if (window.T.config.USER.name) {
        $('.btn-for-user').show();
    } else {
        $('.btn-for-guest').show();
    }

    $('.btn-for-guest [data-action="login"]').click(function () {
        document.location.href = 'https://www.tistory.com/auth/login?redirectUrl=' + encodeURIComponent(window.TistoryBlog.url);
    });
    $('.btn-for-user [data-action="logout"]').click(function () {
        document.location.href = 'https://www.tistory.com/auth/logout?redirectUrl=' + encodeURIComponent(window.TistoryBlog.url);
    });
}
<commit_msg>Date formatting in JS<commit_after>$(function () {

    display_control();
    slider_control();

    $('body').bind('click', function (e) {
        var $target = $(e.target);
        if ($target.closest('.btn_menu').length > 0) {
            $('.area_sidebar').show();
            $('.area_popup').hide();
            $('body').css('overflow', 'hidden');
        } else if ($target.closest('.btn_search').length > 0) {
            $('.area_sidebar').hide();
            $('.area_popup').show();
            $('body').css('overflow', 'hidden');
        } else if ($target.closest('.inner_sidebar').length == 0 && $target.closest('.area_popup').length == 0) {
            $('.area_sidebar').hide();
            $('.area_popup').hide();
            $('body').css('overflow', '');
        }
    });

    $('.btn_close').on('click', function () {
        $('.area_sidebar').hide();
        $('.area_popup').hide();
        $('body').css('overflow', '');
    });
});

function slider_control() {
    $('#main .type_featured .slide_zone').each(function (i) {
        var id = 'featured_slide' + i;
        $(this).closest('.type_featured').attr('id', id);

        $(this).slick({
            arrows: true,
            dots: true,
            infinite: true,
            speed: 500,
            fade: true,
            appendArrows: $('#' + id + ' .box_arrow'),
            appendDots: $('#' + id + ' .inner_main_slide'),
            prevArrow: $('#' + id + ' .box_arrow .btn_prev'),
            nextArrow: $('#' + id + ' .box_arrow .btn_next'),
            dotsClass: 'slide_page slick-dots thema_apply',
            customPaging: function (slider, i) {
                return $('<button type="button" class="ico_circle"/>').text(i + 1);
            },
            cssEase: 'linear',
            responsive: [{
                breakpoint: 1439,
                settings: {
                    fade: false,
                },
            }],
        });
    });
}

function display_control() {
    var $location = $(location),
        pathname = $location.attr('pathname'),
        href = $location.attr('href'),
        parts = pathname.split('/');

    // 검색어 삭제
    $('.btn_search_del').click(function () {
        $('.inp_search').val('');
    });

    // 박스 헤더
    if ($('#main .area_cover').children(':first-child').hasClass('type_featured')) {
        $('#wrap').addClass('white');
    } else if ($('#main .area_cover').length > 0) {
        $('#main .area_cover').addClass('cover_margin');
    }

    /* 검색 리스크가 있을 경우 처리 */
    if ($('.category_search_list').length != false) {
        /* 컨텐츠 출력 영역 숨김 - 목록 표현을 검색 리스트로 대체 */
        $('.category_index_list').hide();

        /* 검색 리스트 처리 - 글 목록에서 썸네일, 카테고리 정보 참조 */
        $('.category_search_list .item_category').each(function (i) {
            var href = $(this).find('.link_category').attr('href'),
                $category_index_item = $('.category_index_list').find('[href="' + href + '"]'),
                thumbnail_full_path = $category_index_item.find('.item-thumbnail').css('background-image'),
                thumbnail_path = window.TistoryBlog.url + pathname;
            if (thumbnail_full_path != undefined) {
                thumbnail_path = thumbnail_full_path.replace(/^url\(['"](.+)['"]\)/, '$1');
            }
            if (thumbnail_path) {
                $(this).find('.link_category').data('thumbnail', thumbnail_path).css({
                    'background-image': 'url(' + thumbnail_path + ')',
                });
                $(this).find('.item-thumbnail').data('thumbnail', thumbnail_path).css({
                    'background-image': 'url(' + thumbnail_path + ')',
                });
            } else {
                $(this).find('.item-thumbnail').addClass('no_img');
            }

            $(this).find('.summary').text($category_index_item.find('.summary').text());
        });
    }

    // 리스트 관련해서 섬네일 없는 경우 no-img class 추가
    $('.item-thumbnail').each(function (i) {
        var $o = $(this),
            thumbnail_path = $o.css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
            base_path = window.TistoryBlog.url + pathname;

        if (thumbnail_path == base_path || thumbnail_path == href) {
            $o.addClass('no-img');
        }
    });
    $('.category_search_list .item_category').each(function (i) {
        var $o = $(this),
            thumbnail_path = $o.css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
            base_path = window.TistoryBlog.url + pathname;
        if (thumbnail_path == base_path) {
            $o.addClass('no-img');
        }
    });
    $('.category_search_list .link_category').each(function (i) {
        var $o = $(this),
            thumbnail_path = $o.css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
            base_path = window.TistoryBlog.url + pathname;
        if (thumbnail_path == base_path) {
            $o.addClass('no-img');
        }
    });

    // 글 출력이 있는 경우
    if ($('.area_view').length != false) {
        var seoImage = $('meta[property="og:image"]').attr('content');
        if (seoImage != undefined && seoImage != false) {
            $('.area_view .article_header .inner_header').css({
                'background-image': 'url(' + seoImage + ')',
            });
            $('.area_view .article_header').addClass('type_article_header_cover');

        } else {
            $('.area_view .article_header').addClass('type_article_header_common');
        }
        if ($('#main > .area_cover:first-child > .type_featured:first-child, .type_article_header_cover').length) {
            $('#wrap').addClass('white');
        }
    }

    // 로그인, 로그아웃 버튼 처리
    if (window.T.config.USER.name) {
        $('.btn-for-user').show();
    } else {
        $('.btn-for-guest').show();
    }

    $('.btn-for-guest [data-action="login"]').click(function () {
        document.location.href = 'https://www.tistory.com/auth/login?redirectUrl=' + encodeURIComponent(window.TistoryBlog.url);
    });
    $('.btn-for-user [data-action="logout"]').click(function () {
        document.location.href = 'https://www.tistory.com/auth/logout?redirectUrl=' + encodeURIComponent(window.TistoryBlog.url);
    });

    // Transform date format into human format
    $('.article_header.type_article_header_cover .date').each(function () {
        const text = this.textContent;
        const m = text.match(/(\d{4})\.(\d{2})\.(\d{2})/);
        if (m) {
            const mapping = {
                '01': 'January',
                '02': 'February',
                '03': 'March',
                '04': 'April',
                '05': 'May',
                '06': 'June',
                '07': 'July',
                '08': 'August',
                '09': 'September',
                '10': 'October',
                '11': 'November',
                '12': 'December',
            }

            const newDate = m[1] + ' ' + mapping[m[2]] + ' ' + m[3];
            this.textContent = newDate;
        }
    });
}
<|endoftext|>