<commit_before>var pcsc = require('../index');

var pcsc = pcsc();
pcsc.on('reader', function(reader) {

    console.log('New reader detected', reader.name);

    reader.on('error', function(err) {
        console.log('Error(', this.name, '):', err.message);
    });

    reader.on('status', function(status) {
        console.log('Status(', this.name, '):', status);
        /* check what has changed */
        var changes = this.state ^ status.state;
        if (changes) {
            if ((changes & this.SCARD_STATE_EMPTY) && (status.state & this.SCARD_STATE_EMPTY)) {
                console.log("card removed");/* card removed */
                reader.disconnect(reader.SCARD_LEAVE_CARD, function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log('Disconnected');
                    }
                });
            } else if ((changes & this.SCARD_STATE_PRESENT) && (status.state & this.SCARD_STATE_PRESENT)) {
                console.log("card inserted");/* card inserted */
                reader.connect(function(err, protocol) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log('Protocol(', this.name, '):', protocol);
                        reader.transmit(new Buffer([0x00, 0xB0, 0x00, 0x00, 0x20]), 40, protocol, function(err, data) {
                            if (err) {
                                console.log(err);
                            } else {
                                console.log('Data received', data);
                            }
                        });
                    }
                });
            }
        }
    });

    reader.on('end', function() {
        console.log('Reader',  this.name, 'removed');
    });
});

pcsc.on('error', function(err) {
    console.log('PCSC error', err.message);
});
<commit_msg>example: fix connect callback log<commit_after>var pcsc = require('../index');

var pcsc = pcsc();
pcsc.on('reader', function(reader) {

    console.log('New reader detected', reader.name);

    reader.on('error', function(err) {
        console.log('Error(', this.name, '):', err.message);
    });

    reader.on('status', function(status) {
        console.log('Status(', this.name, '):', status);
        /* check what has changed */
        var changes = this.state ^ status.state;
        if (changes) {
            if ((changes & this.SCARD_STATE_EMPTY) && (status.state & this.SCARD_STATE_EMPTY)) {
                console.log("card removed");/* card removed */
                reader.disconnect(reader.SCARD_LEAVE_CARD, function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log('Disconnected');
                    }
                });
            } else if ((changes & this.SCARD_STATE_PRESENT) && (status.state & this.SCARD_STATE_PRESENT)) {
                console.log("card inserted");/* card inserted */
                reader.connect(function(err, protocol) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log('Protocol(', reader.name, '):', protocol);
                        reader.transmit(new Buffer([0x00, 0xB0, 0x00, 0x00, 0x20]), 40, protocol, function(err, data) {
                            if (err) {
                                console.log(err);
                            } else {
                                console.log('Data received', data);
                            }
                        });
                    }
                });
            }
        }
    });

    reader.on('end', function() {
        console.log('Reader',  this.name, 'removed');
    });
});

pcsc.on('error', function(err) {
    console.log('PCSC error', err.message);
});
<|endoftext|>


<commit_before>const app = require('express')(),
      usersTable = require('../../models/users.js');

app.get('/user/:email', ( req, res )=>{
   console.log(req.params.email);
   usersTable.find(req.params.email)

      .then(data=>{

        res.send(data);

      })

      .catch(err=>{

        var error = 'Please try again. There was a problem on our side.'
        res.render('signin.pug', error);

      });

});

module.exports = app;
<commit_msg>fix: eliminate console log of data<commit_after>const app = require('express')(),
      usersTable = require('../../models/users.js');

app.get('/user/:email', ( req, res )=>{
   usersTable.find(req.params.email)

      .then(data=>{

        res.send(data);

      })

      .catch(err=>{

        var error = 'Please try again. There was a problem on our side.'
        res.render('signin.pug', error);

      });

});

module.exports = app;
<|endoftext|>


<commit_before>import Resolver from 'resolver';

var App = Ember.Application.extend({
  LOG_ACTIVE_GENERATION: true,
  LOG_MODULE_RESOLVER: true,
  LOG_TRANSITIONS: true,
  LOG_TRANSITIONS_INTERNAL: true,
  LOG_VIEW_LOOKUPS: true,
  modulePrefix: 'appkit', // TODO: loaded via config
  Resolver: Resolver['default'],
  init: function () {
    window.ENV.firebaseRoot = new Firebase("https://" + window.ENV.dbName + ".firebaseio.com/");
    this._super.apply(this, arguments);
  }
});

Ember.Application.initializer({
  name: "BuildEnvironmentDetector",
  initialize: function (container, application) {
    application.deferReadiness();

    var self = this,
        buildEnv = Ember.Object.create();

    application.register('build-environment:environment:current', buildEnv, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'buildEnvironment', 'build-environment:environment:current');
    });

    var isLocal = false;
    var localSocket = null;
    if(document.location.hostname === "localhost" || document.location.hostname === "127.0.0.1")
    {
      isLocal = true;
      localSocket = {
        socket: new window.WebSocket('ws://localhost:6557'),
        doneCallback: null,
        connected: false
      };

      localSocket.socket.onmessage = function(event) {
        if(event.data === 'done') {
          if(localSocket.doneCallback) localSocket.doneCallback();
          localSocket.doneCallback = null; //Reset so done doesn't get called twice
        }
      };

      localSocket.socket.onopen = function() {
        localSocket.connected = true;
      };

      // Shut down LiveReload
      if(window.LiveReload) {
        var shutDown = new CustomEvent('LiveReloadShutDown');
        Ember.$(document)[0].dispatchEvent(shutDown);
      }
    }

    buildEnv.set('local', isLocal);
    buildEnv.set('localSocket', localSocket);

    application.set('buildEnvironment', buildEnv);

    application.advanceReadiness();
  }
});

Ember.Application.initializer({
  name: "FirebaseSimpleLogin",
  initialize: function (container, application) {

    application.deferReadiness();

    var self = this,
        siteName = Ember.$('meta[name="siteName"]').attr('content'),
        session = Ember.Object.create();

    // Add `session` to all the things
    application.register('firebase-simple-login:session:current', session, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'session', 'firebase-simple-login:session:current');
    });
    application.set('session', session);

    session.set('auth', new FirebaseSimpleLogin(window.ENV.firebaseRoot, function(error, user) {

      if (error) {
        // an error occurred while attempting login
        session.set('error', error);
        application.advanceReadiness();
      } else if (user) {

        window.ENV.firebaseRoot.child('management/sites/' + siteName + '/key').once('value', function (snapshot) {

          var bucket = snapshot.val();

          window.ENV.firebase = window.ENV.firebaseRoot.child('buckets/' + siteName + '/' + bucket + '/dev');

          // user authenticated with Firebase
          session.set('user', user);
          session.set('error', null);
          application.advanceReadiness();
        }, function (error) {
          session.get('auth').logout();
          session.set('error', error);
          application.advanceReadiness();
        });
      } else {
        // user is logged out
        session.set('user', null);
        application.advanceReadiness();
      }
    }));

    window.ENV.sendBuildSignal = function() {
      var user = session.get('user.email');

      if(application.get('buildEnvironment').isLocal === false)
      {
        var data = {
          'userid': user,
          'sitename': siteName
        };

        window.ENV.firebase.root().child('management/commands/build/' + siteName).set(data, function() {});
      } else {
        window.ENV.sendGruntCommand('build');
      }
    };

    window.ENV.sendGruntCommand = function(command, callback) {
      var localSocket = application.get('buildEnvironment').localSocket;
      if(localSocket && localSocket.connected) {
        localSocket.socket.send(command);
        if(callback) localSocket.doneCallback = callback;
      }
    }.bind(this);
  }
});

// Before any route, kick user to login if they aren't logged in
Ember.Route.reopen({
  beforeModel: function (transition) {
    var openRoutes = ['login', 'password-reset', 'create-user', 'confirm-email'];
    if (Ember.$.inArray(transition.targetName, openRoutes) === -1 && !this.get('session.user')) {
      this.get('session').set('transition', transition);
      transition.abort();
      this.transitionTo('login');
    }
  }
});

// Ian doesn't like pluralizing, singularizing
Ember.Inflector.inflector.pluralize = function (string ) { return string; };
Ember.Inflector.inflector.singularize = function (string ) { return string; };

// This helps ember-validations not blow up
// https://github.com/dockyard/ember-validations/issues/26#issuecomment-31877071
DS.Model.reopen({
  isValid: false
});

export default App;
<commit_msg>screw it this works<commit_after>import Resolver from 'resolver';

var App = Ember.Application.extend({
  LOG_ACTIVE_GENERATION: true,
  LOG_MODULE_RESOLVER: true,
  LOG_TRANSITIONS: true,
  LOG_TRANSITIONS_INTERNAL: true,
  LOG_VIEW_LOOKUPS: true,
  modulePrefix: 'appkit', // TODO: loaded via config
  Resolver: Resolver['default'],
  init: function () {
    window.ENV.firebaseRoot = new Firebase("https://" + window.ENV.dbName + ".firebaseio.com/");
    this._super.apply(this, arguments);
  }
});

Ember.Application.initializer({
  name: "BuildEnvironmentDetector",
  initialize: function (container, application) {
    application.deferReadiness();

    var self = this,
        buildEnv = Ember.Object.create();

    application.register('build-environment:environment:current', buildEnv, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'buildEnvironment', 'build-environment:environment:current');
    });

    var isLocal = false;
    var localSocket = null;
    if(document.location.hostname === "localhost" || document.location.hostname === "127.0.0.1")
    {
      isLocal = true;
      localSocket = {
        socket: new window.WebSocket('ws://localhost:6557'),
        doneCallback: null,
        connected: false
      };

      localSocket.socket.onmessage = function(event) {
        if(event.data === 'done') {
          if(localSocket.doneCallback) localSocket.doneCallback();
          localSocket.doneCallback = null; //Reset so done doesn't get called twice
        }
      };

      localSocket.socket.onopen = function() {
        localSocket.connected = true;
      };

      // Shut down LiveReload
      if(window.LiveReload) {
        var shutDown = new CustomEvent('LiveReloadShutDown');
        document.addEventListener("LiveReloadConnect", function() {
          document.dispatchEvent(shutDown);
        }, false);
      }
    }

    buildEnv.set('local', isLocal);
    buildEnv.set('localSocket', localSocket);

    application.set('buildEnvironment', buildEnv);

    application.advanceReadiness();
  }
});

Ember.Application.initializer({
  name: "FirebaseSimpleLogin",
  initialize: function (container, application) {

    application.deferReadiness();

    var self = this,
        siteName = Ember.$('meta[name="siteName"]').attr('content'),
        session = Ember.Object.create();

    // Add `session` to all the things
    application.register('firebase-simple-login:session:current', session, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'session', 'firebase-simple-login:session:current');
    });
    application.set('session', session);

    session.set('auth', new FirebaseSimpleLogin(window.ENV.firebaseRoot, function(error, user) {

      if (error) {
        // an error occurred while attempting login
        session.set('error', error);
        application.advanceReadiness();
      } else if (user) {

        window.ENV.firebaseRoot.child('management/sites/' + siteName + '/key').once('value', function (snapshot) {

          var bucket = snapshot.val();

          window.ENV.firebase = window.ENV.firebaseRoot.child('buckets/' + siteName + '/' + bucket + '/dev');

          // user authenticated with Firebase
          session.set('user', user);
          session.set('error', null);
          application.advanceReadiness();
        }, function (error) {
          session.get('auth').logout();
          session.set('error', error);
          application.advanceReadiness();
        });
      } else {
        // user is logged out
        session.set('user', null);
        application.advanceReadiness();
      }
    }));

    window.ENV.sendBuildSignal = function() {
      var user = session.get('user.email');

      if(application.get('buildEnvironment').isLocal === false)
      {
        var data = {
          'userid': user,
          'sitename': siteName
        };

        window.ENV.firebase.root().child('management/commands/build/' + siteName).set(data, function() {});
      } else {
        window.ENV.sendGruntCommand('build');
      }
    };

    window.ENV.sendGruntCommand = function(command, callback) {
      var localSocket = application.get('buildEnvironment').localSocket;
      if(localSocket && localSocket.connected) {
        localSocket.socket.send(command);
        if(callback) localSocket.doneCallback = callback;
      }
    }.bind(this);
  }
});

// Before any route, kick user to login if they aren't logged in
Ember.Route.reopen({
  beforeModel: function (transition) {
    var openRoutes = ['login', 'password-reset', 'create-user', 'confirm-email'];
    if (Ember.$.inArray(transition.targetName, openRoutes) === -1 && !this.get('session.user')) {
      this.get('session').set('transition', transition);
      transition.abort();
      this.transitionTo('login');
    }
  }
});

// Ian doesn't like pluralizing, singularizing
Ember.Inflector.inflector.pluralize = function (string ) { return string; };
Ember.Inflector.inflector.singularize = function (string ) { return string; };

// This helps ember-validations not blow up
// https://github.com/dockyard/ember-validations/issues/26#issuecomment-31877071
DS.Model.reopen({
  isValid: false
});

export default App;
<|endoftext|>


<commit_before>var _ = require("lodash");
var moment = require("moment-timezone");
var crypto = require("crypto");
var url = require("url");
var lib_yaml = require("./yaml");
var zlib = require("zlib");

// Returns the "current" item within an array
exports.current = function (val) {
	if (_.isArray(val)) {
		if (!_.has(val, "currentIndex")) {
			val.currentIndex = 0;
		}
		return val[val.currentIndex];
	}
	else {
		return val;
	}
};

// Calculates a hash value given the algorithm name
exports.hash = function (val, algorithm) {
	algorithm = trim(algorithm);
	var hash = crypto.createHash(algorithm);
	hash.update(val);
	return hash.digest("hex");
};

// Alias for .hash
exports.checksum = exports.hash;

// Hash with "MD5"
exports.md5 = function (val) {
	return exports.checksum(val, "MD5");
};

// Hash with "SHA1"
exports.sha1 = function (val) {
	return exports.checksum(val, "SHA1");
};

exports.base64encode = function (val) {
	return new Buffer(val).toString("base64");
};
exports.b64encode = exports.base64encode;

exports.base64decode = function (val) {
	return new Buffer(val, "base64").toString();
};
exports.b64decode = exports.base64decode;

// Resolves a relative URL with respect to the specified base url
exports.resolve_url = function (relative, base) {
	relative = String(relative).trim();
	base = String(base).trim();
	return url.resolve(base, relative);
};

exports.yaml = function yaml(val) {
	return lib_yaml.dump(val);
};

exports.deflate = function deflate(val) {
	return zlib.deflateSync(val);
}

exports.inflate = function inflate(val) {
	return zlib.inflateSync(val);
}
<commit_msg>base64decode pipe no longer forces toString()<commit_after>var _ = require("lodash");
var moment = require("moment-timezone");
var crypto = require("crypto");
var url = require("url");
var lib_yaml = require("./yaml");
var zlib = require("zlib");

// Returns the "current" item within an array
exports.current = function (val) {
	if (_.isArray(val)) {
		if (!_.has(val, "currentIndex")) {
			val.currentIndex = 0;
		}
		return val[val.currentIndex];
	}
	else {
		return val;
	}
};

// Calculates a hash value given the algorithm name
exports.hash = function (val, algorithm) {
	algorithm = trim(algorithm);
	var hash = crypto.createHash(algorithm);
	hash.update(val);
	return hash.digest("hex");
};

// Alias for .hash
exports.checksum = exports.hash;

// Hash with "MD5"
exports.md5 = function (val) {
	return exports.checksum(val, "MD5");
};

// Hash with "SHA1"
exports.sha1 = function (val) {
	return exports.checksum(val, "SHA1");
};

exports.base64encode = function (val) {
	return new Buffer(val).toString("base64");
};
exports.b64encode = exports.base64encode;

exports.base64decode = function (val) {
	return new Buffer(val, "base64");
};
exports.b64decode = exports.base64decode;

// Resolves a relative URL with respect to the specified base url
exports.resolve_url = function (relative, base) {
	relative = String(relative).trim();
	base = String(base).trim();
	return url.resolve(base, relative);
};

exports.yaml = function yaml(val) {
	return lib_yaml.dump(val);
};

exports.deflate = function deflate(val) {
	return zlib.deflateSync(val);
}

exports.inflate = function inflate(val) {
	return zlib.inflateSync(val);
}
<|endoftext|>


<commit_before>/**
 * LMD Builder
 *
 * @author  Mikhail Davydov
 * @licence MIT
 */

var LMD_JS_SRC_PATH = __dirname + '/../src/',
    fs = require('fs'),
    parser = require("uglify-js").parser,
    uglify = require("uglify-js").uglify;

/**
 * LmdBuilder
 *
 * @constructor
 *
 * @param {Object} data
 * @param {Object} data.config               path to config file
 * @param {Object} [data.output]             result file or STDOUT
 * @param {Object} [data.version='lmd_tiny'] lmd version
 *
 * @example
 *      process.argv = "path/to/node path/to/file.js config.json [result.js] [lmd_version_name]";
 *      new LmdBuilder(process.argv);
 */
var LmdBuilder = function (data) {
    this.configFile = data.config;
    this.outputFile = data.output;
    this.lmdVersionName = data.version || 'lmd_tiny';

    if (!LmdBuilder.versionBuilder[this.lmdVersionName]) {
        throw new Error('No such LMD version - ' + this.lmdVersionName);
    }

    this.configDir = fs.realpathSync(this.configFile);
    this.configDir = this.configDir.split('/');
    this.configDir.pop();
    this.configDir = this.configDir.join('/');
    if (this.configure()) {
        this.build();
    }
};

/**
 * LMD builders templates
 *
 * @namespace
 */
LmdBuilder.versionBuilder = {
    'lmd_min': function (data) {
        return data.lmd_js + '(' + data.global + ',' + data.sandboxed_modules + ')(' + data.lmd_modules + ')(' + data.lmd_main + ')';
    },

    'lmd_tiny': function (data) {
        return data.lmd_js + '(' + data.global + ',' + data.lmd_main + ',' + data.lmd_modules + ',' + data.sandboxed_modules + ')';
    }
};

/**
 * Compress code using UglifyJS
 *
 * @param {String} code
 *
 * @returns {String} compressed code
 */
LmdBuilder.prototype.compress = function (code) {
    var ast = parser.parse(code);
    ast = uglify.ast_mangle(ast);
    ast = uglify.ast_squeeze(ast);

    return uglify.gen_code(ast);
};

/**
 * Wrapper for plain files
 *
 * @param {String} code
 *
 * @returns {String} wrapped code
 */
LmdBuilder.prototype.tryWrap = function (code) {
    try {
        var ast = parser.parse(code);
    } catch (e) {
        throw new Error('parse error on ' + code);
    }

    // ["toplevel",[["defun","depA",["require"],[]]]]
    if (ast && ast.length === 2 &&
        ast[1] && ast[1].length === 1 &&
        ast[1][0][0] === "defun"
        ) {
        return code;
    }

    // ["toplevel",[["stat",["function",null,["require"],[]]]]]
    if (ast && ast.length === 2 &&
        ast[1] && ast[1].length === 1 &&
        ast[1][0][0] === "stat" &&
        ast[1][0][1] &&
        ast[1][0][1][0] === "function"
        ) {
        return code;
    }

    return '(function (require, exports, module) { /* wrapped by builder */\n' + code + '\n})';
};

/**
 * JSON escaper
 *
 * @param file
 */
LmdBuilder.prototype.escape = function (file) {
    return JSON.stringify(file);
};

/**
 * Module code renderer
 *
 * @param {String[]} lmd_modules
 * @param {String}   lmd_main
 * @param {Boolean}  pack
 * @param {String}   globalObject
 * @param {String[]} sandboxed_modules
 *
 * @returns {String}
 */
LmdBuilder.prototype.render = function (lmd_modules, lmd_main, pack, globalObject, sandboxed_modules) {
    globalObject = globalObject || 'this';
    sandboxed_modules = JSON.stringify(sandboxed_modules || {});
    var lmd_js = fs.readFileSync(LMD_JS_SRC_PATH + this.lmdVersionName + '.js', 'utf8'),
        result;

    lmd_modules = '{\n' + lmd_modules.join(',\n') + '\n}';

    result = LmdBuilder.versionBuilder[this.lmdVersionName]({
        lmd_js: lmd_js,
        global: globalObject,
        lmd_main: lmd_main,
        lmd_modules: lmd_modules,
        sandboxed_modules: sandboxed_modules
    });

    if (pack) {
        result = this.compress(result);
    }

    return result;
};

/**
 * Performs configuration
 */
LmdBuilder.prototype.configure = function () {
    if (!this.configFile) {
        console.log('lmd usage:\n\t    lmd config.lmd.json [output.lmd.js] [lmd_min|lmd_tiny]');
        return false;
    }
    return true;
};

/**
 * Extracts file path parameters
 *
 * @param file
 */
LmdBuilder.prototype.extract = function (file) {
    file = file.split('/');
    return {
        file: file.pop(),
        path: (file.length ? file.join('/') + '/' : '')
    };
};

/**
 * Config files deep merge
 *
 * @param {Object} left
 * @param {Object} right
 */
LmdBuilder.prototype.deepDestructableMerge = function (left, right) {
    for (var prop in right) {
        if (right.hasOwnProperty(prop))  {
            if (typeof left[prop] === "object") {
                this.deepDestructableMerge(left[prop], right[prop]);
            } else {
                left[prop] = right[prop];
            }
        }
    }
    return left;
};

/**
 * Merges all config files in module's lineage
 *
 * @param config
 */
LmdBuilder.prototype.tryExtend = function (config) {
    config = config || {};
    if (typeof config.extends !== "string") {
        return config;
    }
    var parentConfig = this.tryExtend(JSON.parse(fs.readFileSync(this.configDir + '/' + config.extends, 'utf8')));

    return this.deepDestructableMerge(parentConfig, config);
};

/**
 * @name LmdModuleStruct
 * @class
 *
 * @field {String}  name       module name
 * @field {String}  path       full path to module
 * @field {Boolean} is_lazy    is lazy module?
 * @field {Boolean} is_sandbox is module sandboxed?
 * @field {Boolean} is_greedy  module is collected using wildcard
 */

/**
 * Collecting module using merged config
 *
 * @param config
 *
 * @returns {Object}
 */
LmdBuilder.prototype.collectModules = function (config) {
    var IS_HAS_WILD_CARD = /\*/;

    var modules = {},
        globalLazy = typeof config.lazy === "undefined" ? true : config.lazy,
        moduleLazy = false,
        moduleName,
        modulePath,
        descriptor,
        moduleDesciptor,
        wildcardRegex,
        moduleData,
        path =  config.path || '';

    if (path[0] !== '/') { // non-absolute
        path = this.configDir + '/' + path;
    }

    // grep paths
    for (moduleName in config.modules) {
        moduleDesciptor = config.modules[moduleName];
        // case "moduleName": "path/to/module.js"
        if (typeof moduleDesciptor === "string") {
            modulePath = moduleDesciptor;
            moduleLazy = globalLazy;
        } else { // case "moduleName": {"path": "path/to/module.js", "lazy": false}
            modulePath = moduleDesciptor.path;
            moduleLazy = typeof moduleDesciptor.lazy === "undefined" ? globalLazy : moduleDesciptor.lazy;
        }
        // its a wildcard
        // "*": "*.js" or "*_pewpew": "*.ru.json" or "ololo": "*.js"
        if (IS_HAS_WILD_CARD.test(modulePath)) {
            descriptor = this.extract(modulePath);
            wildcardRegex = new RegExp("^" + descriptor.file.replace(/\*/g, "(\\w+)") + "$");
            fs.readdirSync(path + descriptor.path).forEach(function (fileName) {
                var match = fileName.match(wildcardRegex),
                    newModuleName;

                if (match) {
                    match.shift();

                    // Modify a module name
                    match.forEach(function (replacement) {
                        newModuleName = moduleName.replace('*', replacement);
                    });

                    moduleData = {
                        name: newModuleName,
                        path: fs.realpathSync(path + descriptor.path + fileName),
                        is_lazy: moduleLazy,
                        is_greedy: true,
                        is_sandbox: moduleDesciptor.sandbox || false
                    };

                    // wildcard have a low priority
                    // if module was directly named it pass
                    if (!(modules[newModuleName] && !modules[newModuleName].is_greedy)) {
                        modules[newModuleName] = moduleData;
                    }
                }
            });
        } else {
            // normal name
            // "name": "name.js"
            modules[moduleName] = {
                name: moduleName,
                path: fs.realpathSync(path + modulePath),
                is_lazy: moduleLazy,
                is_greedy: false,
                is_sandbox: moduleDesciptor.sandbox || false
            };
        }
    }

    return modules;
};

/**
 * Collecting sandboxed modules using merged config
 *
 * @param modulesStruct
 *
 * @returns {Object}
 */
LmdBuilder.prototype.getSandboxedModules = function (modulesStruct, config) {
    // TODO(azproduction) Backward capability
    var result = config.sandbox || {};
    for (var moduleName in modulesStruct) {
        if (modulesStruct[moduleName].is_sandbox) {
            result[moduleName] = true;
        }
    }

    return result;
};

/**
 * Main builder
 */
LmdBuilder.prototype.build = function () {
    var config = this.tryExtend(JSON.parse(fs.readFileSync(this.configFile, 'utf8'))),
        lazy = typeof config.lazy === "undefined" ? true : config.lazy,
        mainModuleName = config.main,
        pack = lazy ? true : typeof config.pack === "undefined" ? true : config.pack,
        moduleContent,
        lmdModules = [],
        sandbox,
        lmdMain,
        lmdFile,
        isJson,
        module,
        modules;

    if (config.modules) {
        modules = this.collectModules(config);
        // build modules string
        for (var index in modules) {
            module = modules[index];
            moduleContent = fs.readFileSync(module.path, 'utf8');

            try {
                JSON.parse(moduleContent);
                isJson = true;
            } catch (e) {
                isJson = false;
            }

            if (!isJson) {
                moduleContent = this.tryWrap(moduleContent);
            }

            if (!isJson && pack) {
                moduleContent = this.compress(moduleContent);
            }

            if (module.name === mainModuleName) {
                lmdMain = moduleContent;
            } else {
                if (!isJson && module.is_lazy) {
                    moduleContent = this.escape('(' + moduleContent.replace(/^function[^\(]*/, 'function') + ')' );
                }
                lmdModules.push(this.escape(module.name) + ': ' + moduleContent);
            }
        }

        sandbox = this.getSandboxedModules(modules, config);
        lmdFile = this.render(lmdModules, lmdMain, pack, config.global, sandbox);

        if (this.outputFile) {
            fs.writeFileSync(this.outputFile, lmdFile,'utf8')
        } else {
            process.stdout.write(lmdFile);
        }
    }
};

module.exports = LmdBuilder;<commit_msg>fixed inline LmdBuilder example<commit_after>/**
 * LMD Builder
 *
 * @author  Mikhail Davydov
 * @licence MIT
 */

var LMD_JS_SRC_PATH = __dirname + '/../src/',
    fs = require('fs'),
    parser = require("uglify-js").parser,
    uglify = require("uglify-js").uglify;

/**
 * LmdBuilder
 *
 * @constructor
 *
 * @param {Object} data
 * @param {Object} data.config               path to config file
 * @param {Object} [data.output]             result file or STDOUT
 * @param {Object} [data.version='lmd_tiny'] lmd version
 *
 * @example
 *      new LmdBuilder({
 *          config: "config.json",
 *          output: "result.js", // optional
 *          version: "lmd_tiny" // optional - default=lmd_tiny
 *      });
 */
var LmdBuilder = function (data) {
    this.configFile = data.config;
    this.outputFile = data.output;
    this.lmdVersionName = data.version || 'lmd_tiny';

    if (!LmdBuilder.versionBuilder[this.lmdVersionName]) {
        throw new Error('No such LMD version - ' + this.lmdVersionName);
    }

    this.configDir = fs.realpathSync(this.configFile);
    this.configDir = this.configDir.split('/');
    this.configDir.pop();
    this.configDir = this.configDir.join('/');
    if (this.configure()) {
        this.build();
    }
};

/**
 * LMD builders templates
 *
 * @namespace
 */
LmdBuilder.versionBuilder = {
    'lmd_min': function (data) {
        return data.lmd_js + '(' + data.global + ',' + data.sandboxed_modules + ')(' + data.lmd_modules + ')(' + data.lmd_main + ')';
    },

    'lmd_tiny': function (data) {
        return data.lmd_js + '(' + data.global + ',' + data.lmd_main + ',' + data.lmd_modules + ',' + data.sandboxed_modules + ')';
    }
};

/**
 * Compress code using UglifyJS
 *
 * @param {String} code
 *
 * @returns {String} compressed code
 */
LmdBuilder.prototype.compress = function (code) {
    var ast = parser.parse(code);
    ast = uglify.ast_mangle(ast);
    ast = uglify.ast_squeeze(ast);

    return uglify.gen_code(ast);
};

/**
 * Wrapper for plain files
 *
 * @param {String} code
 *
 * @returns {String} wrapped code
 */
LmdBuilder.prototype.tryWrap = function (code) {
    try {
        var ast = parser.parse(code);
    } catch (e) {
        throw new Error('parse error on ' + code);
    }

    // ["toplevel",[["defun","depA",["require"],[]]]]
    if (ast && ast.length === 2 &&
        ast[1] && ast[1].length === 1 &&
        ast[1][0][0] === "defun"
        ) {
        return code;
    }

    // ["toplevel",[["stat",["function",null,["require"],[]]]]]
    if (ast && ast.length === 2 &&
        ast[1] && ast[1].length === 1 &&
        ast[1][0][0] === "stat" &&
        ast[1][0][1] &&
        ast[1][0][1][0] === "function"
        ) {
        return code;
    }

    return '(function (require, exports, module) { /* wrapped by builder */\n' + code + '\n})';
};

/**
 * JSON escaper
 *
 * @param file
 */
LmdBuilder.prototype.escape = function (file) {
    return JSON.stringify(file);
};

/**
 * Module code renderer
 *
 * @param {String[]} lmd_modules
 * @param {String}   lmd_main
 * @param {Boolean}  pack
 * @param {String}   globalObject
 * @param {String[]} sandboxed_modules
 *
 * @returns {String}
 */
LmdBuilder.prototype.render = function (lmd_modules, lmd_main, pack, globalObject, sandboxed_modules) {
    globalObject = globalObject || 'this';
    sandboxed_modules = JSON.stringify(sandboxed_modules || {});
    var lmd_js = fs.readFileSync(LMD_JS_SRC_PATH + this.lmdVersionName + '.js', 'utf8'),
        result;

    lmd_modules = '{\n' + lmd_modules.join(',\n') + '\n}';

    result = LmdBuilder.versionBuilder[this.lmdVersionName]({
        lmd_js: lmd_js,
        global: globalObject,
        lmd_main: lmd_main,
        lmd_modules: lmd_modules,
        sandboxed_modules: sandboxed_modules
    });

    if (pack) {
        result = this.compress(result);
    }

    return result;
};

/**
 * Performs configuration
 */
LmdBuilder.prototype.configure = function () {
    if (!this.configFile) {
        console.log('lmd usage:\n\t    lmd config.lmd.json [output.lmd.js] [lmd_min|lmd_tiny]');
        return false;
    }
    return true;
};

/**
 * Extracts file path parameters
 *
 * @param file
 */
LmdBuilder.prototype.extract = function (file) {
    file = file.split('/');
    return {
        file: file.pop(),
        path: (file.length ? file.join('/') + '/' : '')
    };
};

/**
 * Config files deep merge
 *
 * @param {Object} left
 * @param {Object} right
 */
LmdBuilder.prototype.deepDestructableMerge = function (left, right) {
    for (var prop in right) {
        if (right.hasOwnProperty(prop))  {
            if (typeof left[prop] === "object") {
                this.deepDestructableMerge(left[prop], right[prop]);
            } else {
                left[prop] = right[prop];
            }
        }
    }
    return left;
};

/**
 * Merges all config files in module's lineage
 *
 * @param config
 */
LmdBuilder.prototype.tryExtend = function (config) {
    config = config || {};
    if (typeof config.extends !== "string") {
        return config;
    }
    var parentConfig = this.tryExtend(JSON.parse(fs.readFileSync(this.configDir + '/' + config.extends, 'utf8')));

    return this.deepDestructableMerge(parentConfig, config);
};

/**
 * @name LmdModuleStruct
 * @class
 *
 * @field {String}  name       module name
 * @field {String}  path       full path to module
 * @field {Boolean} is_lazy    is lazy module?
 * @field {Boolean} is_sandbox is module sandboxed?
 * @field {Boolean} is_greedy  module is collected using wildcard
 */

/**
 * Collecting module using merged config
 *
 * @param config
 *
 * @returns {Object}
 */
LmdBuilder.prototype.collectModules = function (config) {
    var IS_HAS_WILD_CARD = /\*/;

    var modules = {},
        globalLazy = typeof config.lazy === "undefined" ? true : config.lazy,
        moduleLazy = false,
        moduleName,
        modulePath,
        descriptor,
        moduleDesciptor,
        wildcardRegex,
        moduleData,
        path =  config.path || '';

    if (path[0] !== '/') { // non-absolute
        path = this.configDir + '/' + path;
    }

    // grep paths
    for (moduleName in config.modules) {
        moduleDesciptor = config.modules[moduleName];
        // case "moduleName": "path/to/module.js"
        if (typeof moduleDesciptor === "string") {
            modulePath = moduleDesciptor;
            moduleLazy = globalLazy;
        } else { // case "moduleName": {"path": "path/to/module.js", "lazy": false}
            modulePath = moduleDesciptor.path;
            moduleLazy = typeof moduleDesciptor.lazy === "undefined" ? globalLazy : moduleDesciptor.lazy;
        }
        // its a wildcard
        // "*": "*.js" or "*_pewpew": "*.ru.json" or "ololo": "*.js"
        if (IS_HAS_WILD_CARD.test(modulePath)) {
            descriptor = this.extract(modulePath);
            wildcardRegex = new RegExp("^" + descriptor.file.replace(/\*/g, "(\\w+)") + "$");
            fs.readdirSync(path + descriptor.path).forEach(function (fileName) {
                var match = fileName.match(wildcardRegex),
                    newModuleName;

                if (match) {
                    match.shift();

                    // Modify a module name
                    match.forEach(function (replacement) {
                        newModuleName = moduleName.replace('*', replacement);
                    });

                    moduleData = {
                        name: newModuleName,
                        path: fs.realpathSync(path + descriptor.path + fileName),
                        is_lazy: moduleLazy,
                        is_greedy: true,
                        is_sandbox: moduleDesciptor.sandbox || false
                    };

                    // wildcard have a low priority
                    // if module was directly named it pass
                    if (!(modules[newModuleName] && !modules[newModuleName].is_greedy)) {
                        modules[newModuleName] = moduleData;
                    }
                }
            });
        } else {
            // normal name
            // "name": "name.js"
            modules[moduleName] = {
                name: moduleName,
                path: fs.realpathSync(path + modulePath),
                is_lazy: moduleLazy,
                is_greedy: false,
                is_sandbox: moduleDesciptor.sandbox || false
            };
        }
    }

    return modules;
};

/**
 * Collecting sandboxed modules using merged config
 *
 * @param modulesStruct
 *
 * @returns {Object}
 */
LmdBuilder.prototype.getSandboxedModules = function (modulesStruct, config) {
    // TODO(azproduction) Backward capability
    var result = config.sandbox || {};
    for (var moduleName in modulesStruct) {
        if (modulesStruct[moduleName].is_sandbox) {
            result[moduleName] = true;
        }
    }

    return result;
};

/**
 * Main builder
 */
LmdBuilder.prototype.build = function () {
    var config = this.tryExtend(JSON.parse(fs.readFileSync(this.configFile, 'utf8'))),
        lazy = typeof config.lazy === "undefined" ? true : config.lazy,
        mainModuleName = config.main,
        pack = lazy ? true : typeof config.pack === "undefined" ? true : config.pack,
        moduleContent,
        lmdModules = [],
        sandbox,
        lmdMain,
        lmdFile,
        isJson,
        module,
        modules;

    if (config.modules) {
        modules = this.collectModules(config);
        // build modules string
        for (var index in modules) {
            module = modules[index];
            moduleContent = fs.readFileSync(module.path, 'utf8');

            try {
                JSON.parse(moduleContent);
                isJson = true;
            } catch (e) {
                isJson = false;
            }

            if (!isJson) {
                moduleContent = this.tryWrap(moduleContent);
            }

            if (!isJson && pack) {
                moduleContent = this.compress(moduleContent);
            }

            if (module.name === mainModuleName) {
                lmdMain = moduleContent;
            } else {
                if (!isJson && module.is_lazy) {
                    moduleContent = this.escape('(' + moduleContent.replace(/^function[^\(]*/, 'function') + ')' );
                }
                lmdModules.push(this.escape(module.name) + ': ' + moduleContent);
            }
        }

        sandbox = this.getSandboxedModules(modules, config);
        lmdFile = this.render(lmdModules, lmdMain, pack, config.global, sandbox);

        if (this.outputFile) {
            fs.writeFileSync(this.outputFile, lmdFile,'utf8')
        } else {
            process.stdout.write(lmdFile);
        }
    }
};

module.exports = LmdBuilder;<|endoftext|>


<commit_before>var router = require('express').Router();
var sockets = require('../sockets');
var Workspace = require('../models/workspace');
var defaultWorkspace = require('../models/defaultWorkspace');

function generateUUID() {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random()*16)%16 | 0;
    d = Math.floor(d/16);
    return (c=='x' ? r : (r&0x3|0x8)).toString(16);
  });
  return uuid;
};

router.post('/create', function(req, res, next) {
  // Compute real hash for new workspace here}
  var hash = generateUUID();
  var newWorkspace = Object.assign(defaultWorkspace);
  newWorkspace.id = hash;
  Workspace.create(newWorkspace, function (err, workspace) {
    if (err) {
      return console.log(err);
    }

    res.json({hash: hash, workspace: workspace});
  });
});

router.post('/load', function(req, res, next) {
  Workspace.findOne({'id': req.body.id}, function(err, workspace) {
    if (err) {
      return console.error(err);
    }

    console.log(workspace);
    res.json({'workspace': workspace});
  })
});

module.exports = router;

<commit_msg>Fixed a syntax issue Keenan was running into on master<commit_after>var router = require('express').Router();
var sockets = require('../sockets');
var Workspace = require('../models/workspace');
var defaultWorkspace = require('../models/defaultWorkspace');

function generateUUID() {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random()*16)%16 | 0;
    d = Math.floor(d/16);
    return (c=='x' ? r : (r&0x3|0x8)).toString(16);
  });
  return uuid;
};

router.post('/create', function(req, res, next) {
  // Compute real hash for new workspace here}
  var hash = generateUUID();
  var newWorkspace = defaultWorkspace;
  newWorkspace.id = hash;
  Workspace.create(newWorkspace, function (err, workspace) {
    if (err) {
      return console.log(err);
    }

    res.json({hash: hash, workspace: workspace});
  });
});

router.post('/load', function(req, res, next) {
  Workspace.findOne({'id': req.body.id}, function(err, workspace) {
    if (err) {
      return console.error(err);
    }

    console.log(workspace);
    res.json({'workspace': workspace});
  })
});

module.exports = router;

<|endoftext|>


<commit_before>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    neo4j = require('node-neo4j');

function del(req, res, next, type) {
    if(type == "users") {
        var username = req.authorization.basic.username
        console.log('DELETE USER');
        console.log('DELETE ' + username);
        console.log('parameters supplied');
        var url = 'http://localhost:5984/users/' + username,
            db = new neo4j('http://localhost:7474');
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if user is not found will send 404 error
            if(response.statusCode == 404) {
                return next(new restify.BadRequestError('User Not Found'));
            };
            if(response.statusCode == 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev,
                    nodeid = body.nodeid;
                console.log(rev);
                console.log(nodeid);
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if(err) throw err;
                    if(results.data.length == 0) {
                        db.deleteNode(nodeid, function(err, node) {
                            if(err) throw err;
                            if(node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function(err, response) {
                                    if(err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted User!");
                                    res.send("Deleted User!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function(item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function(err, relationship) {
                                if(err) throw err;
                                if(relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if(i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if(err) throw err;
                                            if(node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function(err, response) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted User!");
                                                    res.send("Deleted User!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                })
            };
        });
    } else if(type == "business") {
        var businessName = req.authorization.basic.username
        console.log('DELETE BUSINESS');
        console.log('DELETE ' + businessName);
        validateHTTP.validateHTTP(req, res, next, "business");
        console.log('parameters supplied');
        var url = 'http://localhost:5984/business/' + businessName;
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if business is not found will send 404 error
            if(response.statusCode == 404) {
                return next(new restify.BadRequestError('Business Not Found'));
            };
            if(response.statusCode == 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev;
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if(err) throw err;
                    if(results.data.length == 0) {
                        db.deleteNode(nodeid, function(err, node) {
                            if(err) throw err;
                            if(node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function(err, response) {
                                    if(err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted Business!");
                                    res.send("Deleted Business!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function(item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function(err, relationship) {
                                if(err) throw err;
                                if(relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if(i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if(err) throw err;
                                            if(node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function(err, response) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted Bsuiness!");
                                                    res.send("Deleted Business!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                });
            };
        });
    } else {
        console.log("Error, Invalid Type!");
    };
};
module.exports.del = del;<commit_msg>del.js: code clean<commit_after>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    neo4j = require('node-neo4j');

function del(req, res, next, type) {
    if (type == "users") {
        var username = req.authorization.basic.username
        console.log('DELETE USER');
        console.log('DELETE ' + username);
        console.log('parameters supplied');
        var url = 'http://localhost:5984/users/' + username,
            db = new neo4j('http://localhost:7474');
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if user is not found will send 404 error
            if (response.statusCode == 404) {
                return next(new restify.BadRequestError('User Not Found'));
            };
            if (response.statusCode == 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev,
                    nodeid = body.nodeid;
                console.log(rev);
                console.log(nodeid);
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if (err) throw err;
                    if (results.data.length == 0) {
                        db.deleteNode(nodeid, function(err, node) {
                            if (err) throw err;
                            if (node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function(err, response) {
                                    if (err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted User!");
                                    res.send("Deleted User!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function(item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function (err, relationship) {
                                if (err) throw err;
                                if (relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if (i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if (err) throw err;
                                            if (node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function (err, response) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted User!");
                                                    res.send("Deleted User!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                })
            };
        });
    } else if (type == "business") {
        var businessName = req.authorization.basic.username
        console.log('DELETE BUSINESS');
        console.log('DELETE ' + businessName);
        validateHTTP.validateHTTP(req, res, next, "business");
        console.log('parameters supplied');
        var url = 'http://localhost:5984/business/' + businessName;
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if business is not found will send 404 error
            if (response.statusCode == 404) {
                return next(new restify.BadRequestError('Business Not Found'));
            };
            if (response.statusCode == 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev;
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if (err) throw err;
                    if (results.data.length == 0) {
                        db.deleteNode(nodeid, function (err, node) {
                            if (err) throw err;
                            if (node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function (err, response) {
                                    if (err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted Business!");
                                    res.send("Deleted Business!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function (item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function (err, relationship) {
                                if (err) throw err;
                                if (relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if (i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if (err) throw err;
                                            if (node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function(err, response) {
                                                    if (err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted Bsuiness!");
                                                    res.send("Deleted Business!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                });
            };
        });
    } else {
        console.log("Error, Invalid Type!");
    };
};
module.exports.del = del;<|endoftext|>


<commit_before>var audioContext = new AudioContext()
var analyser = audioContext.createAnalyser()
analyser.fftSize = 4096
var biquadFilter = audioContext.createBiquadFilter()
var audioBuffer = new Float32Array(analyser.fftSize)
var frequencyData = new Uint8Array(analyser.frequencyBinCount)
var waveform = new Waveform('#waveform')
var spectrogram = new Spectrogram('#spectrogram')
var pitchDetector = new (Module().PitchDetector)('default', analyser.fftSize, 1, audioContext.sampleRate)
var $pitch = document.querySelector('#pitch')

biquadFilter.type = 'lowpass'
biquadFilter.frequency.value = 440

navigator.mediaDevices.getUserMedia({audio: true}).then(function (stream) {
  audioContext.createMediaStreamSource(stream).connect(biquadFilter)
  biquadFilter.connect(analyser)
})

function noteFromFrequency(frequency) {
  var noteNum = 12 * (Math.log(frequency / 440) / Math.log(2))
  return Math.round(noteNum) + 69
}

function frequencyFromNote(note) {
  return 440 * Math.pow(2, (note - 69) / 12)
}

function centsDiffFromFrequency(frequency, note) {
  return Math.floor(1200 * Math.log(frequency / frequencyFromNote(note)) / Math.log(2))
}

var noteStrings = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']

process()
function process() {
  requestAnimationFrame(process)
  analyser.getFloatTimeDomainData(audioBuffer)
  analyser.getByteFrequencyData(frequencyData)
  waveform.update(audioBuffer)
  spectrogram.update(frequencyData)

  var frequency = pitchDetector.getPitch(audioBuffer)
  if (frequency) {
    var note = noteFromFrequency(frequency)
    var noteString = noteStrings[note % 12] || ''
    var centsDiff = centsDiffFromFrequency(frequency, note)
    $pitch.innerHTML = noteString + ', ' + centsDiff + ' cents, ' + frequency.toFixed(1) + ' Hz'
  }
}<commit_msg>update: use default fft size<commit_after>var audioContext = new AudioContext()
var analyser = audioContext.createAnalyser()
var biquadFilter = audioContext.createBiquadFilter()
var audioBuffer = new Float32Array(analyser.fftSize)
var frequencyData = new Uint8Array(analyser.frequencyBinCount)
var waveform = new Waveform('#waveform')
var spectrogram = new Spectrogram('#spectrogram')
var pitchDetector = new (Module().PitchDetector)('default', analyser.fftSize, 1, audioContext.sampleRate)
var $pitch = document.querySelector('#pitch')

biquadFilter.type = 'lowpass'
biquadFilter.frequency.value = 440

navigator.mediaDevices.getUserMedia({audio: true}).then(function (stream) {
  audioContext.createMediaStreamSource(stream).connect(biquadFilter)
  biquadFilter.connect(analyser)
})

function noteFromFrequency(frequency) {
  var noteNum = 12 * (Math.log(frequency / 440) / Math.log(2))
  return Math.round(noteNum) + 69
}

function frequencyFromNote(note) {
  return 440 * Math.pow(2, (note - 69) / 12)
}

function centsDiffFromFrequency(frequency, note) {
  return Math.floor(1200 * Math.log(frequency / frequencyFromNote(note)) / Math.log(2))
}

var noteStrings = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']

process()
function process() {
  requestAnimationFrame(process)
  analyser.getFloatTimeDomainData(audioBuffer)
  analyser.getByteFrequencyData(frequencyData)
  waveform.update(audioBuffer)
  spectrogram.update(frequencyData)

  var frequency = pitchDetector.getPitch(audioBuffer)
  if (frequency) {
    var note = noteFromFrequency(frequency)
    var noteString = noteStrings[note % 12] || ''
    var centsDiff = centsDiffFromFrequency(frequency, note)
    $pitch.innerHTML = noteString + ', ' + centsDiff + ' cents, ' + frequency.toFixed(1) + ' Hz'
  }
}<|endoftext|>


<commit_before>'use strict';

function onGoogleReady() {
    angular.bootstrap(document.getElementById("map"), ['onsApp']);
}

//var surnameServiceDecorator = function($delegate) {
//
//    var addSurname = function() {
//        var result = $delegate.addSurname();
//        console.log('log add surnames');
//        return result;
//    };
//
//    $delegate.addSurname = addSurname;
//    return $delegate;
//};

var onsApp = angular.module('onsApp', ['ngRoute', 'onsControllers', 'onsServices', 'ui.bootstrap', 'ui.grid', 'ui.grid.pagination', 'angularMoment', 'ui.map'])
    // allow DI for use in controllers, unit tests
    .constant('_', window._)
    .constant('baseUrl', 'http://localhost:8000/app/')
    .constant('baseRestUrl', 'http://localhost:8080/')
    // use in views, ng-repeat="x in _.range(3)"
    .config(function($provide){
        $provide.decorator('surnameService', function($delegate) {
            var swap = function(originalFn) {
              return function() {
                  var args = [].slice.call(arguments);
                  console.log('add surnamearguments', args);
                  return originalFn.apply(null, args);
              };
            };
            $delegate.addSurname = swap($delegate.addSurname);
            return $delegate;
        });
    })
    .run(function ($rootScope) {
        $rootScope._ = window._;

// register the interceptor as a service

    });

onsApp.directive('personList', function() {
        return {
            controller: function($scope) {

                $scope.delete = function(person) {
                    $scope.personsForm.persons.splice($scope.persons.indexOf(person), 1);
                }
            },
            restrict: 'E',
            replace: true,
            scope: {
                persons: '=',
                orderProp: '='
            },
            templateUrl: 'personList.html'
            //  template: "hello {{orderProp}}"
        };
    }
);

onsApp.directive('formHelper', function() {
    return {
        restrict : 'A',
        require: 'form',
        link: function (scope, element, attrs, form) {
            scope[attrs.formHelper] = {
                isFormValid: function() {
                    return form.$valid;
                },
                checkFormValid: function() {
                    var checkAllRequired = function (){
                        // set the form to dirty to enable invalid indicators
                        if(angular.isDefined(form)) {
                            angular.forEach(form.$error.required, function (required) {
                                required.$setTouched();
                            });
                        }
                    };
                    checkAllRequired(form);
                    return angular.isDefined(form) && !form.$invalid;
                },
                showValidationMessageFor: function(fieldName) {
                    // only show message if the field is invalid and has been changed
                    // (otherwise you'll get the message as soon as you see the form)
                    return form[fieldName].$invalid && form[fieldName].$touched;
                }
            };
        }
    };
});

onsApp.directive('surnameList', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                surnames: '='
            },
            templateUrl: 'surnameList.html'
        };
    }
);

onsApp.directive('locationList', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                locations: '='
            },
            templateUrl: 'locationList.html'
        };
    }
);

onsApp.directive('showPersonDetails', function($location) {
    return function link(scope, element, attrs) {
        element.on('click', function() {
            $location.url('/persons/' + attrs.showPersonDetails);
        });
    }
});

onsApp.directive('sortName', function() {
    return {
        link: function(scope, elm, attrs) {
            elm.on('click', function() {
                if (attrs.sortName != scope.orderProp) {
                    scope.orderProp = attrs.sortName
                }
                scope.$apply();
            });
        }
    }
});

function uppercase(str) {
    if(angular.isString(str)) {
        return str.toUpperCase();
    }
    else {
        return str;
    }
}

onsApp.filter('bla', function() {
    return function(arr) {
        var result = [];
        if (angular.isDefined(arr)) {
            for (var i = 0; i < arr.length; ++i) {
                var personDetails = arr[i];
                var newPersonFirstName =  uppercase(personDetails.person.firstName);
                personDetails.person.firstName = newPersonFirstName;
                result.push(personDetails);
            }
        }
        return result;
    };
});

onsApp.filter('locationsForCensusCountry', function() {
        return function(arr, censusId) {
        var result = [];
        if (angular.isDefined(arr)) {
            for (var i = 0; i < arr.length; ++i) {
                var personDetails = arr[i];
                var newPersonFirstName =  uppercase(personDetails.person.firstName);
                personDetails.person.firstName = newPersonFirstName;
                result.push(personDetails);
            }
        }
        return result;
    };
});

onsApp.filter('capitalize', function() {
    return function(input, all) {
        return (!!input) ? input.replace(/([^\W_]+[^\s-]*) */g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) : '';
    }
});

onsApp.filter('males', function() {
    return function(arr, isMale) {
        var result = [];
        if (angular.isDefined(arr)) {
            for (var i = 0; i < arr.length; ++i) {
                var personDetails = arr[i];
                if (isMale) {
                    if (personDetails.person.gender == 1) {
                        result.push(personDetails);
                    }
                } else {
                    if (personDetails.person.gender == 0) {
                        result.push(personDetails);
                    }
                }
            }
        }
        return result;
    };
});

onsApp.directive('personForm', function() {
    return {
        controller: function($scope, $attrs) {
            $scope.person = {};
            $scope.clickStatus = false;
            if($attrs.controller) {
                $scope.$parent[$attrs.controller] = this;
            }

            $scope.submit = function() {
                if ($scope.addPersonForm.$valid) {
                    $scope.addPerson({person: $scope.person});
                } else {
                    alert("please fill in all details");
                }
            };

            this.clear = function() {
                $scope.person = {};
                $scope.addPersonForm.$setPristine();
            }

            $scope.today = function() {
                $scope.person.birthDate = new Date();
            };
            $scope.today();

            $scope.clear = function () {
                $scope.person.birthDate = null;
            };

            // Disable weekend selection
            $scope.disabled = function(date, mode) {
                return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
            };

//            $scope.toggleMin = function() {
//                $scope.minDate = $scope.minDate ? null : new Date();
//            };
//            $scope.toggleMin();

            $scope.open = function($event) {
                $event.preventDefault();
                $event.stopPropagation();

                $scope.opened = true;
            };

            $scope.dateOptions = {
                formatYear: 'yy',
                startingDay: 1
            };

            $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
            $scope.format = $scope.formats[0];

        },
        restrict: 'E',
        replace: true,
        scope: {
            addPerson: '&',
            fathers: '=',
            surnames: '=',
            mothers: '='

        },
        templateUrl: 'personForm.html'
    };
});

onsApp.directive('locationForm', function() {
    return {
        controller: function($scope, $attrs) {
            $scope.location = {};
            $scope.clickStatus = false;
            if($attrs.controller) {
                $scope.$parent[$attrs.controller] = this;
            }

            $scope.submit = function() {
                if ($scope.addLocationForm.$valid) {
                    $scope.addLocation({location: $scope.location});
                } else {
                    alert("please fill in all details");
                }
            };

            this.clear = function() {
                $scope.location = {};
                $scope.addLocationForm.$setPristine();
            }
        },
        restrict: 'E',
        replace: true,
        scope: {
            addLocation: '&',
            countries: '='
        },
        templateUrl: 'locationForm.html'
    };
});

onsApp.config(function($routeProvider, $provide, $httpProvider) {
    $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'HomeCtrl'});
//    $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'navigation'});
    $routeProvider.when('/trees', {templateUrl: 'partials/treeList.html', controller: 'TreeListCtrl'});
    $routeProvider.when('/trees/:treeId', {templateUrl: 'partials/treeDetails.html', controller: 'TreeDetailsCtrl'});
    $routeProvider.when('/persons', {templateUrl: 'partials/personList.html', controller: 'PersonListCtrl'});
    $routeProvider.when('/persons/:personId', {templateUrl: 'partials/personDetails.html', controller: 'PersonDetailsCtrl'});
    $routeProvider.when('/censuses', {templateUrl: 'partials/censusList.html', controller: 'CensusListCtrl'});
    $routeProvider.when('/censuses  /:censusId', {templateUrl: 'partials/censusDetails.html', controller: 'CensusDetailsCtrl'});
    $routeProvider.when('/surnames', {templateUrl: 'partials/surnameList.html', controller: 'SurnameListCtrl'});
    $routeProvider.when('/surnames/:surnameId', {templateUrl: 'partials/surnameDetails.html', controller: 'SurnameDetailsCtrl'});
    $routeProvider.when('/locations', {templateUrl: 'partials/locationList.html', controller: 'LocationListCtrl'});
    $routeProvider.when('/locations/:locationId', {templateUrl: 'partials/locationDetails.html', controller: 'LocationDetailsCtrl'});
    $routeProvider.otherwise({redirectTo: '/home'});

//    $httpProvider.defaults.withCredentials = true;
//    delete $httpProvider.defaults.headers.common['X-Requested-With'];
//    $httpProvider.defaults.headers.get = {
//    //    'Origin' : 'http://localhost:8000',
//        'Access-Control-Allow-Credentials': true,
//        'Access-Control-Allow-Origin': 'http://localhost:8000'
//    };
//
//    $httpProvider.defaults.headers.options = {
//        'Access-Control-Request-Headers': 'Access-Control-Allow-Credentials , Access-Control-Allow-Origin',
//        'Access-Control-Allow-Origin': 'http://localhost:8000'
//    };

//    $provide.factory('myHttpInterceptor', function($q, $location) {
//        return {
//            // optional method
//            'response': function(response) {
//                // do something on success
//                console.log(response);
//                if (response.status === 401 || response.status === 302) {
//
//                    $location.path('index.html#/login')
//                }
//                return response;
//            },
//
//            // optional method
//            'responseError': function(rejection) {
//                console.log(rejection);
//                // do something on error
////                if (canRecover(rejection)) {
////                    return responseOrNewPromise
////                }
////                if (rejection.status === 302 ) {
////                    console.log('302 found');
////                }
////
////                if (rejection.status === 0) {
////                    $location.path("/login");
////                }
//
//                if (rejection.status === 401 || rejection.status === 302) {
//                    $location.path('index.html#/login')
//                }
//
//                return $q.reject(rejection);
//            }
//        };
//    });
//
//    $httpProvider.interceptors.push('myHttpInterceptor');

});

onsApp.filter('personUrl', function() {
    return function(person) {
        return '#/persons/' + person.id;
    }
});

onsApp.filter('capitalize', function() {
    return function(surname) {
        var surnameMap = [];
        surnameMap['etherton'] = 'ETHERTON';
        surnameMap['wilkinson'] = 'WILKINSON';
        return surnameMap[surname];
    }
});

<commit_msg>added config<commit_after>'use strict';

function onGoogleReady() {
    angular.bootstrap(document.getElementById("map"), ['onsApp']);
}

//var surnameServiceDecorator = function($delegate) {
//
//    var addSurname = function() {
//        var result = $delegate.addSurname();
//        console.log('log add surnames');
//        return result;
//    };
//
//    $delegate.addSurname = addSurname;
//    return $delegate;
//};

var onsApp = angular.module('onsApp', ['ngRoute', 'onsControllers', 'onsServices', 'ui.bootstrap', 'ui.grid', 'ui.grid.pagination', 'angularMoment', 'ui.map'])
    // allow DI for use in controllers, unit tests
    .constant('_', window._)
    .constant('baseUrl', 'http://localhost:8000/app/')
    .constant('baseRestUrl', 'http://localhost:8080/')
    // use in views, ng-repeat="x in _.range(3)"
    .config(function($provide){

//        var surnameDecorator = function($delegate) {
//            var addSurname = function(data) {
//              var result = $delegate.addSurname(data);
//              return result;
//            };
//            return $delegate;
//        };

        $provide.decorator('surnameService', function($delegate) {
            var swap = function(originalFn) {
                return function() {
                    var args = [].slice.call(arguments);
                    console.log('add surnamearguments', args);
                    return originalFn.apply(null, args);
                };
            };
            $delegate.addSurname = swap($delegate.addSurname);
            return $delegate;
        });
//        $provide.decorator('surnameService', function($delegate) {
//            var swap = function(originalFn) {
//              return function() {
//                  var args = [].slice.call(arguments);
//                  console.log('add surnamearguments', args);
//                  return originalFn.apply(null, args);
//              };
//            };
//            $delegate.addSurname = swap($delegate.addSurname);
//            return $delegate;
//        });
    })
    .run(function ($rootScope) {
        $rootScope._ = window._;

// register the interceptor as a service

    });

onsApp.directive('personList', function() {
        return {
            controller: function($scope) {

                $scope.delete = function(person) {
                    $scope.personsForm.persons.splice($scope.persons.indexOf(person), 1);
                }
            },
            restrict: 'E',
            replace: true,
            scope: {
                persons: '=',
                orderProp: '='
            },
            templateUrl: 'personList.html'
            //  template: "hello {{orderProp}}"
        };
    }
);

onsApp.directive('formHelper', function() {
    return {
        restrict : 'A',
        require: 'form',
        link: function (scope, element, attrs, form) {
            scope[attrs.formHelper] = {
                isFormValid: function() {
                    return form.$valid;
                },
                checkFormValid: function() {
                    var checkAllRequired = function (){
                        // set the form to dirty to enable invalid indicators
                        if(angular.isDefined(form)) {
                            angular.forEach(form.$error.required, function (required) {
                                required.$setTouched();
                            });
                        }
                    };
                    checkAllRequired(form);
                    return angular.isDefined(form) && !form.$invalid;
                },
                showValidationMessageFor: function(fieldName) {
                    // only show message if the field is invalid and has been changed
                    // (otherwise you'll get the message as soon as you see the form)
                    return form[fieldName].$invalid && form[fieldName].$touched;
                }
            };
        }
    };
});

onsApp.directive('surnameList', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                surnames: '='
            },
            templateUrl: 'surnameList.html'
        };
    }
);

onsApp.directive('locationList', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                locations: '='
            },
            templateUrl: 'locationList.html'
        };
    }
);

onsApp.directive('showPersonDetails', function($location) {
    return function link(scope, element, attrs) {
        element.on('click', function() {
            $location.url('/persons/' + attrs.showPersonDetails);
        });
    }
});

onsApp.directive('sortName', function() {
    return {
        link: function(scope, elm, attrs) {
            elm.on('click', function() {
                if (attrs.sortName != scope.orderProp) {
                    scope.orderProp = attrs.sortName
                }
                scope.$apply();
            });
        }
    }
});

function uppercase(str) {
    if(angular.isString(str)) {
        return str.toUpperCase();
    }
    else {
        return str;
    }
}

onsApp.filter('bla', function() {
    return function(arr) {
        var result = [];
        if (angular.isDefined(arr)) {
            for (var i = 0; i < arr.length; ++i) {
                var personDetails = arr[i];
                var newPersonFirstName =  uppercase(personDetails.person.firstName);
                personDetails.person.firstName = newPersonFirstName;
                result.push(personDetails);
            }
        }
        return result;
    };
});

onsApp.filter('locationsForCensusCountry', function() {
        return function(arr, censusId) {
        var result = [];
        if (angular.isDefined(arr)) {
            for (var i = 0; i < arr.length; ++i) {
                var personDetails = arr[i];
                var newPersonFirstName =  uppercase(personDetails.person.firstName);
                personDetails.person.firstName = newPersonFirstName;
                result.push(personDetails);
            }
        }
        return result;
    };
});

onsApp.filter('capitalize', function() {
    return function(input, all) {
        return (!!input) ? input.replace(/([^\W_]+[^\s-]*) */g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) : '';
    }
});

onsApp.filter('males', function() {
    return function(arr, isMale) {
        var result = [];
        if (angular.isDefined(arr)) {
            for (var i = 0; i < arr.length; ++i) {
                var personDetails = arr[i];
                if (isMale) {
                    if (personDetails.person.gender == 1) {
                        result.push(personDetails);
                    }
                } else {
                    if (personDetails.person.gender == 0) {
                        result.push(personDetails);
                    }
                }
            }
        }
        return result;
    };
});

onsApp.directive('personForm', function() {
    return {
        controller: function($scope, $attrs) {
            $scope.person = {};
            $scope.clickStatus = false;
            if($attrs.controller) {
                $scope.$parent[$attrs.controller] = this;
            }

            $scope.submit = function() {
                if ($scope.addPersonForm.$valid) {
                    $scope.addPerson({person: $scope.person});
                } else {
                    alert("please fill in all details");
                }
            };

            this.clear = function() {
                $scope.person = {};
                $scope.addPersonForm.$setPristine();
            }

            $scope.today = function() {
                $scope.person.birthDate = new Date();
            };
            $scope.today();

            $scope.clear = function () {
                $scope.person.birthDate = null;
            };

            // Disable weekend selection
            $scope.disabled = function(date, mode) {
                return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
            };

//            $scope.toggleMin = function() {
//                $scope.minDate = $scope.minDate ? null : new Date();
//            };
//            $scope.toggleMin();

            $scope.open = function($event) {
                $event.preventDefault();
                $event.stopPropagation();

                $scope.opened = true;
            };

            $scope.dateOptions = {
                formatYear: 'yy',
                startingDay: 1
            };

            $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
            $scope.format = $scope.formats[0];

        },
        restrict: 'E',
        replace: true,
        scope: {
            addPerson: '&',
            fathers: '=',
            surnames: '=',
            mothers: '='

        },
        templateUrl: 'personForm.html'
    };
});

onsApp.directive('locationForm', function() {
    return {
        controller: function($scope, $attrs) {
            $scope.location = {};
            $scope.clickStatus = false;
            if($attrs.controller) {
                $scope.$parent[$attrs.controller] = this;
            }

            $scope.submit = function() {
                if ($scope.addLocationForm.$valid) {
                    $scope.addLocation({location: $scope.location});
                } else {
                    alert("please fill in all details");
                }
            };

            this.clear = function() {
                $scope.location = {};
                $scope.addLocationForm.$setPristine();
            }
        },
        restrict: 'E',
        replace: true,
        scope: {
            addLocation: '&',
            countries: '='
        },
        templateUrl: 'locationForm.html'
    };
});

onsApp.config(function($routeProvider, $provide, $httpProvider) {
    $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'HomeCtrl'});
//    $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'navigation'});
    $routeProvider.when('/trees', {templateUrl: 'partials/treeList.html', controller: 'TreeListCtrl'});
    $routeProvider.when('/trees/:treeId', {templateUrl: 'partials/treeDetails.html', controller: 'TreeDetailsCtrl'});
    $routeProvider.when('/persons', {templateUrl: 'partials/personList.html', controller: 'PersonListCtrl'});
    $routeProvider.when('/persons/:personId', {templateUrl: 'partials/personDetails.html', controller: 'PersonDetailsCtrl'});
    $routeProvider.when('/censuses', {templateUrl: 'partials/censusList.html', controller: 'CensusListCtrl'});
    $routeProvider.when('/censuses  /:censusId', {templateUrl: 'partials/censusDetails.html', controller: 'CensusDetailsCtrl'});
    $routeProvider.when('/surnames', {templateUrl: 'partials/surnameList.html', controller: 'SurnameListCtrl'});
    $routeProvider.when('/surnames/:surnameId', {templateUrl: 'partials/surnameDetails.html', controller: 'SurnameDetailsCtrl'});
    $routeProvider.when('/locations', {templateUrl: 'partials/locationList.html', controller: 'LocationListCtrl'});
    $routeProvider.when('/locations/:locationId', {templateUrl: 'partials/locationDetails.html', controller: 'LocationDetailsCtrl'});
    $routeProvider.otherwise({redirectTo: '/home'});

//    $httpProvider.defaults.withCredentials = true;
//    delete $httpProvider.defaults.headers.common['X-Requested-With'];
//    $httpProvider.defaults.headers.get = {
//    //    'Origin' : 'http://localhost:8000',
//        'Access-Control-Allow-Credentials': true,
//        'Access-Control-Allow-Origin': 'http://localhost:8000'
//    };
//
//    $httpProvider.defaults.headers.options = {
//        'Access-Control-Request-Headers': 'Access-Control-Allow-Credentials , Access-Control-Allow-Origin',
//        'Access-Control-Allow-Origin': 'http://localhost:8000'
//    };

//    $provide.factory('myHttpInterceptor', function($q, $location) {
//        return {
//            // optional method
//            'response': function(response) {
//                // do something on success
//                console.log(response);
//                if (response.status === 401 || response.status === 302) {
//
//                    $location.path('index.html#/login')
//                }
//                return response;
//            },
//
//            // optional method
//            'responseError': function(rejection) {
//                console.log(rejection);
//                // do something on error
////                if (canRecover(rejection)) {
////                    return responseOrNewPromise
////                }
////                if (rejection.status === 302 ) {
////                    console.log('302 found');
////                }
////
////                if (rejection.status === 0) {
////                    $location.path("/login");
////                }
//
//                if (rejection.status === 401 || rejection.status === 302) {
//                    $location.path('index.html#/login')
//                }
//
//                return $q.reject(rejection);
//            }
//        };
//    });
//
//    $httpProvider.interceptors.push('myHttpInterceptor');

});

onsApp.filter('personUrl', function() {
    return function(person) {
        return '#/persons/' + person.id;
    }
});

onsApp.filter('capitalize', function() {
    return function(surname) {
        var surnameMap = [];
        surnameMap['etherton'] = 'ETHERTON';
        surnameMap['wilkinson'] = 'WILKINSON';
        return surnameMap[surname];
    }
});

<|endoftext|>


<commit_before>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
*/

function checkForSlows() {
    var slows = 0
    var now = new Date().getTime / 1000;
    for (var x in pending_urls) {
        if ((now - pending_urls[x]) > 1) {
            slows++;
            break
        }
    }
    if (slows == 0) {
        showSpinner(false)
    } else {
        showSpinner(true);
    }
}
// GetAsync: func for getting a doc async with a callback
function GetAsync(theUrl, xstate, callback) {
    var xmlHttp = null;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (pending_urls) {
        pending_urls[theUrl] = new Date().getTime() / 1000;
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send(null);
    xmlHttp.onprogress = function() {
        checkForSlows()
    }
    xmlHttp.onreadystatechange = function(state) {
        if (xmlHttp.readyState == 4) {
            delete pending_urls[theUrl]
        }
        checkForSlows()
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            if (callback) {
                try {
                    callback(JSON.parse(xmlHttp.responseText), xstate);
                } catch (e) {
                    callback(JSON.parse(xmlHttp.responseText), xstate)
                }
            }

        }
        if (xmlHttp.readyState == 4 && xmlHttp.status == 404) {
            alert("404'ed: " + theUrl)
        }
    }
}

function showSpinner(show) {
    var obj = document.getElementById('spinner')
    if (!obj) {
        obj = document.createElement('div')
        obj.setAttribute("id", "spinner")
        obj.innerHTML = "
Loading results, please wait..."
        document.body.appendChild(obj)
    }
    if (show) {
        obj.style.display = "block"
    } else {
        obj.style.display = "none"
    }
}<commit_msg>fix slow counting func<commit_after>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
*/

function checkForSlows() {
    var slows = 0
    var now = new Date().getTime() / 1000;
    for (var x in pending_urls) {
        if ((now - pending_urls[x]) > 1) {
            slows++;
            break
        }
    }
    if (slows == 0) {
        showSpinner(false)
    } else {
        showSpinner(true);
    }
}
// GetAsync: func for getting a doc async with a callback
function GetAsync(theUrl, xstate, callback) {
    var xmlHttp = null;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (pending_urls) {
        pending_urls[theUrl] = new Date().getTime() / 1000;
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send(null);
    xmlHttp.onprogress = function() {
        checkForSlows()
    }
    xmlHttp.onreadystatechange = function(state) {
        if (xmlHttp.readyState == 4) {
            delete pending_urls[theUrl]
        }
        checkForSlows()
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            if (callback) {
                try {
                    callback(JSON.parse(xmlHttp.responseText), xstate);
                } catch (e) {
                    callback(JSON.parse(xmlHttp.responseText), xstate)
                }
            }

        }
        if (xmlHttp.readyState == 4 && xmlHttp.status == 404) {
            alert("404'ed: " + theUrl)
        }
    }
}

function showSpinner(show) {
    var obj = document.getElementById('spinner')
    if (!obj) {
        obj = document.createElement('div')
        obj.setAttribute("id", "spinner")
        obj.innerHTML = "
Loading results, please wait..."
        document.body.appendChild(obj)
    }
    if (show) {
        obj.style.display = "block"
    } else {
        obj.style.display = "none"
    }
}<|endoftext|>