<commit_before>/* ShuffleManager
 *
 * Manages navigation throughout a list which is:
 * - Sourced from another provided list
 * - In random order (except to avoid consecutive duplicates)
 * - Extended endlessly on-the-fly, as needed
 * - Able to have future history overwritten by non-random choices
 * - Able to swap source lists and maintain shuffle order for common members
 */

class ShuffleManager {
  constructor (list, options = {}) {
    this.list = list;
    this.backStack = [];
    this.forwardStack = [];
    this.currentItem = null;

    this.setOptions(options);
  }

  findNextItem () {
    if (!this.list.length) {
      return null;
    }
    for (let i = 1; i <= this.forwardStack.length; i++) {
      if (this.list.indexOf(this.forwardStack[this.forwardStack.length - i]) !== -1) {
        goForward(this, i);
        return this.currentItem;
      }
    }
    if (allItemsMatch(this.list, this.currentItem)) {
      // we can serve this as our "next" item but we
      // won't modify our history since it's the same.
      return this.currentItem;
    }
    let nextItem;
    do {
        nextItem = this.list[Math.floor(Math.random() * this.list.length)];
    } while (this.currentItem === nextItem || nextItem === undefined);
    // if we're skipping items that aren't in our current list we may
    // have some items in our forwardStack - make sure we move to the front.
    goForward(this, this.forwardStack.length);
    if (this.currentItem !== undefined) {
      this.backStack.push(this.currentItem);
    }
    this.currentItem = nextItem;
    return this.currentItem;
  }

  findPreviousItem () {
    if (!this.list.length) {
      return null;
    }
    for (let i = 1; i <= this.backStack.length; i++) {
      if (this.list.indexOf(this.backStack[this.backStack.length - i]) !== -1) {
        goBack(this, i);
        return this.currentItem;
      }
    }
    if (!this.allowBackShuffle)
      return null;
    }
    if (allItemsMatch(this.list, this.currentItem)) {
      // we can serve this as our "next" item but we
      // won't modify our history since it's the same.
      return this.currentItem;
    }
    let previousItem;
    do {
        previousItem = this.list[Math.floor(Math.random() * this.list.length)];
    } while (this.currentItem === previousItem || previousItem === undefined);
    // if we're skipping items that aren't in our current list we may
    // have some items in our backStack - make sure we move to the back.
    goBack(this, this.backStack.length);
    if (this.currentItem !== undefined) {
      this.forwardStack.push(this.currentItem);
    }
    this.currentItem = previousItem;
    return this.currentItem;
  }

  pickNextItem (index) {
    if (this.list[index] === undefined) {
      return null;
    }
    if (this.currentItem !== undefined) {
      this.backStack.push(this.currentItem);
    }
    this.forwardStack.length = 0;
    this.currentItem = this.list[index];
    return this.currentItem;
  }

  setList (list) {
    this.list = list;
  }

  setOptions (options) {
    this.allowBackShuffle = Boolean(options.allowBackShuffle);
  }

  clear () {
    this.backStack.length = 0;
    this.forwardStack.length = 0;
    this.currentItem = null;
  }
}

function allItemsMatch (list, item) {
  if (!list.length) {
    return false;
  }
  for (let i = 0; i < list.length; i++) {
    if (item !== list[i]) {
      return false;
    }
  }
  return true;
}

function goForward (sm, n) {
  for (let i = 0; i < n; i++) {
    if (!sm.forwardStack.length) {
      sm.goBack(i); // rollback before erroring
      throw `Could not go forward ${n} times!`;
    }
    sm.backStack.push(sm.currentItem);
    sm.currentItem = sm.forwardStack.pop();
  }
}

function goBack (sm, n) {
  for (let i = 0; i < n; i++) {
    if (!sm.backStack.length) {
      sm.goForward(i); // rollback before erroring
      throw `Could not go back ${n} times!`;
    }
    sm.forwardStack.push(sm.currentItem);
    sm.currentItem = sm.backStack.pop();
  }
}

module.exports = ShuffleManager;
<commit_msg>When no item is available, ShuffleManager methods return undefined, not null.<commit_after>/* ShuffleManager
 *
 * Manages navigation throughout a list which is:
 * - Sourced from another provided list
 * - In random order (except to avoid consecutive duplicates)
 * - Extended endlessly on-the-fly, as needed
 * - Able to have future history overwritten by non-random choices
 * - Able to swap source lists and maintain shuffle order for common members
 */

class ShuffleManager {
  constructor (list, options = {}) {
    this.list = list;
    this.backStack = [];
    this.forwardStack = [];
    this.currentItem = null;

    this.setOptions(options);
  }

  findNextItem () {
    if (!this.list.length) {
      return undefined;
    }
    for (let i = 1; i <= this.forwardStack.length; i++) {
      if (this.list.indexOf(this.forwardStack[this.forwardStack.length - i]) !== -1) {
        goForward(this, i);
        return this.currentItem;
      }
    }
    if (allItemsMatch(this.list, this.currentItem)) {
      // we can serve this as our "next" item but we
      // won't modify our history since it's the same.
      return this.currentItem;
    }
    let nextItem;
    do {
        nextItem = this.list[Math.floor(Math.random() * this.list.length)];
    } while (this.currentItem === nextItem || nextItem === undefined);
    // if we're skipping items that aren't in our current list we may
    // have some items in our forwardStack - make sure we move to the front.
    goForward(this, this.forwardStack.length);
    if (this.currentItem !== undefined) {
      this.backStack.push(this.currentItem);
    }
    this.currentItem = nextItem;
    return this.currentItem;
  }

  findPreviousItem () {
    if (!this.list.length) {
      return undefined;
    }
    for (let i = 1; i <= this.backStack.length; i++) {
      if (this.list.indexOf(this.backStack[this.backStack.length - i]) !== -1) {
        goBack(this, i);
        return this.currentItem;
      }
    }
    if (!this.allowBackShuffle)
      return undefined;
    }
    if (allItemsMatch(this.list, this.currentItem)) {
      // we can serve this as our "next" item but we
      // won't modify our history since it's the same.
      return this.currentItem;
    }
    let previousItem;
    do {
        previousItem = this.list[Math.floor(Math.random() * this.list.length)];
    } while (this.currentItem === previousItem || previousItem === undefined);
    // if we're skipping items that aren't in our current list we may
    // have some items in our backStack - make sure we move to the back.
    goBack(this, this.backStack.length);
    if (this.currentItem !== undefined) {
      this.forwardStack.push(this.currentItem);
    }
    this.currentItem = previousItem;
    return this.currentItem;
  }

  pickNextItem (index) {
    if (this.list[index] === undefined) {
      return undefined;
    }
    if (this.currentItem !== undefined) {
      this.backStack.push(this.currentItem);
    }
    this.forwardStack.length = 0;
    this.currentItem = this.list[index];
    return this.currentItem;
  }

  setList (list) {
    this.list = list;
  }

  setOptions (options) {
    this.allowBackShuffle = Boolean(options.allowBackShuffle);
  }

  clear () {
    this.backStack.length = 0;
    this.forwardStack.length = 0;
    this.currentItem = null;
  }
}

function allItemsMatch (list, item) {
  if (!list.length) {
    return false;
  }
  for (let i = 0; i < list.length; i++) {
    if (item !== list[i]) {
      return false;
    }
  }
  return true;
}

function goForward (sm, n) {
  for (let i = 0; i < n; i++) {
    if (!sm.forwardStack.length) {
      sm.goBack(i); // rollback before erroring
      throw `Could not go forward ${n} times!`;
    }
    sm.backStack.push(sm.currentItem);
    sm.currentItem = sm.forwardStack.pop();
  }
}

function goBack (sm, n) {
  for (let i = 0; i < n; i++) {
    if (!sm.backStack.length) {
      sm.goForward(i); // rollback before erroring
      throw `Could not go back ${n} times!`;
    }
    sm.forwardStack.push(sm.currentItem);
    sm.currentItem = sm.backStack.pop();
  }
}

module.exports = ShuffleManager;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var express = require('express'),
    http = require('http'),
	morgan = require('morgan'),
	bodyParser = require('body-parser'),
	session = require('express-session'),
	compress = require('compression'),
	methodOverride = require('method-override'),
	cookieParser = require('cookie-parser'),
	helmet = require('helmet'),
	passport = require('passport'),
	mongoStore = require('connect-mongo')({
		session: session
	}),
	flash = require('connect-flash'),
	config = require('./config'),
	consolidate = require('consolidate'),
	path = require('path');

module.exports = function(db) {
	// Initialize express app
	var app = express();
    var server = http.createServer(app);
    var io = require('socket.io').listen(server);

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + ':// ' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded());
	app.use(bodyParser.json());
	app.use(methodOverride());

	// Enable jsonp
	app.enable('jsonp callback');

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		secret: config.sessionSecret,
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.iexss());
	app.use(helmet.contentTypeOptions());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});
// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Pass to next layer of middleware
    next();
});

    io.on('connection', function(socket){
        socket.broadcast.emit('user connected');

         socket.on('send msg', function(msg){
            console.log(msg);
         });
    });

	return server;
};<commit_msg>change express remove socket<commit_after>'use strict';

/**
 * Module dependencies.
 */
var express = require('express'),
    http = require('http'),
	morgan = require('morgan'),
	bodyParser = require('body-parser'),
	session = require('express-session'),
	compress = require('compression'),
	methodOverride = require('method-override'),
	cookieParser = require('cookie-parser'),
	helmet = require('helmet'),
	passport = require('passport'),
	mongoStore = require('connect-mongo')({
		session: session
	}),
	flash = require('connect-flash'),
	config = require('./config'),
	consolidate = require('consolidate'),
	path = require('path');

module.exports = function(db) {
	// Initialize express app
	var app = express();
    var server = http.createServer(app);
    var io = require('socket.io').listen(server);

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + ':// ' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded());
	app.use(bodyParser.json());
	app.use(methodOverride());

	// Enable jsonp
	app.enable('jsonp callback');

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		secret: config.sessionSecret,
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection
		})
	}));

	// use passport session
	app.use(passport.initialize());
	app.use(passport.session());

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.iexss());
	app.use(helmet.contentTypeOptions());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});
// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Pass to next layer of middleware
    next();
});

//    io.on('connection', function(socket){
//        socket.broadcast.emit('user connected');
//
//         socket.on('send msg', function(msg){
//            console.log(msg);
//         });
//    });

	return app;
};<|endoftext|>


<commit_before>define('logger', function() {
    function logger(name, color) {
        return function() {
            if (!logger.enabled) {
                return;
            }
            var args = Array.prototype.slice.call(arguments);
            var tabs = '';
            (args[0] + '').replace(/^\t+/, function(m) {
                tabs = m;
                return '';
            });
            args[0] = "%c" + tabs + name + "::" + args[0];
            args.splice(1, 0, "color:" + color +";");
            console.log.apply(console, args);
        };
    }
    logger.enabled = true;
    return logger;
});<commit_msg>optimize logger<commit_after>define('logger', function() {
    function logger(name, color) {
        return function() {
            if (!logger.enabled) {
                return;
            }
            var args = Array.prototype.slice.call(arguments);
            var tabs = '';
            var str = args[0] + '';
            str.replace(/^\t+/, function(m) {
                tabs = m;
                return '';
            });
            args[0] = "%c" + tabs + name + "::" + str;
            args.splice(1, 0, "color:" + color +";");
            console.log.apply(console, args);
        };
    }
    logger.enabled = true;
    return logger;
});<|endoftext|>


<commit_before>/**
 * Configure advanced options for the Express server inside of Sails.
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#documentation
 */
module.exports.express = {

  // Completely override Express middleware loading.
  // If you only want to override the bodyParser, cookieParser
  // or methodOverride middleware, see the appropriate keys below.
  // If you only want to override one or more of the default middleware,
  // but keep the order the same, use the `middleware` key.
  // See the `http` hook in the Sails core for the default loading order.
  //
  // loadMiddleware: function( app, defaultMiddleware, sails ) { ... }

  // Override one or more of the default middleware (besides bodyParser, cookieParser)
  //
  // middleware: {
  //    session: false, // turn off session completely for HTTP requests
  //    404: function ( req, res, next ) { ... your custom 404 middleware ... }
  // }

  // The middleware function used for parsing the HTTP request body.
  // (this most commonly comes up in the context of file uploads)
  //
  // Defaults to a slightly modified version of `express.bodyParser`, i.e.:
  // If the Connect `bodyParser` doesn't understand the HTTP body request
  // data, Sails runs it again with an artificial header, forcing it to try
  // and parse the request body as JSON.  (this allows JSON to be used as your
  // request data without the need to specify a 'Content-type: application/json'
  // header)
  //
  // If you want to change any of that, you can override the bodyParser with
  // your own custom middleware:
  // bodyParser: function customBodyParser (options) { ... return function(req, res, next) {...}; }
  //
  // Or you can always revert back to the vanilla parser built-in to Connect/Express:
  // bodyParser: require('express').bodyParser,
  //
  // Or to disable the body parser completely:
  // bodyParser: false,
  // (useful for streaming file uploads-- to disk or S3 or wherever you like)
  //
  // WARNING
  // ======================================================================
  // Multipart bodyParser (i.e. express.multipart() ) will be removed
  // in Connect 3 / Express 4.
  // [Why?](https://github.com/senchalabs/connect/wiki/Connect-3.0)
  //
  // The multipart component of this parser will be replaced
  // in a subsequent version of Sails (after v0.10, probably v0.11) with:
  // [file-parser](https://github.com/balderdashy/file-parser)
  // (or something comparable)
  //
  // If you understand the risks of using the multipart bodyParser,
  // and would like to disable the warning log messages, uncomment:
  // silenceMultipartWarning: true,
  // ======================================================================

  // Cookie parser middleware to use
  //			(or false to disable)
  //
  // Defaults to `express.cookieParser`
  //
  // Example override:
  // cookieParser: (function customMethodOverride (req, res, next) {})(),

  // HTTP method override middleware
  //			(or false to disable)
  //
  // This option allows artificial query params to be passed to trick
  // Sails into thinking a different HTTP verb was used.
  // Useful when supporting an API for user-agents which don't allow
  // PUT or DELETE requests
  //
  // Defaults to `express.methodOverride`
  //
  // Example override:
  // methodOverride: (function customMethodOverride (req, res, next) {})()
};

/**
 * HTTP Flat-File Cache
 *
 * These settings are for Express' static middleware- the part that serves
 * flat-files like images, css, client-side templates, favicons, etc.
 *
 * In Sails, this affects the files in your app's `assets` directory.
 * By default, Sails uses your project's Gruntfile to compile/copy those
 * assets to `.tmp/public`, where they're accessible to Express.
 *
 * The HTTP static cache is only active in a 'production' environment,
 * since that's the only time Express will cache flat-files.
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#documentation
 */
module.exports.cache = {

  // The number of seconds to cache files being served from disk
  // (only works in production mode)
  maxAge: 31557600000
};
<commit_msg>Silence the warning about the multipart bodyParser<commit_after>/**
 * Configure advanced options for the Express server inside of Sails.
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#documentation
 */
module.exports.express = {

  // Completely override Express middleware loading.
  // If you only want to override the bodyParser, cookieParser
  // or methodOverride middleware, see the appropriate keys below.
  // If you only want to override one or more of the default middleware,
  // but keep the order the same, use the `middleware` key.
  // See the `http` hook in the Sails core for the default loading order.
  //
  // loadMiddleware: function( app, defaultMiddleware, sails ) { ... }

  // Override one or more of the default middleware (besides bodyParser, cookieParser)
  //
  // middleware: {
  //    session: false, // turn off session completely for HTTP requests
  //    404: function ( req, res, next ) { ... your custom 404 middleware ... }
  // }

  // The middleware function used for parsing the HTTP request body.
  // (this most commonly comes up in the context of file uploads)
  //
  // Defaults to a slightly modified version of `express.bodyParser`, i.e.:
  // If the Connect `bodyParser` doesn't understand the HTTP body request
  // data, Sails runs it again with an artificial header, forcing it to try
  // and parse the request body as JSON.  (this allows JSON to be used as your
  // request data without the need to specify a 'Content-type: application/json'
  // header)
  //
  // If you want to change any of that, you can override the bodyParser with
  // your own custom middleware:
  // bodyParser: function customBodyParser (options) { ... return function(req, res, next) {...}; }
  //
  // Or you can always revert back to the vanilla parser built-in to Connect/Express:
  // bodyParser: require('express').bodyParser,
  //
  // Or to disable the body parser completely:
  // bodyParser: false,
  // (useful for streaming file uploads-- to disk or S3 or wherever you like)
  //
  // WARNING
  // ======================================================================
  // Multipart bodyParser (i.e. express.multipart() ) will be removed
  // in Connect 3 / Express 4.
  // [Why?](https://github.com/senchalabs/connect/wiki/Connect-3.0)
  //
  // The multipart component of this parser will be replaced
  // in a subsequent version of Sails (after v0.10, probably v0.11) with:
  // [file-parser](https://github.com/balderdashy/file-parser)
  // (or something comparable)
  //
  // If you understand the risks of using the multipart bodyParser,
  // and would like to disable the warning log messages, uncomment:
  silenceMultipartWarning: true
  // ======================================================================

  // Cookie parser middleware to use
  //			(or false to disable)
  //
  // Defaults to `express.cookieParser`
  //
  // Example override:
  // cookieParser: (function customMethodOverride (req, res, next) {})(),

  // HTTP method override middleware
  //			(or false to disable)
  //
  // This option allows artificial query params to be passed to trick
  // Sails into thinking a different HTTP verb was used.
  // Useful when supporting an API for user-agents which don't allow
  // PUT or DELETE requests
  //
  // Defaults to `express.methodOverride`
  //
  // Example override:
  // methodOverride: (function customMethodOverride (req, res, next) {})()
};

/**
 * HTTP Flat-File Cache
 *
 * These settings are for Express' static middleware- the part that serves
 * flat-files like images, css, client-side templates, favicons, etc.
 *
 * In Sails, this affects the files in your app's `assets` directory.
 * By default, Sails uses your project's Gruntfile to compile/copy those
 * assets to `.tmp/public`, where they're accessible to Express.
 *
 * The HTTP static cache is only active in a 'production' environment,
 * since that's the only time Express will cache flat-files.
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#documentation
 */
module.exports.cache = {

  // The number of seconds to cache files being served from disk
  // (only works in production mode)
  maxAge: 31557600000
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Central place to detect feature support for the current platform,
// expand as needed.

const FEATURES = {
  trust_on_first_use : () => {
    try {
      // This is insane. We are verifying that we have a version of getPeerCertificate
      // that supports reading the whole certificate, eg this commit:
      // https://github.com/nodejs/node/commit/345c40b6
      let desc = require('tls').TLSSocket.prototype.getPeerCertificate;
      return desc.length() >= 1;
    } catch( e ) {
      return false;
    }
  }
};

function hasFeature( name ) {
  return FEATURES[name] && FEATURES[name]();
}

export default hasFeature;
<commit_msg>FIxed bug when accessing length<commit_after>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Central place to detect feature support for the current platform,
// expand as needed.

const FEATURES = {
  trust_on_first_use : () => {
    try {
      // This is insane. We are verifying that we have a version of getPeerCertificate
      // that supports reading the whole certificate, eg this commit:
      // https://github.com/nodejs/node/commit/345c40b6
      let desc = require('tls').TLSSocket.prototype.getPeerCertificate;
      return desc.length >= 1;
    } catch( e ) {
      return false;
    }
  }
};

function hasFeature( name ) {
  return FEATURES[name] && FEATURES[name]();
}

export default hasFeature;
<|endoftext|>


<commit_before>var constants = require("./constants");
var Class = require(__basedir + "/utilities/class");
var BaseGameObject = require("./shared/baseGameObject");

/**
 * A collection of static functions that deals with transforming game states to and from serializable objects when communicating between client <--> sever
 */
var serializer = {
    defaultBoolean: function(b) {
        switch(typeof(b)) {
            case "string":
                return b === "true";
            case "number":
                return b !== 0;
            default:
                return !!b;
        }
    },

    defaultNumber: function(n) {
        return Number(n) || 0.0;
    },

    defaultInteger: function(i) {
        return parseInt(i) || 0;
    },

    defaultString: function(s) {
        return (s === undefined ? "" : String(s));
    },

    defaultArray: function(a) {
        return (Array.isArray(a) ? a : []);
    },

    defaultObject: function(o) {
        return (serializer.isObject(o) ? o : {});
    },

    defaultGameObject: function(o) {
        return (Class.isInstance(o, BaseGameObject) ? o : null);
    },

    defaultType: function(typeName, o) {
        return serializer[typeName.toLowerCase().upperFirst()](o);
    },

    isEmpty: function(obj){
        return (Object.getOwnPropertyNames(obj).length === 0);
    },

    isEmptyExceptFor: function(obj, key) {
        return (serializer.isObject(obj) && Object.getOwnPropertyNames(obj).length === 1 && obj[key] !== undefined);
    },

    isGameObjectReference: function(obj) {
        return serializer.isEmptyExceptFor(obj, 'id');
    },

    isObject: function(obj) {
        return (typeof(obj) === 'object' && obj !== null);
    },

    isSerializable: function(obj, key) {
        return serializer.isObject(obj) && (obj.hasOwnProperty(key) || (obj._serializableKeys && obj._serializableKeys[key])) && !String(key).startsWith("_") && (obj._serializableKeys === undefined || obj._serializableKeys[key]);
    },

    isDeltaArray: function(a) {
        return (serializer.isObject(a) && a[constants.shared.DELTA_LIST_LENGTH] !== undefined);
    },

    /**
     * serializes something about a game so it is safe to send over a socket. This is required to avoid cycles and send lists correctly.
     *
     * @param {*} state - The variable you want to serialize. Anything in the game should be serializeable, numberss, strings, BaseGameObjects, dicts, lists, nulls, etc.
     * @param {BaseGame} game - the game you are serializing things for
     * @returns {*} state, serialized. It will never be the same Object if it is an Object ({} or [])
     */
    serialize: function(state, game) {
        if(!serializer.isObject(state)) {
            return state;
        }
        else if(Class.isInstance(state, BaseGameObject)) { // no need to serialize this whole thing
            return { id: state.id };
        }

        game = game || state;
        var serialized = {};

        if(state.isArray) { // record the length, we never send arrays in serialized states because you can't tell when they change in size without sending all the elements
            serialized[constants.shared.DELTA_LIST_LENGTH] = state.length;
        }

        for(var key in state) {
            if(serializer.isSerializable(state, key)) {
                var value = state[key];
                if(serializer.isObject(value)) {
                    serialized[key] = serializer.serialize(value, game);
                }
                else {
                    serialized[key] = value;
                }
            }
        }
        return serialized;
    },

    deserialize: function(data, game, dataTypeConverter) {
        if(serializer.isObject(data) && game) {
            var result = data.isArray ? [] : {};

            for(var key in data) {
                var value = data[key];
                if(typeof(value) == "object") {
                    if(serializer.isGameObjectReference(value)) { // it's a tracked game object
                        result[key] = game.getGameObject(value.id);
                    }
                    else {
                        result[key] = serializer.deserialize(value, game);
                    }
                }
                else {
                    result[key] = value;
                }
            }

            return result;
        }

        if(dataTypeConverter) {
            data = dataTypeConverter(data);
        }

        return data;
    },
}

module.exports = serializer;
<commit_msg>"false" will be treated as false for booleans<commit_after>var constants = require("./constants");
var Class = require(__basedir + "/utilities/class");
var BaseGameObject = require("./shared/baseGameObject");

/**
 * A collection of static functions that deals with transforming game states to and from serializable objects when communicating between client <--> sever
 */
var serializer = {
    defaultBoolean: function(b) {
        switch(typeof(b)) {
            case "string":
                var lowered = b.toLower();
                if(lowered === "true") { // they sent some form of "true" as a string, so make it the boolean true
                    return true;
                }
                else if(lowered === "false") { // they sent some form of "false" as a string, so make it the boolean false
                    return false;
                }
                return Boolean(b);
            case "number":
                return b !== 0;
            default:
                return !!b;
        }
    },

    defaultNumber: function(n) {
        return Number(n) || 0.0;
    },

    defaultInteger: function(i) {
        return parseInt(i) || 0;
    },

    defaultString: function(s) {
        return (s === undefined ? "" : String(s));
    },

    defaultArray: function(a) {
        return (Array.isArray(a) ? a : []);
    },

    defaultObject: function(o) {
        return (serializer.isObject(o) ? o : {});
    },

    defaultGameObject: function(o) {
        return (Class.isInstance(o, BaseGameObject) ? o : null);
    },

    defaultType: function(typeName, o) {
        return serializer[typeName.toLowerCase().upperFirst()](o);
    },

    isEmpty: function(obj){
        return (Object.getOwnPropertyNames(obj).length === 0);
    },

    isEmptyExceptFor: function(obj, key) {
        return (serializer.isObject(obj) && Object.getOwnPropertyNames(obj).length === 1 && obj[key] !== undefined);
    },

    isGameObjectReference: function(obj) {
        return serializer.isEmptyExceptFor(obj, 'id');
    },

    isObject: function(obj) {
        return (typeof(obj) === 'object' && obj !== null);
    },

    isSerializable: function(obj, key) {
        return serializer.isObject(obj) && (obj.hasOwnProperty(key) || (obj._serializableKeys && obj._serializableKeys[key])) && !String(key).startsWith("_") && (obj._serializableKeys === undefined || obj._serializableKeys[key]);
    },

    isDeltaArray: function(a) {
        return (serializer.isObject(a) && a[constants.shared.DELTA_LIST_LENGTH] !== undefined);
    },

    /**
     * serializes something about a game so it is safe to send over a socket. This is required to avoid cycles and send lists correctly.
     *
     * @param {*} state - The variable you want to serialize. Anything in the game should be serializeable, numberss, strings, BaseGameObjects, dicts, lists, nulls, etc.
     * @param {BaseGame} game - the game you are serializing things for
     * @returns {*} state, serialized. It will never be the same Object if it is an Object ({} or [])
     */
    serialize: function(state, game) {
        if(!serializer.isObject(state)) {
            return state;
        }
        else if(Class.isInstance(state, BaseGameObject)) { // no need to serialize this whole thing
            return { id: state.id };
        }

        game = game || state;
        var serialized = {};

        if(state.isArray) { // record the length, we never send arrays in serialized states because you can't tell when they change in size without sending all the elements
            serialized[constants.shared.DELTA_LIST_LENGTH] = state.length;
        }

        for(var key in state) {
            if(serializer.isSerializable(state, key)) {
                var value = state[key];
                if(serializer.isObject(value)) {
                    serialized[key] = serializer.serialize(value, game);
                }
                else {
                    serialized[key] = value;
                }
            }
        }
        return serialized;
    },

    deserialize: function(data, game, dataTypeConverter) {
        if(serializer.isObject(data) && game) {
            var result = data.isArray ? [] : {};

            for(var key in data) {
                var value = data[key];
                if(typeof(value) == "object") {
                    if(serializer.isGameObjectReference(value)) { // it's a tracked game object
                        result[key] = game.getGameObject(value.id);
                    }
                    else {
                        result[key] = serializer.deserialize(value, game);
                    }
                }
                else {
                    result[key] = value;
                }
            }

            return result;
        }

        if(dataTypeConverter) {
            data = dataTypeConverter(data);
        }

        return data;
    },
}

module.exports = serializer;
<|endoftext|>


<commit_before>
// makeSimpleTagRegex MUST match text  surrounded by the provided open and close tags
// this text MAY span more than one line and include white space
// open and close tags MAY contain multiple characters and not be identical to each other
// Text surrounded by multiple instances of the same tag type MUST only match one copy of the tag
// eg text is here would only return text is here as a token
//
// regex based on https://stackoverflow.com/questions/11592033/regex-match-text-between-tags
// a simpler expression for matching single character delimters was originally used. See below
// new RegExp(`[${open}]([^${close}]+)[${close}]`, 'gi');
export function makeBlockRegex({ open, close = open }) {
  return new RegExp(`(\\${open})(?!\\${open})(.+?)(\\${close})`, 'gi');
}

/**
 * normally in a lex parser we would have clearly defined openening and closing symbols
 * since the source is plain english (not code) and we need to support
 * markdown style tag where opening and closing delimeters look exactly alike
 * eg *i am bold*
 * we use the regex to find the text with delimeters and determine the delimeter
 * characters locations from the match
*/
export default function factory(delimiters, name = 'DEFAULT') {
  return {
    pattern: makeBlockRegex(delimiters),
    tokenizer: function tokenizer(match) {
      return [
        {
          name,
          type: 'BLOCK_START',
          start: match.index,
          chars: match[1],
          delimiters
        },
        {
          name,
          start: match.index + match[1].length + match[2].length,
          type: 'BLOCK_END',
          chars: match[3],
          delimiters
        }
      ];
    }
  };
}
<commit_msg>fix bug in block delimiter parser<commit_after>// (\*)\**[^*]+\**(\*)
/**
 * Intended to produce a basic block patterns from simple characters
 * for example. if open and close are * then it will match *lorem ipsum*
 * In the event of multiple delimiters surounding text it will treat
 * the outer most delimiters as the token. The others will not be marked as
 * tokens and later treated as literals
 */
export function makeBlockRegex({ open, close = open }) {
  return new RegExp(`(\\${open})\\${open}*[^${open}]+\\${close}*(\\${close})`, 'g');
}

export default function factory(delimiters, name = 'DEFAULT', regex) {
  return {
    pattern: regex || makeBlockRegex(delimiters),
    tokenizer: function tokenizer(match) {
      return [
        {
          name,
          type: 'BLOCK_START',
          start: match.index,
          chars: match[1],
          delimiters
        },
        {
          name,
          start: match.index + match[0].length - match[2].length,
          type: 'BLOCK_END',
          chars: match[3],
          delimiters
        }
      ];
    }
  };
}
<|endoftext|>


<commit_before>$('document').ready(function(){
    $('#sidebar_kiri li').click(function(){
        $('#sidebar_kiri li').removeClass('aktif');
        $(this).addClass('aktif');
    });
    var elemen = "";
    var n = $('table')[0].getElementsByTagName('tr').length;
    $('button').click(function(){
        var p = Array(n);
        for(a = 0; a < n; a++){
            p[a] = $('table')[0].rows[a].cells[1].innerHTML;
            $('table')[0].rows[a].cells[1].innerHTML = "<input onkeyup='gantinilai()' class='atur-profil' type='text' placeholder='"+p[a]+"'/>";
        }
    });
    for(a = 0; a < n; a++){
        document.getElementsByClassName('atur-profil')[a]
    }
//        var up = Array(n);
//        var c = "";
//        for(a = 0; a<n; a++){
//            up[a] = $('table')[0].rows[a].cells[1].getElementsByTagName('input')[0].val();
//        }
//        for(a = 0; a<n; a++){
//            c += up[a];
//        }
//        $('#perbarui').val() = c;
});<commit_msg>update TAKHunter<commit_after>$('document').ready(function(){
    $('#sidebar_kiri li').click(function(){
        $('#sidebar_kiri li').removeClass('aktif');
        $(this).addClass('aktif');
    });
    var elemen = "";
    var n = $('table')[0].getElementsByTagName('tr').length;
    $('button').click(function(){
        var p = Array(n);
        for(a = 0; a < n; a++){
            p[a] = $('table')[0].rows[a].cells[1].innerHTML;
            $('table')[0].rows[a].cells[1].innerHTML = "<input onkeyup='gantinilai()' class='atur-profil' type='text' placeholder='"+p[a]+"'/>";
        }
    });
function gantinilai(){
    var n = $('table')[0].getElementsByTagName('tr').length;
    var profil = Array(n);
    document.getElementById('perbarui').value = "";
    for(a = 0; a < n; a++){
        profil[a] = document.getElementsByClassName('atur-profil')[a].value;
        document.getElementById('perbarui').value += profil[a];
    }
}<|endoftext|>


<commit_before>HTMLWidgets.widget({
    name: 'rcytoscapejs',
    type: 'output',

    initialize: function (el, width, height) {
        return {
            // TODO: add instance fields as required
        }
    },

    resize: function (el, width, height, instance) {
        if (instance.cy)
            instance.cy.resize();
    },

    renderValue: function (el, x, instance) {
        //console.log(x.nodeEntries);
        //console.log(x.edgeEntries);

        //var nodetest = JSON.parse(x.nodeEntries);
        //var edgetest = JSON.parse(x.edgeEntries);

        //console.log(nodetest);
        //console.log(edgetest);

        var defaults = ({
          zoomFactor: 0.05, // zoom factor per zoom tick
          zoomDelay: 45, // how many ms between zoom ticks
          minZoom: 0.1, // min zoom level
          maxZoom: 10, // max zoom level
          fitPadding: 50, // padding when fitting
          panSpeed: 10, // how many ms in between pan ticks
          panDistance: 10, // max pan distance per tick
          panDragAreaSize: 75, // the length of the pan drag box in which the vector for panning is calculated (bigger = finer control of pan speed and direction)
          panMinPercentSpeed: 0.25, // the slowest speed we can pan by (as a percent of panSpeed)
          panInactiveArea: 8, // radius of inactive area in pan drag box
          panIndicatorMinOpacity: 0.5, // min opacity of pan indicator (the draggable nib); scales from this to 1.0
          autodisableForMobile: true, // disable the panzoom completely for mobile (since we don't really need it with gestures like pinch to zoom)

          // icon class names
          sliderHandleIcon: 'fa fa-minus',
          zoomInIcon: 'fa fa-plus',
          zoomOutIcon: 'fa fa-minus',
          resetIcon: 'fa fa-expand'
        });

        var positionMap = {};

        //add position information to data for preset layout
        for (var i = 0; i < x.nodeEntries.length ; i++){
            var xPos = x.nodeEntries[i].data.x;
            var yPos = x.nodeEntries[i].data.y;
            positionMap[x.nodeEntries[i].data.id] = {'x':parseFloat(xPos), 'y':parseFloat(yPos)};
        }

        instance.cy = new cytoscape({
            container: el,
            style: cytoscape.stylesheet()
                .selector('node')
                .css({
                    'color': 'data(nodeLabelColor)',
                    'opacity': 'data(opacity)',
                    'content': 'data(name)',
                    'text-valign': 'center',
                    'shape': 'data(shape)',
                    'text-outline-color': 'data(color)',
                    'background-color': 'data(color)',
                    'width': 'data(width)',
                    'height': 'data(height)',
                    'weight': 'data(weight)',
                    'border-style': 'data(borderstyle)',
                    'border-color': 'data(bordercolor)',
                    'border-width': 'data(borderwidth)',
                    'border-opacity': 'data(borderopacity)',
                    'rank': 'data(rank)'
                })
                .selector('edge')
                .css({
                    'line-color': 'data(color)',
                    'source-arrow-color': 'data(color)',
                    'target-arrow-color': 'data(color)',
                    'source-arrow-shape': 'data(edgeSourceShape)',
                    'target-arrow-shape': 'data(edgeTargetShape)',
                    'width': 'data(width)',
                    'opacity': 'data(opacity)'
                })
                .selector(':selected')
                .css({
                    'background-color': '#000000',
                    'line-color': 'black',
                    'target-arrow-color': 'black',
                    'source-arrow-color': 'black'
                })
                .selector('.highlighted')
                .css({
                    'background-color': '#000000',
                    'line-color': '#000000',
                    'target-arrow-color': '#000000',
                    'transition-property': 'background-color, line-color, target-arrow-color',
                    'transition-duration': '0.5s'
                })
                .selector('.faded')
                .css({
                    'opacity': 0.25,
                    'text-opacity': 0
                }),

            elements: {
                nodes: x.nodeEntries,
                //nodes: [{ data: { id:'509209821', name:'509209821', color:'#888888', shape:'ellipse', href:''} }, { data: { id:'531376085', name:'531376085', color:'#888888', shape:'ellipse', href:''} }],
                edges: x.edgeEntries
                //edges: [{ data: { source:'509209821', target:'531376085', color:'#888888', edgeSourceShape:'none', edgeTargetShape:'triangle'} }]

            },
            layout: {
                name: x.layout,
                ungrabifyWhileSimulating: true,
                positions: positionMap
            },
            ready: function () {
                window.cy = this;

                if(x.showPanzoom) {
                  cy.panzoom(defaults);
                }

                cy.boxSelectionEnabled(true);
                cy.userZoomingEnabled(true);
                cy.on('tap', 'node', function (event) {
                    var nodeHighlighted = this.hasClass("highlighted");
                    console.log(nodeHighlighted);
                    var nodes = this.closedNeighborhood().connectedNodes();
                    //console.log(nodes);
                    console.log("A:" + el.id);
                    console.log("ID:" + this._private.data.id);
                    Shiny.onInputChange("clickedNode", this._private.data.id);
                    console.log("break");

                    if (nodes.length === 0) {
                        this.toggleClass("highlighted");
                    }

                    if (nodeHighlighted) {
                        for (var i = 0; i < nodes.length; i++) {
                            if (nodes[i].hasClass("highlighted")) {
                                nodes[i].toggleClass("highlighted");
                            }
                        }
                    } else {
                        for (var i = 0; i < nodes.length; i++) {
                            if (!nodes[i].hasClass("highlighted")) {
                                nodes[i].toggleClass("highlighted");
                            }
                        }
                    }

                    var globalnodes = instance.cy.nodes();
                    var selected = [];
                    for (var i = 0; i < globalnodes.length; i++) {
                        if (globalnodes[i].hasClass("highlighted")) {
                            selected.push(globalnodes[i]._private.ids);
                        }
                    }

                    //console.log(globalnodes);
                    //console.log(selected);

                    var keys = [];
                    for (var i = 0; i < selected.length; i++) {
                        var kk = selected[i];
                        for (var k in kk) keys.push(k);
                    }
                    console.log(keys);
                    Shiny.onInputChange("connectedNodes", keys);
                });

                cy.on('tap', 'node', function (event) {
                    var node = this;
                    $(".qtip").remove();
                    //console.log(event);

                    var name = node._private.data.name;
                    var hrefclick = node._private.data.hrefclick;

                    var target = event.cyTarget;
                    var sourceName = target.data("id");
                    var targetName = target.data("hrefclick");
                    console.log(sourceName);
                    //console.log(targetName);

                    var x = event.cyRenderedPosition.x;
                    var y = event.cyRenderedPosition.y;
                    //var x = event.cyPosition.x;
                    //var y = event.cyPosition.y;
                    //console.log("x="+x+" Y="+y);

                    cy.getElementById(node.id()).qtip({
                        content: {
                            text: function (event, api) {
                              // Retrieve content from custom attribute of the $('.selector') elements.
                              return hrefclick;
                            }
                        },
                        show: {
                            ready: true
                        },
                        position: {
                            my: 'bottom center',
                            at: 'top center',
                            adjust: {
                              cyViewport: true
                            },
                            effect: false
                        },
                        hide: false,
                        style: {
                            classes: 'qtip-bootstrap',
                            tip: {
                              width: 48,
                              height: 8
                            }
                        }
                    });
                });
                cy.on('mouseenter', 'node', function (event) {
                    var node = this;
                    //$(".qtip").remove();
                    //console.log(event);

                    var name = node._private.data.name;
                    var href = node._private.data.href;

                    var target = event.cyTarget;
                    var sourceName = target.data("id");
                    var targetName = target.data("href");
                    console.log(sourceName);
                    //console.log(targetName);

                    var x = event.cyRenderedPosition.x;
                    var y = event.cyRenderedPosition.y;
                    //var x = event.cyPosition.x;
                    //var y = event.cyPosition.y;
                    //console.log("x="+x+" Y="+y);

                    cy.getElementById(node.id()).qtip({
                        content: {
                            text: function (event, api) {
                              // Retrieve content from custom attribute of the $('.selector') elements.
                              return href;
                            }
                        },
                        show: {
                            ready: true,
                            effect: false,
                            delay: 500
                        },
                        position: {
                            my: 'bottom center',
                            at: 'top center',
                            adjust: {
                              cyViewport: true
                            },
                            effect: false
                        },
                        hide: {
                            fixed: true,
                            event: 'mouseleave',
                            effect: false
                        },
                        style: {
                            classes: 'qtip-bootstrap',
                            tip: {
                              width: 16,
                              height: 8
                            }
                        }
                    });
                });
            }
        });
    }
});
<commit_msg>Revert back to mouseover instead of mouseenter<commit_after>HTMLWidgets.widget({
    name: 'rcytoscapejs',
    type: 'output',

    initialize: function (el, width, height) {
        return {
            // TODO: add instance fields as required
        }
    },

    resize: function (el, width, height, instance) {
        if (instance.cy)
            instance.cy.resize();
    },

    renderValue: function (el, x, instance) {
        //console.log(x.nodeEntries);
        //console.log(x.edgeEntries);

        //var nodetest = JSON.parse(x.nodeEntries);
        //var edgetest = JSON.parse(x.edgeEntries);

        //console.log(nodetest);
        //console.log(edgetest);

        var defaults = ({
          zoomFactor: 0.05, // zoom factor per zoom tick
          zoomDelay: 45, // how many ms between zoom ticks
          minZoom: 0.1, // min zoom level
          maxZoom: 10, // max zoom level
          fitPadding: 50, // padding when fitting
          panSpeed: 10, // how many ms in between pan ticks
          panDistance: 10, // max pan distance per tick
          panDragAreaSize: 75, // the length of the pan drag box in which the vector for panning is calculated (bigger = finer control of pan speed and direction)
          panMinPercentSpeed: 0.25, // the slowest speed we can pan by (as a percent of panSpeed)
          panInactiveArea: 8, // radius of inactive area in pan drag box
          panIndicatorMinOpacity: 0.5, // min opacity of pan indicator (the draggable nib); scales from this to 1.0
          autodisableForMobile: true, // disable the panzoom completely for mobile (since we don't really need it with gestures like pinch to zoom)

          // icon class names
          sliderHandleIcon: 'fa fa-minus',
          zoomInIcon: 'fa fa-plus',
          zoomOutIcon: 'fa fa-minus',
          resetIcon: 'fa fa-expand'
        });

        var positionMap = {};

        //add position information to data for preset layout
        for (var i = 0; i < x.nodeEntries.length ; i++){
            var xPos = x.nodeEntries[i].data.x;
            var yPos = x.nodeEntries[i].data.y;
            positionMap[x.nodeEntries[i].data.id] = {'x':parseFloat(xPos), 'y':parseFloat(yPos)};
        }

        instance.cy = new cytoscape({
            container: el,
            style: cytoscape.stylesheet()
                .selector('node')
                .css({
                    'color': 'data(nodeLabelColor)',
                    'opacity': 'data(opacity)',
                    'content': 'data(name)',
                    'text-valign': 'center',
                    'shape': 'data(shape)',
                    'text-outline-color': 'data(color)',
                    'background-color': 'data(color)',
                    'width': 'data(width)',
                    'height': 'data(height)',
                    'weight': 'data(weight)',
                    'border-style': 'data(borderstyle)',
                    'border-color': 'data(bordercolor)',
                    'border-width': 'data(borderwidth)',
                    'border-opacity': 'data(borderopacity)',
                    'rank': 'data(rank)'
                })
                .selector('edge')
                .css({
                    'line-color': 'data(color)',
                    'source-arrow-color': 'data(color)',
                    'target-arrow-color': 'data(color)',
                    'source-arrow-shape': 'data(edgeSourceShape)',
                    'target-arrow-shape': 'data(edgeTargetShape)',
                    'width': 'data(width)',
                    'opacity': 'data(opacity)'
                })
                .selector(':selected')
                .css({
                    'background-color': '#000000',
                    'line-color': 'black',
                    'target-arrow-color': 'black',
                    'source-arrow-color': 'black'
                })
                .selector('.highlighted')
                .css({
                    'background-color': '#000000',
                    'line-color': '#000000',
                    'target-arrow-color': '#000000',
                    'transition-property': 'background-color, line-color, target-arrow-color',
                    'transition-duration': '0.5s'
                })
                .selector('.faded')
                .css({
                    'opacity': 0.25,
                    'text-opacity': 0
                }),

            elements: {
                nodes: x.nodeEntries,
                //nodes: [{ data: { id:'509209821', name:'509209821', color:'#888888', shape:'ellipse', href:''} }, { data: { id:'531376085', name:'531376085', color:'#888888', shape:'ellipse', href:''} }],
                edges: x.edgeEntries
                //edges: [{ data: { source:'509209821', target:'531376085', color:'#888888', edgeSourceShape:'none', edgeTargetShape:'triangle'} }]

            },
            layout: {
                name: x.layout,
                ungrabifyWhileSimulating: true,
                positions: positionMap
            },
            ready: function () {
                window.cy = this;

                if(x.showPanzoom) {
                  cy.panzoom(defaults);
                }

                cy.boxSelectionEnabled(true);
                cy.userZoomingEnabled(true);
                cy.on('tap', 'node', function (event) {
                    var nodeHighlighted = this.hasClass("highlighted");
                    console.log(nodeHighlighted);
                    var nodes = this.closedNeighborhood().connectedNodes();
                    //console.log(nodes);
                    console.log("A:" + el.id);
                    console.log("ID:" + this._private.data.id);
                    Shiny.onInputChange("clickedNode", this._private.data.id);
                    console.log("break");

                    if (nodes.length === 0) {
                        this.toggleClass("highlighted");
                    }

                    if (nodeHighlighted) {
                        for (var i = 0; i < nodes.length; i++) {
                            if (nodes[i].hasClass("highlighted")) {
                                nodes[i].toggleClass("highlighted");
                            }
                        }
                    } else {
                        for (var i = 0; i < nodes.length; i++) {
                            if (!nodes[i].hasClass("highlighted")) {
                                nodes[i].toggleClass("highlighted");
                            }
                        }
                    }

                    var globalnodes = instance.cy.nodes();
                    var selected = [];
                    for (var i = 0; i < globalnodes.length; i++) {
                        if (globalnodes[i].hasClass("highlighted")) {
                            selected.push(globalnodes[i]._private.ids);
                        }
                    }

                    //console.log(globalnodes);
                    //console.log(selected);

                    var keys = [];
                    for (var i = 0; i < selected.length; i++) {
                        var kk = selected[i];
                        for (var k in kk) keys.push(k);
                    }
                    console.log(keys);
                    Shiny.onInputChange("connectedNodes", keys);
                });

                cy.on('tap', 'node', function (event) {
                    var node = this;
                    $(".qtip").remove();
                    //console.log(event);

                    var name = node._private.data.name;
                    var hrefclick = node._private.data.hrefclick;

                    var target = event.cyTarget;
                    var sourceName = target.data("id");
                    var targetName = target.data("hrefclick");
                    console.log(sourceName);
                    //console.log(targetName);

                    var x = event.cyRenderedPosition.x;
                    var y = event.cyRenderedPosition.y;
                    //var x = event.cyPosition.x;
                    //var y = event.cyPosition.y;
                    //console.log("x="+x+" Y="+y);

                    cy.getElementById(node.id()).qtip({
                        content: {
                            text: function (event, api) {
                              // Retrieve content from custom attribute of the $('.selector') elements.
                              return hrefclick;
                            }
                        },
                        show: {
                            ready: true
                        },
                        position: {
                            my: 'bottom center',
                            at: 'top center',
                            adjust: {
                              cyViewport: true
                            },
                            effect: false
                        },
                        hide: false,
                        style: {
                            classes: 'qtip-bootstrap',
                            tip: {
                              width: 48,
                              height: 8
                            }
                        }
                    });
                });
                cy.on('mouseover', 'node', function (event) {
                    var node = this;
                    //$(".qtip").remove();
                    //console.log(event);

                    var name = node._private.data.name;
                    var href = node._private.data.href;

                    var target = event.cyTarget;
                    var sourceName = target.data("id");
                    var targetName = target.data("href");
                    console.log(sourceName);
                    //console.log(targetName);

                    var x = event.cyRenderedPosition.x;
                    var y = event.cyRenderedPosition.y;
                    //var x = event.cyPosition.x;
                    //var y = event.cyPosition.y;
                    //console.log("x="+x+" Y="+y);

                    cy.getElementById(node.id()).qtip({
                        content: {
                            text: function (event, api) {
                              // Retrieve content from custom attribute of the $('.selector') elements.
                              return href;
                            }
                        },
                        show: {
                            ready: true,
                            effect: false,
                            delay: 500
                        },
                        position: {
                            my: 'bottom center',
                            at: 'top center',
                            adjust: {
                              cyViewport: true
                            },
                            effect: false
                        },
                        hide: {
                            fixed: true,
                            event: 'mouseleave',
                            effect: false
                        },
                        style: {
                            classes: 'qtip-bootstrap',
                            tip: {
                              width: 16,
                              height: 8
                            }
                        }
                    });
                });
            }
        });
    }
});
<|endoftext|>


<commit_before>// <% if (typescript) { %>
/// <% if (module) { %>
import fs from 'fs';
// <% } else { %>const fs = require('fs');<% } %>

const lintTSConfig = 'tsconfig.lint.json';

const generateTSConfig = (stagedFilenames) => {
  const tsconfig = JSON.parse(fs.readFileSync('tsconfig.json', 'utf8'));
  tsconfig.include = stagedFilenames;
  fs.writeFileSync(lintTSConfig, JSON.stringify(tsconfig));
  return 'tsc --noEmit --project tsconfig.lint.json';
};

const deleteTSConfig = (stagedFilenames) => {
  stagedFilenames.length = 0;
  if (fs.existsSync(lintTSConfig)) {
    fs.unlinkSync(lintTSConfig);
  }
  return '';
};
// <% } %>

/// <% if (module) { %>
export default {
  // <% } else { %>module.exports = {<% } %>
  // <% if (prettier) { %>
  '*': ['prettier --check'],
  // <% } %>
  // <% if (jsTarget) { %>
  '<%= jsTarget %>': [
    // <% if (eslint) { %>
    'eslint',
    // <% } %>
    // <% if (typescript) { %>
    generateTSConfig,
    deleteTSConfig,
    // <% } %>
    // <% if (jest) { %>
    'jest --bail --findRelatedTests',
    // <% } %>
  ],
  // <% } %>
  // <% if (cssTarget && stylelint) { %>
  '<%= cssTarget %>': ['stylelint<% if (scss) { %> --syntax=scss<% } %>'],
  // <% } %>
};
<commit_msg>style: disable rule on line<commit_after>// <% if (typescript) { %>
/// <% if (module) { %>
import fs from 'fs';
// <% } else { %>const fs = require('fs');<% } %>

const lintTSConfig = 'tsconfig.lint.json';

const generateTSConfig = (stagedFilenames) => {
  const tsconfig = JSON.parse(fs.readFileSync('tsconfig.json', 'utf8'));
  tsconfig.include = stagedFilenames;
  fs.writeFileSync(lintTSConfig, JSON.stringify(tsconfig));
  return 'tsc --noEmit --project tsconfig.lint.json';
};

const deleteTSConfig = (stagedFilenames) => {
  // eslint-disable-next-line no-param-reassign
  stagedFilenames.length = 0;
  if (fs.existsSync(lintTSConfig)) {
    fs.unlinkSync(lintTSConfig);
  }
  return '';
};
// <% } %>

/// <% if (module) { %>
export default {
  // <% } else { %>module.exports = {<% } %>
  // <% if (prettier) { %>
  '*': ['prettier --check'],
  // <% } %>
  // <% if (jsTarget) { %>
  '<%= jsTarget %>': [
    // <% if (eslint) { %>
    'eslint',
    // <% } %>
    // <% if (typescript) { %>
    generateTSConfig,
    deleteTSConfig,
    // <% } %>
    // <% if (jest) { %>
    'jest --bail --findRelatedTests',
    // <% } %>
  ],
  // <% } %>
  // <% if (cssTarget && stylelint) { %>
  '<%= cssTarget %>': ['stylelint<% if (scss) { %> --syntax=scss<% } %>'],
  // <% } %>
};
<|endoftext|>


<commit_before>var formgroup = '
%name% <input class="form-control" id="%id%" name="%name%" placeholder="%pholder%" title="" type="text" required />
';
var jscript1 = 'var date = $("%id%").val();';
var jscript2 =  '$("%printid%").append(date);';

var repairsdict = {
  "tname":{
    "id":"tname",
    "name":"Your Name",
    "pholder":"Your First and Last Name"},
  "address":{
    "id":"taddress",
    "name":"Your Address",
     "pholder":"123 Main Street"},
  "city":{
    "id":"tcity",
    "name":"Your City of Residence",
    "pholder":"Cityville"},
  "postal":{
    "id":"tpostal",
    "name": "Your Postal Code",
    "pholder":"V5Y1J2"},
  "lname":{
    "id": "lname",
    "name": "Your Landlords Name",
    "pholder": "Jane Doe"},
  "laddress":{
    "id": "laddress",
    "name": "You Landlords Address",
    "pholder": "123 Main Street"
  },
  "lcity":{
    "id":"lcity",
    "name":"Your Landlords City of Residence",
    "pholder":"Cityville"
  },
  "lpostal":{
    "id":"lpostal",
    "name": "Your Postal Code",
    "pholder":"V5Y1J2"
  },
  "repairs":{
    "id": "repairs",
    "name":"Description of Repairs",
    "pholder":"Descriptive List of Repairs. Please use complete sentences. For instance, 'The upstairs sink is leaking.'"
  },
  "rdate":{
    "id":"rdate",
    "name": "Reasonable Date for Completion of Repairs",
    "pholder": "Provide a deadline for the repairs to be finished by."}
  }

function textareafy(fgroup, col, row) {
  $input = $("#"+fgroup["id"]);
  $textarea = $("<textarea></textarea>").attr({
    class: 'form-control',
    id: $input.attr('id'),
    name: $input.attr('name'),
    placeholder: fgroup["pholder"],
    cols: col,
    rows: row
  });
  $input.after($textarea).remove();

}

function saveform(dictionary) {
  for (var fgroup in dictionary) {
    dictionary[fgroup]["var"] = $("#"+dictionary[fgroup]["id"]).val();
    $("." + dictionary[fgroup]["id"]+"print").each(function(){
      $(this).text(function(){
        return $(this).text().replace(/%text%/, dictionary[fgroup]["var"]);
      });
    });
  }
}

function printform(num, dict) {
  for (var fgroup in dict) {
    formattedgroup = formgroup.replace(/%name%/g, dict[fgroup]["name"]).replace(/%id%/g, dict[fgroup]["id"]).replace(/%pholder%/g, dict[fgroup]["pholder"]);
    $("#"+forms[num]).append(formattedgroup);
  };

var repintroduction = {
  "tdate":{
    "id":"tdate",
    "name":"Todays date",
    "pholder":"MM/DD/YYYY"},
  "tname":{
      "id":"tname",
      "name":"Your Name",
      "pholder":"Your First and Last Name"},
  "address":{
      "id":"taddress",
      "name":"Your Address",
       "pholder":"123 Main Street"},
  "city":{
      "id":"tcity",
      "name":"Your City of Residence",
      "pholder":"Cityville"},
  "postal":{
      "id":"tpostal",
      "name": "Your Postal Code",
      "pholder":"V5Y1J2"},
  "lname":{
      "id": "lname",
      "name": "Your Landlords Name",
      "pholder": "Jane Doe"},
  "laddress":{
      "id": "laddress",
      "name": "You Landlords Address",
      "pholder": "123 Main Street"},
  "lcity":{
      "id":"lcity",
      "name":"Your Landlords City of Residence",
      "pholder":"Cityville"},
  "lpostal":{
      "id":"lpostal",
      "name": "Your Postal Code",
      "pholder":"V5Y1J2"},
  "idate":{
      "id":"idate",
      "name": "Date the issue started",
      "pholder": "MM/DD/YYYY"},
  "issuesummaryprint":{
      "id":"issuesummaryprint",
      "name":"Issue summary",
      "pholder": "Brief summary of the issue, in complete sentences. The sink was broken."},
  "ldate":{
      "id":"ldate",
      "name": "Date letter was sent to landlord",
      "pholder": "MM/DD/YYYY"},
  "ddate":{
      "id":"ddate",
      "name": "Deadline Given Landlord for Completion of Repairs",
      "pholder": "MM/DD/YYYY"},
  "repairs":{
      "id": "repairs",
      "name":"Description of Repairs",
      "pholder":"Descriptive List of Repairs. Please use complete sentences. For instance, 'The upstairs sink is leaking.'"}
}
var repbackground = {
  "bckground":{
    "id": "bckground",
    "name":"Background",
    "pholder":"Provide any additional background you'd like to add to this complaint. You can leave this blank. Be specific and give dates. Less is usually more. "},
  "impact":{
    "id":"impact",
    "name":"Impact",
    "pholder":"In a few short sentences describe how your landlord's neglegence has negatively effected you. These impacts can be physical, mental, or financial. Be as specific as possible and give dates and full names of witnesses wherever possible."}
  }
var evidence = {
  "edate":{
    "id": "edate",
    "name":"Evidence Time Stap",
    "pholder":""},
}
var repconclusion = {
  "damages":{
    "id":"damages",
    "name":"Damages",
    "pholder":"Amount of money you are asking to get re-imbursed for. If you are asking for money back you should submit a Monetary order worksheet (http://www2.gov.bc.ca/assets/gov/housing-and-tenancy/residential-tenancies/forms/rtb21.pdf)"
  }
}
<commit_msg>linted<commit_after>var formgroup = '
%name% <input class="form-control" id="%id%" name="%name%" placeholder="%pholder%" title="" type="text" required />
';
var jscript1 = 'var date = $("%id%").val();';
var jscript2 =  '$("%printid%").append(date);';

var repairsdict = {
  "tname":{
    "id":"tname",
    "name":"Your Name",
    "pholder":"Your First and Last Name"},
  "address":{
    "id":"taddress",
    "name":"Your Address",
     "pholder":"123 Main Street"},
  "city":{
    "id":"tcity",
    "name":"Your City of Residence",
    "pholder":"Cityville"},
  "postal":{
    "id":"tpostal",
    "name": "Your Postal Code",
    "pholder":"V5Y1J2"},
  "lname":{
    "id": "lname",
    "name": "Your Landlords Name",
    "pholder": "Jane Doe"},
  "laddress":{
    "id": "laddress",
    "name": "You Landlords Address",
    "pholder": "123 Main Street"
  },
  "lcity":{
    "id":"lcity",
    "name":"Your Landlords City of Residence",
    "pholder":"Cityville"
  },
  "lpostal":{
    "id":"lpostal",
    "name": "Your Postal Code",
    "pholder":"V5Y1J2"
  },
  "repairs":{
    "id": "repairs",
    "name":"Description of Repairs",
    "pholder":"Descriptive List of Repairs. Please use complete sentences. For instance, 'The upstairs sink is leaking.'"
  },
  "rdate":{
    "id":"rdate",
    "name": "Reasonable Date for Completion of Repairs",
    "pholder": "Provide a deadline for the repairs to be finished by."}
  };

function textareafy(fgroup, col, row) {
  $input = $("#"+fgroup["id"]);
  $textarea = $("<textarea></textarea>").attr({
    class: 'form-control',
    id: $input.attr('id'),
    name: $input.attr('name'),
    placeholder: fgroup["pholder"],
    cols: col,
    rows: row
  });
  $input.after($textarea).remove();
};

function saveform(dictionary) {
  for (var fgroup in dictionary) {
    dictionary[fgroup]["var"] = $("#"+dictionary[fgroup]["id"]).val();
    $("." + dictionary[fgroup]["id"]+"print").each(function(){
      $(this).text(function(){
        return $(this).text().replace(/%text%/, dictionary[fgroup]["var"]);
      });
    });
  }
};

function printform(num, dict) {
  for (var fgroup in dict) {
    formattedgroup = formgroup.replace(/%name%/g, dict[fgroup]["name"]).replace(/%id%/g, dict[fgroup]["id"]).replace(/%pholder%/g, dict[fgroup]["pholder"]);
    $("#"+forms[num]).append(formattedgroup);
  };

var repintroduction = {
  "tdate":{
    "id":"tdate",
    "name":"Todays date",
    "pholder":"MM/DD/YYYY"},
  "tname":{
      "id":"tname",
      "name":"Your Name",
      "pholder":"Your First and Last Name"},
  "address":{
      "id":"taddress",
      "name":"Your Address",
       "pholder":"123 Main Street"},
  "city":{
      "id":"tcity",
      "name":"Your City of Residence",
      "pholder":"Cityville"},
  "postal":{
      "id":"tpostal",
      "name": "Your Postal Code",
      "pholder":"V5Y1J2"},
  "lname":{
      "id": "lname",
      "name": "Your Landlords Name",
      "pholder": "Jane Doe"},
  "laddress":{
      "id": "laddress",
      "name": "You Landlords Address",
      "pholder": "123 Main Street"},
  "lcity":{
      "id":"lcity",
      "name":"Your Landlords City of Residence",
      "pholder":"Cityville"},
  "lpostal":{
      "id":"lpostal",
      "name": "Your Postal Code",
      "pholder":"V5Y1J2"},
  "idate":{
      "id":"idate",
      "name": "Date the issue started",
      "pholder": "MM/DD/YYYY"},
  "issuesummaryprint":{
      "id":"issuesummaryprint",
      "name":"Issue summary",
      "pholder": "Brief summary of the issue, in complete sentences. The sink was broken."},
  "ldate":{
      "id":"ldate",
      "name": "Date letter was sent to landlord",
      "pholder": "MM/DD/YYYY"},
  "ddate":{
      "id":"ddate",
      "name": "Deadline Given Landlord for Completion of Repairs",
      "pholder": "MM/DD/YYYY"},
  "repairs":{
      "id": "repairs",
      "name":"Description of Repairs",
      "pholder":"Descriptive List of Repairs. Please use complete sentences. For instance, 'The upstairs sink is leaking.'"}
};
var repbackground = {
  "bckground":{
    "id": "bckground",
    "name":"Background",
    "pholder":"Provide any additional background you'd like to add to this complaint. You can leave this blank. Be specific and give dates. Less is usually more. "},
  "impact":{
    "id":"impact",
    "name":"Impact",
    "pholder":"In a few short sentences describe how your landlord's neglegence has negatively effected you. These impacts can be physical, mental, or financial. Be as specific as possible and give dates and full names of witnesses wherever possible."}
  };
var evidence = {
  "edate":{
    "id": "edate",
    "name":"Evidence Time Stap",
    "pholder":""},
};
var repconclusion = {
  "damages":{
    "id":"damages",
    "name":"Damages",
    "pholder":"Amount of money you are asking to get re-imbursed for. If you are asking for money back you should submit a Monetary order worksheet (http://www2.gov.bc.ca/assets/gov/housing-and-tenancy/residential-tenancies/forms/rtb21.pdf)"
  }
};
<|endoftext|>


<commit_before>/**
 * Paths are relative to the location from which
 * require.js is called.
 * To assemble the module, define the path variable
 * _c.path.usr in main.js
 * For example:
 * var _c = _c || {};
 * _c.path = _c.path || {};
 * _c.path.usr = '../usr/';
 */
(function(path) {
    var files = [
        'extend',
        'utils/arrays',
        'draw/canvas-utils',
        'draw/highlights',
        'draw/point',
        'draw/drawable',
        'draw/shape',
        'draw/ellipse',
        'draw/circle',
        'draw/rectangle',
        'draw/polygon',
        'draw/regular-polygon',
        'draw/image',
        'draw/tile-set',
        'draw/frame-set',
        'draw/composite',
        'draw/sprite',
        'draw/time-warp',
        'draw/timer'
    ];

    files.forEach(function(file, i) {
        files[i] = path.usr + file;
    });

    define(files, function(
        extend,
        arrayUtils,
        canvasUtils,
        highlights,
        Point,
        Drawable,
        Shape,
        Ellipse,
        Circle,
        Rectangle,
        Polygon,
        RegularPolygon,
        Image,
        TileSet,
        FrameSet,
        Composite,
        Sprite,
        TimeWarp,
        Timer
    ) {
        if (!path.images) path.images = './images/';
    });
})(_c.path);
<commit_msg>Remove obsolete main file<commit_after><|endoftext|>


<commit_before>/*
 * mik-loan
 * https://github.com/ellnestam/mik-loan
 *
 * Copyright (c) 2013 Ola Ellnestam
 * Licensed under the MIT license.
 */

'use strict';

var url = require('url');
var http = require('http');
var repository = require('./loan/repository.js');

var APPLICATION = "apply";
var FETCH = "fetch";
var TICKET_ID = "ticketId";
var APPROVE = "approve";

var srv = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    if (query.action === 'apply') {
	var application = {amount: query['amount'],
			   contact: query['contact'],
			   applicationNo: 3
			  };
	repository.store(application, function printTicket(ticket) {
	    res.end(ticket + '\n');
	});

    } else if (query.action === 'fetch') {
	var ticketId = query[TICKET_ID];
        repository.fetch(ticketId, function printFetched(data) {
	    console.log('D2: ' + data);
	    res.end(data + '\n');
	});
	return;
    } else if (query.action === 'approve') {
        repository.approveLoan(query[TICKET_ID], function printTicket(ticket) {
	    res.end(ticket + '\n');
	});
	return;
    }

    res.end('Incorrect parameters provided\n');
}).listen(8080);

function approveLoan(ticketId) {
    return 'Approving ' + ticketId + '\n';;
};

function fetchLoanInfo(ticketId) {
    return JSON.stringify(repository.fetch(ticketId)) + '\n';
}

/* console.log('Storing that mutha');
var files = fs.readdir('loans', function(err, list) {
    console.log(list);

});
console.log(files); */

<commit_msg>Clean up<commit_after>'use strict';

var url = require('url');
var http = require('http');
var repository = require('./loan/repository.js');

var APPLICATION = "apply";
var FETCH = "fetch";
var TICKET_ID = "ticketId";
var APPROVE = "approve";

var srv = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    if (query.action === 'apply') {
	var application = {amount: query['amount'],
			   contact: query['contact'],
			   applicationNo: 3
			  };
	repository.store(application, function printTicket(ticket) {
	    res.end(ticket + '\n');
	});

    } else if (query.action === 'fetch') {
	var ticketId = query[TICKET_ID];
        repository.fetch(ticketId, function printFetched(application) {
	    res.end(application + '\n');
	});
	return;
    } else if (query.action === 'approve') {
        repository.approveLoan(query[TICKET_ID], function printTicket(ticket) {
	    res.end(ticket + '\n');
	});
	return;
    }

    res.end('Incorrect parameters provided\n');
}).listen(8080);
<|endoftext|>