<commit_before>// Dependencies
var express         = require( 'express' ),
    logger          = require( 'morgan' ),
    bodyParser      = require( 'body-parser' ),
    cookieParser    = require( 'cookie-parser' ),
    cookieSession   = require( 'cookie-session' ),
    fs              = require( 'fs' ),
    crypto          = require( 'crypto' ),
    slug            = require( 'slug' ),
    server          = express(),
    port            = process.env.PORT || 3030;

// Secret tokens
var cookieParserSecret = crypto.randomBytes( 64 ).toString( 'base64' ),
    cookieSessionSecret = crypto.randomBytes( 64 ).toString( 'base64' );

var studentsFile = __dirname + '/students.json';

// Middleware configuration
server.set( 'view engine', 'jade' );
// server.use( logger( 'combined' ) );
server.use( '/assets', express.static( __dirname + '/assets' ) );
server.use( bodyParser.urlencoded({ extended: false }) );
server.use( cookieParser( cookieParserSecret ) );
server.use( cookieSession({ secret: cookieSessionSecret }) );

fs.exists( studentsFile, function( e ) {
    if ( ! e ) {
        var db = { students: [] };
        fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
            if ( err ) {
                console.log( '[ERROR]: Unable to create new students.json', err );
            } else {
                console.log( '[SERVER]: Created new students.json' );
            }
        });
    }
});

function trimSSN( ssn ) {
    ssn = ssn.trim();

    if ( ssn.indexOf( '-' ) < 0 ) {
        ssn = ssn.slice( 0, 6 ) + '-' + ssn.slice( 6, 10 );
    }

    return ssn;
}

// Routes
server.get( '/', function( req, res ) {
    res.render( 'index', {
        error: req.query.error,
        success: req.query.success
    });
});

server.post( '/', function( req, res ) {
    var db = {},
        exists = false;

    if ( req.body.program == '0' || req.body.firstname == '' ||
         req.body.lastname == '' || req.body.ssn == '' ||
         req.body.phone == '' || req.body.email == '' ) {
        res.redirect( '/?error=1' );
        return;
    }

    req.body.ssn = trimSSN( req.body.ssn )

    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]: Unable to open students.json.', err );
            res.redirect( '/?error=1' );
            return;
        }

        db = JSON.parse( data );
        db.students = db.students || [];

        var i;

        db.students.forEach( function( student, index ) {
            if ( student.ssn == req.body.ssn ) {
                exists = true;
                i = index;
            }
        });

        if ( exists ) {
            console.log( '[SERVER]: Student already exists - updating.' );
            db.students[i] = req.body;
        } else {
            console.log( '[SERVER]: Creating new student.' );
            req.body.image = slug( req.body.lastname + ' ' + req.body.firstname, '_' ).toLowerCase() + '_thumb.jpg';
            db.students.push( req.body );
        }

        fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
            if ( err ) {
                console.log( '[ERROR]: Unable to write to students file.', err );
                res.redirect( '/?error=1' );
                return;
            }

            res.redirect( '/?success=' + ( exists ? '2' : '1' ) );
        });
    });
});

server.get( '/student', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        var db = JSON.parse( data );

        db.students.forEach( function( student ) {
            if ( student.ssn == req.query.ssn ) {
                res.status( 200 ).end();
            }
        });

        res.status( 418 ).end();
    });
});

server.get( '/clear', function( req, res ) {
    var db = { students: [] },
        date = new Date();

    fs.rename( studentsFile, 'students_backup_' + date.toString() + '.json', function( err ) {
        if ( err ) {
            console.log( '[ERROR]: Unable to rename students.json', err );
            res.redirect( '/list' );
        } else {
            console.log( '[SYSTEM]: Backup created!' );

            fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
                if ( err ) {
                    console.log( '[ERROR]: Unable to create new students.json', err );
                } else {
                    console.log( '[SERVER]: Created new students.json' );
                }

                res.redirect( '/list' );
            });
        }
    });
});

server.get( '/list', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data );

        db.students.sort( function( a, b ) {
            if ( a.lastname < b.lastname ) {
                return -1;
            }
            if ( a.lastname > b.lastname ) {
                return 1;
            }
            return 0;
        });

        res.render( 'list', { students: db.students } );
    });
});

server.get( '/edit', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data ),
            student = {};

        db.students.forEach( function( s ) {
            if ( req.query.ssn = s.ssn ) {
                student = s;
            }
        });

        res.render( 'edit', {
            student: student,
            error: req.query.error,
            success: req.query.success
        });
    });
});

server.post( '/edit', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data ),
            i = false;

        db.students.forEach( function( student, index ) {
            if ( req.body.ssn = student.ssn ) {
                i = index;
            }
        });

        if ( i !== false ) {
            db.students[i] = req.body;

            fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
                if ( err ) {
                    console.log( '[ERROR]: Unable to write to students file.', err );
                    return;
                }

                res.redirect( '/edit?success=1&ssn=' + db.students[i].ssn );
            });
        } else {
            res.redirect( '/edit?error=1&ssn=' + db.students[i].ssn );
        }
    });
});

server.get( '/export', function( req, res ) {
    res.render( 'export' );
});

server.get( '/download', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data ),
            csv = 'firstname,lastname,phone,email,ssn,image\n';

        db.students.sort( function( a, b ) {
            if ( a.lastname < b.lastname ) {
                return -1;
            }
            if ( a.lastname > b.lastname ) {
                return 1;
            }
            return 0;
        });

        db.students.forEach( function( student ) {
            if ( req.query.program == 'any' ) {
                csv += [
                    student.firstname,
                    student.lastname,
                    student.phone,
                    student.email,
                    student.ssn,
                    student.image
                ].join( ',' ) + '\n';
            } else if ( student.program == req.query.program ) {
                csv += [
                    student.firstname,
                    student.lastname,
                    student.phone,
                    student.email,
                    student.ssn,
                    student.image
                ].join( ',' ) + '\n';
            }
        });

        res.attachment( 'students.csv' );
        res.type( 'text/csv' );
        res.charset = 'UTF-8';
        res.send( csv );
    });
});

// Error handlers
server.use( function( req, res, next ) {
    var err = new Error( 'Page Not Found [' + req.path + ']' );
    err.status = 404;
    next( err );
});
server.use( function( err, req, res, next ) {
    err.status = err.status || 500;
    console.log( '[ERROR]:', err );
    res.status( err.status );
    res.render( 'error', { status: err.status } );
});

// Start listening for HTTP requests
server.listen( port, function() {
    console.log( '[SERVER]: Started listening on port ' + port );
});
<commit_msg>fixed issue with editing<commit_after>// Dependencies
var express         = require( 'express' ),
    logger          = require( 'morgan' ),
    bodyParser      = require( 'body-parser' ),
    cookieParser    = require( 'cookie-parser' ),
    cookieSession   = require( 'cookie-session' ),
    fs              = require( 'fs' ),
    crypto          = require( 'crypto' ),
    slug            = require( 'slug' ),
    server          = express(),
    port            = process.env.PORT || 3030;

// Secret tokens
var cookieParserSecret = crypto.randomBytes( 64 ).toString( 'base64' ),
    cookieSessionSecret = crypto.randomBytes( 64 ).toString( 'base64' );

var studentsFile = __dirname + '/students.json';

// Middleware configuration
server.set( 'view engine', 'jade' );
// server.use( logger( 'combined' ) );
server.use( '/assets', express.static( __dirname + '/assets' ) );
server.use( bodyParser.urlencoded({ extended: false }) );
server.use( cookieParser( cookieParserSecret ) );
server.use( cookieSession({ secret: cookieSessionSecret }) );

fs.exists( studentsFile, function( e ) {
    if ( ! e ) {
        var db = { students: [] };
        fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
            if ( err ) {
                console.log( '[ERROR]: Unable to create new students.json', err );
            } else {
                console.log( '[SERVER]: Created new students.json' );
            }
        });
    }
});

function trimSSN( ssn ) {
    ssn = ssn.trim();

    if ( ssn.indexOf( '-' ) < 0 ) {
        ssn = ssn.slice( 0, 6 ) + '-' + ssn.slice( 6, 10 );
    }

    return ssn;
}

// Routes
server.get( '/', function( req, res ) {
    res.render( 'index', {
        error: req.query.error,
        success: req.query.success
    });
});

server.post( '/', function( req, res ) {
    var db = {},
        exists = false;

    if ( req.body.program == '0' || req.body.firstname == '' ||
         req.body.lastname == '' || req.body.ssn == '' ||
         req.body.phone == '' || req.body.email == '' ) {
        res.redirect( '/?error=1' );
        return;
    }

    req.body.ssn = trimSSN( req.body.ssn )

    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]: Unable to open students.json.', err );
            res.redirect( '/?error=1' );
            return;
        }

        db = JSON.parse( data );
        db.students = db.students || [];

        var i;

        db.students.forEach( function( student, index ) {
            if ( student.ssn == req.body.ssn ) {
                exists = true;
                i = index;
            }
        });

        if ( exists ) {
            console.log( '[SERVER]: Student already exists - updating.' );
            db.students[i] = req.body;
        } else {
            console.log( '[SERVER]: Creating new student.' );
            req.body.image = slug( req.body.lastname + ' ' + req.body.firstname, '_' ).toLowerCase() + '_thumb.jpg';
            db.students.push( req.body );
        }

        fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
            if ( err ) {
                console.log( '[ERROR]: Unable to write to students file.', err );
                res.redirect( '/?error=1' );
                return;
            }

            res.redirect( '/?success=' + ( exists ? '2' : '1' ) );
        });
    });
});

server.get( '/student', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        var db = JSON.parse( data );

        db.students.forEach( function( student ) {
            if ( student.ssn == req.query.ssn ) {
                res.status( 200 ).end();
            }
        });

        res.status( 418 ).end();
    });
});

server.get( '/clear', function( req, res ) {
    var db = { students: [] },
        date = new Date();

    fs.rename( studentsFile, 'students_backup_' + date.toString() + '.json', function( err ) {
        if ( err ) {
            console.log( '[ERROR]: Unable to rename students.json', err );
            res.redirect( '/list' );
        } else {
            console.log( '[SYSTEM]: Backup created!' );

            fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
                if ( err ) {
                    console.log( '[ERROR]: Unable to create new students.json', err );
                } else {
                    console.log( '[SERVER]: Created new students.json' );
                }

                res.redirect( '/list' );
            });
        }
    });
});

server.get( '/list', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data );

        db.students.sort( function( a, b ) {
            if ( a.lastname < b.lastname ) {
                return -1;
            }
            if ( a.lastname > b.lastname ) {
                return 1;
            }
            return 0;
        });

        res.render( 'list', { students: db.students } );
    });
});

server.get( '/edit', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data ),
            student = {};

        db.students.forEach( function( s ) {
            if ( req.query.ssn == s.ssn ) {
                student = s;
            }
        });

        res.render( 'edit', {
            student: student,
            error: req.query.error,
            success: req.query.success
        });
    });
});

server.post( '/edit', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data ),
            i = false;

        db.students.forEach( function( student, index ) {
            if ( req.body.ssn = student.ssn ) {
                i = index;
            }
        });

        if ( i !== false ) {
            db.students[i] = req.body;

            fs.writeFile( studentsFile, JSON.stringify( db ), function( err ) {
                if ( err ) {
                    console.log( '[ERROR]: Unable to write to students file.', err );
                    return;
                }

                res.redirect( '/edit?success=1&ssn=' + db.students[i].ssn );
            });
        } else {
            res.redirect( '/edit?error=1&ssn=' + db.students[i].ssn );
        }
    });
});

server.get( '/export', function( req, res ) {
    res.render( 'export' );
});

server.get( '/download', function( req, res ) {
    fs.readFile( studentsFile, 'utf8', function( err, data ) {
        if ( err ) {
            console.log( '[ERROR]:', err );
            return;
        }

        var db = JSON.parse( data ),
            csv = 'firstname,lastname,phone,email,ssn,image\n';

        db.students.sort( function( a, b ) {
            if ( a.lastname < b.lastname ) {
                return -1;
            }
            if ( a.lastname > b.lastname ) {
                return 1;
            }
            return 0;
        });

        db.students.forEach( function( student ) {
            if ( req.query.program == 'any' ) {
                csv += [
                    student.firstname,
                    student.lastname,
                    student.phone,
                    student.email,
                    student.ssn,
                    student.image
                ].join( ',' ) + '\n';
            } else if ( student.program == req.query.program ) {
                csv += [
                    student.firstname,
                    student.lastname,
                    student.phone,
                    student.email,
                    student.ssn,
                    student.image
                ].join( ',' ) + '\n';
            }
        });

        res.attachment( 'students.csv' );
        res.type( 'text/csv' );
        res.charset = 'UTF-8';
        res.send( csv );
    });
});

// Error handlers
server.use( function( req, res, next ) {
    var err = new Error( 'Page Not Found [' + req.path + ']' );
    err.status = 404;
    next( err );
});
server.use( function( err, req, res, next ) {
    err.status = err.status || 500;
    console.log( '[ERROR]:', err );
    res.status( err.status );
    res.render( 'error', { status: err.status } );
});

// Start listening for HTTP requests
server.listen( port, function() {
    console.log( '[SERVER]: Started listening on port ' + port );
});
<|endoftext|>


<commit_before>import assign from 'lodash/object/assign';
import difference from 'lodash/array/difference';

export default function createPrototypeProxy() {
  let proxy = {};
  let current = null;
  let mountedInstances = [];

  function proxyMethod(name) {
    return function () {
      if (typeof current[name] === 'function') {
        return current[name].apply(this, arguments);
      }
    };
  }

  function proxiedComponentWillMount() {
    mountedInstances.push(this);
    if (typeof current.componentWillMount === 'function') {
      return current.componentWillMount.apply(this, arguments);
    }
  }

  function proxiedComponentWillUnmount() {
    mountedInstances.splice(mountedInstances.indexOf(this), 1);
    if (typeof current.componentWillUnmount === 'function') {
      return current.componentWillUnmount.apply(this, arguments);
    }
  }

  function update(next) {
    // Save current source of truth
    current = next;

    // Find changed property names
    const nextNames = Object.getOwnPropertyNames(next);
    const currentNames = Object.getOwnPropertyNames(proxy);
    const addedNames = difference(nextNames, currentNames);
    const removedNames = difference(currentNames, nextNames);

    // Remove properties and methods that are no longer there
    removedNames.forEach(name => {
      delete proxy[name];
    });

    // Copy every descriptor
    nextNames.forEach(name => {
      const descriptor = Object.getOwnPropertyDescriptor(next, name);
      Object.defineProperty(proxy, name, descriptor);
    });

    // Proxy newly added methods
    addedNames.forEach(name => {
      const descriptor = Object.getOwnPropertyDescriptor(next, name);
      if (typeof descriptor.value !== 'function') {
        return;
      }

      // Wrap the original function
      proxy[name] = proxyMethod(name);
      // Copy properties of the original function, if any
      assign(proxy[name], descriptor.value);
    });

    // Track mounted instances so we can forceUpdate() them later
    proxy.componentWillMount = proxiedComponentWillMount;
    proxy.componentWillUnmount = proxiedComponentWillUnmount;

    // Woodoo to appease Babel and React
    proxy.__proto__ = next;
    proxy.__reactAutoBindMap = {};
  }

  function get() {
    return proxy;
  }

  function getMountedInstances() {
    return mountedInstances;
  }

  return {
    update,
    get,
    getMountedInstances
  };
};<commit_msg>Whoops, we didn't need that code<commit_after>import assign from 'lodash/object/assign';
import difference from 'lodash/array/difference';

export default function createPrototypeProxy() {
  let proxy = {};
  let current = null;
  let mountedInstances = [];

  function proxyMethod(name) {
    return function () {
      if (typeof current[name] === 'function') {
        return current[name].apply(this, arguments);
      }
    };
  }

  function proxiedComponentWillMount() {
    mountedInstances.push(this);
    if (typeof current.componentWillMount === 'function') {
      return current.componentWillMount.apply(this, arguments);
    }
  }

  function proxiedComponentWillUnmount() {
    mountedInstances.splice(mountedInstances.indexOf(this), 1);
    if (typeof current.componentWillUnmount === 'function') {
      return current.componentWillUnmount.apply(this, arguments);
    }
  }

  function update(next) {
    // Save current source of truth
    current = next;

    // Find changed property names
    const nextNames = Object.getOwnPropertyNames(next);
    const currentNames = Object.getOwnPropertyNames(proxy);
    const addedNames = difference(nextNames, currentNames);
    const removedNames = difference(currentNames, nextNames);

    // Remove properties and methods that are no longer there
    removedNames.forEach(name => {
      delete proxy[name];
    });

    // Proxy newly added methods
    addedNames.forEach(name => {
      const descriptor = Object.getOwnPropertyDescriptor(next, name);
      if (typeof descriptor.value !== 'function') {
        return;
      }

      // Wrap the original function
      proxy[name] = proxyMethod(name);
      // Copy properties of the original function, if any
      assign(proxy[name], descriptor.value);
    });

    // Track mounted instances so we can forceUpdate() them later
    proxy.componentWillMount = proxiedComponentWillMount;
    proxy.componentWillUnmount = proxiedComponentWillUnmount;

    // Redirect any other properties directly
    proxy.__proto__ = next;

    // Reset autobinding cache
    proxy.__reactAutoBindMap = {};
  }

  function get() {
    return proxy;
  }

  function getMountedInstances() {
    return mountedInstances;
  }

  return {
    update,
    get,
    getMountedInstances
  };
};<|endoftext|>


<commit_before>'use strict';

// Loading dependencies.
var _ = require('underscore'),
    express = require('express'),
    bodyParser = require('body-parser');

// Loading all of the locale-specific avenger data.
var data = {
    de: require('./data/de'),
    en: require('./data/en'),
    fr: require('./data/fr')
};

// Loading all of the locale-specific translations.
var translations = {
    de: require('./locales/de.json'),
    fr: require('./locales/fr.json')
};

// Instantiating the framework and a router for our requests.
var app = express(),
    router = express.Router();

// The port which this script will listen to.
var apiPort = 4000;

// Anti XSSI (Cross-site script inclusion) string.
var xssiString = ')]}\',';

// Application parses request bodies: application/json, application/x-www-form-urlencoded, and multipart/form-data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Handler for all requests. Responses are given CORS headers.
router.use(function(request, response, next) {
    console.log('Request:', 'GET', request.originalUrl);
    response.header('Access-Control-Allow-Origin', '*');
    next();
});

// Route: Locale-specific translations.
router.get('/api/:locale(de|fr)/translations', function(request, response) {
    var relevantRecord = translations[request.params.locale];

    setTimeout(function() {
        response.type('application/json');
        response.send(xssiString + JSON.stringify(relevantRecord));
    }, 1000);
});

// Route: Collection endpoint returning all records.
router.get('/api/:locale/avengers', function(request, response) {
    var relevantDataset = data[request.params.locale],
        returnData = [];

    relevantDataset.forEach(function(record) {
        returnData.push(_.pick(record, 'id', 'slug', 'alias', 'gender'));
    });

    setTimeout(function() {
        response.type('application/json');
        response.send(xssiString + JSON.stringify(returnData));
    }, 3000);
});

// Route: Model endpoint returning an individual record.
router.get('/api/:locale/avengers/:slug', function(request, response) {
    var relevantDataset = data[request.params.locale],
        individualRecord = _.findWhere(relevantDataset, { slug: request.params.slug });

    setTimeout(function() {
        response.type('application/json');
        response.send(xssiString + JSON.stringify(individualRecord));
    }, 3000);
});

// Route: Homepage with locale.
router.get('/:locale(en|fr|de)', function(request, response) {
    response.render ('homepage', { locale: request.params.locale });
});

// Route: Homepage without locale (redirected).
router.get('^/$', function(request, response) {
    response.redirect('/en');
});

// Hook up the jade view engine to our application.
app.set('view engine', 'jade');
app.set('views', './views');
app.locals.pretty = true;

// Associate the router with our application.
app.use('/', router);

// Hosting the dist folder as a static directory of files.
app.use('/dist', express.static('dist'));

// Listen for the above routes on the following port.
app.listen(apiPort);

// Debugging to the console that the server has started.
console.log('Mock API Server: http://localhost:' + apiPort + '/');<commit_msg>Returning the server instance from the API so it can be stopped once tests complete.<commit_after>'use strict';

// Loading dependencies.
var _ = require('underscore'),
    express = require('express'),
    bodyParser = require('body-parser');

// Loading all of the locale-specific avenger data.
var data = {
    de: require('./data/de'),
    en: require('./data/en'),
    fr: require('./data/fr')
};

// Loading all of the locale-specific translations.
var translations = {
    de: require('./locales/de.json'),
    fr: require('./locales/fr.json')
};

// Instantiating the framework and a router for our requests.
var app = express(),
    router = express.Router();

// The port which this script will listen to.
var apiPort = 4000;

// Anti XSSI (Cross-site script inclusion) string.
var xssiString = ')]}\',';

// Application parses request bodies: application/json, application/x-www-form-urlencoded, and multipart/form-data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Handler for all requests. Responses are given CORS headers.
router.use(function(request, response, next) {
    console.log('Request:', 'GET', request.originalUrl);
    response.header('Access-Control-Allow-Origin', '*');
    next();
});

// Route: Locale-specific translations.
router.get('/api/:locale(de|fr)/translations', function(request, response) {
    var relevantRecord = translations[request.params.locale];

    setTimeout(function() {
        response.type('application/json');
        response.send(xssiString + JSON.stringify(relevantRecord));
    }, 1000);
});

// Route: Collection endpoint returning all records.
router.get('/api/:locale/avengers', function(request, response) {
    var relevantDataset = data[request.params.locale],
        returnData = [];

    relevantDataset.forEach(function(record) {
        returnData.push(_.pick(record, 'id', 'slug', 'alias', 'gender'));
    });

    setTimeout(function() {
        response.type('application/json');
        response.send(xssiString + JSON.stringify(returnData));
    }, 3000);
});

// Route: Model endpoint returning an individual record.
router.get('/api/:locale/avengers/:slug', function(request, response) {
    var relevantDataset = data[request.params.locale],
        individualRecord = _.findWhere(relevantDataset, { slug: request.params.slug });

    setTimeout(function() {
        response.type('application/json');
        response.send(xssiString + JSON.stringify(individualRecord));
    }, 3000);
});

// Route: Homepage with locale.
router.get('/:locale(en|fr|de)', function(request, response) {
    response.render ('homepage', { locale: request.params.locale });
});

// Route: Homepage without locale (redirected).
router.get('^/$', function(request, response) {
    response.redirect('/en');
});

// Hook up the jade view engine to our application.
app.set('view engine', 'jade');
app.set('views', './views');
app.locals.pretty = true;

// Associate the router with our application.
app.use('/', router);

// Hosting the dist folder as a static directory of files.
app.use('/dist', express.static('dist'));

// Listen for the above routes on the specified port, returning the server instance.
module.exports = app.listen(apiPort);

// Debugging to the console that the server has started.
console.log('Mock API Server: http://localhost:' + apiPort + '/');<|endoftext|>


<commit_before>//
<commit_msg>code express server<commit_after>var express    = require('express');
var bodyParser = require('body-parser');

var app        = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;

// API ROUTES
var router = express.Router();

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
  res.json({ message: 'Welcome to noms api' });
});

// more routes for our API will happen here

// REGISTER ROUTES
// all routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const http = require('http');

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Testing
slapp.command('/bible', /.*/, (msg, text) => {
  console.log('received bible command');
  msg.say('Received slash command for Bible. Command entered:' + text);
  sendRequest(parseVerse(text), msg);
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// Send HTTP Request
function sendRequest(verse, msg) {
  var body;
  var options = {
    host: 'labs.bible.org',
    path: '/api/?passage=' + verse + '&formatting=full',
  }

  var request = http.get(options, function(response){
    console.log('STATUS: ' + response.statusCode);
    console.log('HEADERS: ' + JSON.stringify(response.headers));

    // Buffer the body entirely for processing as a whole.
    var bodyStream = [];
    response.on('data', function(chunk) {
      // Partially streamed body
      console.log('-----got chunk-----');
      bodyStream.push(chunk);
    }).on('end', function() {
      // Completely streamed body
      console.log('-----finished body-----');
      body = Buffer.concat(bodyStream).toString();
      console.log('BODY: ' + body);
      reply(body, msg);
    })
  });

  request.on('error', function(e) {
    console.log('error occurred in HTTP GET request: ', e.message);
  });
}

function reply(body, msg) {
  var verse = body.replace(/<\/?b>/g, '*')
                  .replace(/<\/?i>/g, '_')
                  .replace(/<p.{0,}?>/g, '\n')
                  .replace(/<.+?>/g, '');
  console.log('got this from sendRequest():', verse);
  msg.say('Here\'s your verse!\n>' + verse);
}

function parseVerse(text) {
  var verse = 'Lk+2:1;+4:4';
  return verse;
}

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>added another quote charater to a necessary place in a regex replacement<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const http = require('http');

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Testing
slapp.command('/bible', /.*/, (msg, text) => {
  console.log('received bible command');
  msg.say('Received slash command for Bible. Command entered:' + text);
  sendRequest(parseVerse(text), msg);
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// Send HTTP Request
function sendRequest(verse, msg) {
  var body;
  var options = {
    host: 'labs.bible.org',
    path: '/api/?passage=' + verse + '&formatting=full',
  }

  var request = http.get(options, function(response){
    console.log('STATUS: ' + response.statusCode);
    console.log('HEADERS: ' + JSON.stringify(response.headers));

    // Buffer the body entirely for processing as a whole.
    var bodyStream = [];
    response.on('data', function(chunk) {
      // Partially streamed body
      console.log('-----got chunk-----');
      bodyStream.push(chunk);
    }).on('end', function() {
      // Completely streamed body
      console.log('-----finished body-----');
      body = Buffer.concat(bodyStream).toString();
      console.log('BODY: ' + body);
      reply(body, msg);
    })
  });

  request.on('error', function(e) {
    console.log('error occurred in HTTP GET request: ', e.message);
  });
}

function reply(body, msg) {
  var verse = body.replace(/<\/?b>/g, '*')
                  .replace(/<\/?i>/g, '_')
                  .replace(/<p.{0,}?>/g, '\n>')
                  .replace(/<.+?>/g, '');
  console.log('got this from sendRequest():', verse);
  msg.say('Here\'s your verse!\n>' + verse);
}

function parseVerse(text) {
  var verse = 'Lk+2:1;+4:4';
  return verse;
}

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>'use strict';

/**
 * Upload.js service
 *
 * @description: A set of functions similar to controller's actions to avoid code duplication.
 */

const fs = require('fs');
const _ = require('lodash');
const toArray = require('stream-to-array');
const uuid = require('uuid/v4');

module.exports = {
  bufferize: async files => {
    if (_.isEmpty(files) === 0) {
      throw 'Missing files.';
    }

    // files is always an array to map on
    files = _.isArray(files) ? files : [files];

    // transform all files in buffer
    return Promise.all(
      files.map(async stream => {
        const parts = await toArray(fs.createReadStream(stream.path));
        const buffers = parts.map(
          part => _.isBuffer(part) ? part : Buffer.from(part)
        );

        return {
          name: stream.name,
          hash: uuid().replace(/-/g, ''),
          ext: stream.name.split('.').length > 1 ? `.${_.last(stream.name.split('.'))}` : '',
          buffer: Buffer.concat(buffers),
          mime: stream.type,
          size: (stream.size / 1000).toFixed(2)
        };
      })
    );
  },

  upload: async (files, config) => {
    // Get upload provider settings to configure the provider to use.
    const provider = _.find(strapi.plugins.upload.config.providers, { provider: config.provider });

    if (!provider) {
      throw new Error(`The provider package isn't installed. Please run \`npm install strapi-upload-${config.provider}\``);
    }

    const actions = provider.init(config);

    // Execute upload function of the provider for all files.
    return Promise.all(
      files.map(async file => {
        await actions.upload(file);

        // Remove buffer to don't save it.
        delete file.buffer;

        file.provider = provider.provider;

        return await strapi.plugins['upload'].services.upload.add(file);
      })
    );
  },

  add: async (values) => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      return await strapi.plugins['content-manager'].services['contentmanager'].add({
        model: 'file'
      }, values, 'upload');
    }

    return strapi.query('file', 'upload').create(values);
  },

  edit: async (params, values) => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';
      params.id = (params._id || params.id);

      return await strapi.plugins['content-manager'].services['contentmanager'].edit(params, values, 'upload');
    }

    return strapi.query('file', 'upload').update(_.assign(params, values));
  },

  fetch: (params) => {
    return strapi.query('file', 'upload').findOne(_.pick(params, ['_id', 'id']));
  },

  fetchAll: (params) => {
    return strapi.query('file', 'upload').find(strapi.utils.models.convertParams('file', params));
  },

  count: async () => {
    return await strapi.query('file', 'upload').count();
  },

  remove: async (params, config) => {
    const file = await strapi.plugins['upload'].services.upload.fetch(params);

    // get upload provider settings to configure the provider to use
    const provider = _.cloneDeep(_.find(strapi.plugins.upload.config.providers, {provider: config.provider}));
    _.assign(provider, config);
    const actions = provider.init(config);

    // execute delete function of the provider
    if (file.provider === provider.provider) {
      await actions.delete(file);
    }

    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';
      params.id = (params._id || params.id);

      await strapi.plugins['content-manager'].services['contentmanager'].delete(params, {source: 'upload'});
    }

    return strapi.query('file', 'upload').delete(params);
  },

  uploadToEntity: async function (params, files, source) {
    // Retrieve provider settings from database.
    const config = await strapi.store({
      environment: strapi.config.environment,
      type: 'plugin',
      name: 'upload'
    }).get({ key: 'provider' });

    const model = source && source !== 'content-manager' ?
      strapi.plugins[source].models[params.model]:
      strapi.models[params.model];

    // Asynchronous upload.
    await Promise.all(
      Object.keys(files)
        .map(async attribute => {
          // Bufferize files per attribute.
          const buffers = await this.bufferize(files[attribute]);
          const enhancedFiles = buffers.map(file => {
            const details = model.attributes[attribute];

            // Add related information to be able to make
            // the relationships later.
            file[details.via] = [{
              refId: params.id,
              ref: params.model,
              source,
              field: attribute,
            }];

            return file;
          });

          // Make upload async.
          return this.upload(enhancedFiles, config);
        })
    );
  }
};
<commit_msg>Fix delete uploaded file SQL fix #1459<commit_after>'use strict';

/**
 * Upload.js service
 *
 * @description: A set of functions similar to controller's actions to avoid code duplication.
 */

const fs = require('fs');
const _ = require('lodash');
const toArray = require('stream-to-array');
const uuid = require('uuid/v4');

module.exports = {
  bufferize: async files => {
    if (_.isEmpty(files) === 0) {
      throw 'Missing files.';
    }

    // files is always an array to map on
    files = _.isArray(files) ? files : [files];

    // transform all files in buffer
    return Promise.all(
      files.map(async stream => {
        const parts = await toArray(fs.createReadStream(stream.path));
        const buffers = parts.map(
          part => _.isBuffer(part) ? part : Buffer.from(part)
        );

        return {
          name: stream.name,
          hash: uuid().replace(/-/g, ''),
          ext: stream.name.split('.').length > 1 ? `.${_.last(stream.name.split('.'))}` : '',
          buffer: Buffer.concat(buffers),
          mime: stream.type,
          size: (stream.size / 1000).toFixed(2)
        };
      })
    );
  },

  upload: async (files, config) => {
    // Get upload provider settings to configure the provider to use.
    const provider = _.find(strapi.plugins.upload.config.providers, { provider: config.provider });

    if (!provider) {
      throw new Error(`The provider package isn't installed. Please run \`npm install strapi-upload-${config.provider}\``);
    }

    const actions = provider.init(config);

    // Execute upload function of the provider for all files.
    return Promise.all(
      files.map(async file => {
        await actions.upload(file);

        // Remove buffer to don't save it.
        delete file.buffer;

        file.provider = provider.provider;

        return await strapi.plugins['upload'].services.upload.add(file);
      })
    );
  },

  add: async (values) => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      return await strapi.plugins['content-manager'].services['contentmanager'].add({
        model: 'file'
      }, values, 'upload');
    }

    return strapi.query('file', 'upload').create(values);
  },

  edit: async (params, values) => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';
      params.id = (params._id || params.id);

      return await strapi.plugins['content-manager'].services['contentmanager'].edit(params, values, 'upload');
    }

    return strapi.query('file', 'upload').update(_.assign(params, values));
  },

  fetch: (params) => {
    return strapi.query('file', 'upload').findOne(_.pick(params, ['_id', 'id']));
  },

  fetchAll: (params) => {
    return strapi.query('file', 'upload').find(strapi.utils.models.convertParams('file', params));
  },

  count: async () => {
    return await strapi.query('file', 'upload').count();
  },

  remove: async (params, config) => {
    params.id = (params._id || params.id);

    const file = await strapi.plugins['upload'].services.upload.fetch(params);

    // get upload provider settings to configure the provider to use
    const provider = _.cloneDeep(_.find(strapi.plugins.upload.config.providers, {provider: config.provider}));
    _.assign(provider, config);
    const actions = provider.init(config);

    // execute delete function of the provider
    if (file.provider === provider.provider) {
      await actions.delete(file);
    }

    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';

      await strapi.plugins['content-manager'].services['contentmanager'].delete(params, {source: 'upload'});
    }

    return strapi.query('file', 'upload').delete(params);
  },

  uploadToEntity: async function (params, files, source) {
    // Retrieve provider settings from database.
    const config = await strapi.store({
      environment: strapi.config.environment,
      type: 'plugin',
      name: 'upload'
    }).get({ key: 'provider' });

    const model = source && source !== 'content-manager' ?
      strapi.plugins[source].models[params.model]:
      strapi.models[params.model];

    // Asynchronous upload.
    await Promise.all(
      Object.keys(files)
        .map(async attribute => {
          // Bufferize files per attribute.
          const buffers = await this.bufferize(files[attribute]);
          const enhancedFiles = buffers.map(file => {
            const details = model.attributes[attribute];

            // Add related information to be able to make
            // the relationships later.
            file[details.via] = [{
              refId: params.id,
              ref: params.model,
              source,
              field: attribute,
            }];

            return file;
          });

          // Make upload async.
          return this.upload(enhancedFiles, config);
        })
    );
  }
};
<|endoftext|>


<commit_before>var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);<commit_msg>Use env port<commit_after>var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(process.env.PORT || 8080);<|endoftext|>


<commit_before>var ws = require("nodejs-websocket"),
    express = require("express");

process.stdout.on("error", function(err) {
    console.log("ERROR:", err, err.code);
    switch (err.code) {
        case "EPIPE":
            break;
        default:
            process.exit(0);
    }
});

var app = express(),
    httpServer = require("http").createServer(app);

app.get("/", function(req, res) {
    res.send("Test");
});
httpServer.listen(process.env.PORT || 8000);

var wsServer = null;
var settings = {
        pingInterval: 30*1000, // ms
        sessionTimeout: 2*60*1000 // ms
};
var errors = {
    msgFailed: "Message construction failed.",
    sendFailed: "Message sending failed.",
    parseFailed: "Message parse failed.",
    malformed: "Message malformed.",
    unknownHeader: "Unknown header."
};

// id: {connections: [], timeout: f}
var sessions = {};

// sessionId: {contact: "", tier: "", region: ""}
var scrims = {};
var tiers = ["Low", "Mid", "High", "High+", "High++"];
var regions = ["SEA", "NA", "EU"];

function message(header, body) {
    var m = {header: header.toUpperCase(), body: body, timestamp: +new Date()};
    try {
        m = JSON.stringify(m);
    } catch (e) {
        return {message: null, error: e};
    } finally {
        return {message: m, error: null};
    }
}

function send(sid, header, body) {
    var m = message(header, body);
    if (m.error) {
        console.log("Error:", errors.msgFailed, m.error);
        return;
    }
    if (!(sid in sessions)) {
        console.log("Error:", errors.sendFailed, "Session with that ID not found.", sid);
        return;
    }
    console.log(sid, "<-", header, body);
    sessions[sid].connections.forEach(function(c) {
        try {
            c.send(m.message);
        } catch(err) {
            console.log("Error:", errors.sendFailed, err);
        }
    });
}

function broadcast(header, body) {
    for (sid in sessions) {
        send(sid, header, body);
    }
}

function pinger() {
    setInterval(function () {
        broadcast("PING", null);
    }, settings.pingInterval);
}

function merge(conn, sid) {
    if (conn.sessionId === sid) return;
    if (!(sid in sessions)) {
        sessions[sid] = {connections: [conn], timeout: function() {}};
        delete scrims[conn.sessionId];
        delete sessions[conn.sessionId];
        conn.sessionId = sid;
        return;
    }

    delete sessions[conn.sessionId];
    clearTimeout(sessions[sid].timeout);
    sessions[sid].connections.push(conn);

    if (conn.sessionId in scrims) {
        scrims[sid] = scrims[conn.sessionId];
        delete scrims[conn.sessionId];
        update();
    }
    conn.sessionId = sid;
}

function update() {
    var data = [];
    for (k in scrims) {
        data.push(scrims[k]);
    }
    broadcast("UPDATE", data);
    console.log("Scrims:", data);
}

function handle(conn, data) {
    if (!("header" in data) || !("body" in data)) {
        send(conn.sessionId, "ERROR", errors.malformed);
        return;
    }
    data.header = data.header || "";
    data.body = data.body || "";

    switch (data.header.toUpperCase()) {
        case "IDENT":
            var oldSid = data.body;
            if (oldSid) {
                console.log("Switch", conn.sessionId, "to", oldSid);
                merge(conn, oldSid);
            }
            break;
        case "SET":
            if (typeof data.body !== "object") {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (!("tier" in data.body) || !("region" in data.body) || !("contact" in data.body)) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (tiers.indexOf(data.body.tier) < 0 || regions.indexOf(data.body.region) < 0 || data.body.contact.length > 20) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            scrims[conn.sessionId] = {contact: data.body.contact, region: data.body.region, tier: data.body.tier};
            update();
            break;
        case "CLEAR":
            delete scrims[conn.sessionId];
            update();
            break;
        case "PONG":
            break;
        case "SESSIONS":
            console.log(Object.keys(sessions));
            break;
        default:
            send(conn.sessionId, "ERROR", errors.unknownHeader + ": " + data.header);
    }
}

pinger();
wsServer = ws.createServer(function(conn) {
    conn.id = uuid();
    conn.sessionId = uuid();
    while (conn.readyState == conn.CONNECTING) {}
    sessions[conn.sessionId] = {connections: [conn], timeout: function() {}};
    console.log(conn.sessionId, "connected.");
    send(conn.sessionId, "IDENT", conn.sessionId);
    update();

    conn.on("text", function(str) {
        var data;
        try {
            data = JSON.parse(str);
        } catch(err) {
            console.log("Error:", errors.parseFailed, err);
            return;
        }
        if (!data) return;
        console.log("Received:", data);
        handle(conn, data);
    });

    conn.on("close", function(code, reason) {
        console.log(conn.id, "disconnected:", code, reason);
        if (conn.sessionId in sessions) {
            for (var i = 0; i < sessions[conn.sessionId].connections.length; i++) {
                var c = sessions[conn.sessionId].connections[i];
                if (c.id === conn.id) {
                    sessions[conn.sessionId].connections.splice(i, 1);
                    break;
                }
            }
            if (sessions[conn.sessionId].connections.length < 1) {
                sessions[conn.sessionId].timeout = setTimeout(function() {
                    delete scrims[conn.sessionId];
                    delete sessions[conn.sessionId];
                    update();
                }, settings.sessionTimeout);
            }
        }
    });
}).listen(httpServer);

function uuid(a){
    return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)
}
<commit_msg>Test HTTP server on the shared port<commit_after>var ws = require("nodejs-websocket"),
    express = require("express");

process.stdout.on("error", function(err) {
    console.log("ERROR:", err, err.code);
    switch (err.code) {
        case "EPIPE":
            break;
        default:
            process.exit(0);
    }
});

var app = express(),
    httpServer = require("http").createServer(app);

app.get("/test", function(req, res) {
    res.send("test");
});
httpServer.listen(process.env.PORT || 8000);

var wsServer = null;
var settings = {
        pingInterval: 30*1000, // ms
        sessionTimeout: 2*60*1000 // ms
};
var errors = {
    msgFailed: "Message construction failed.",
    sendFailed: "Message sending failed.",
    parseFailed: "Message parse failed.",
    malformed: "Message malformed.",
    unknownHeader: "Unknown header."
};

// id: {connections: [], timeout: f}
var sessions = {};

// sessionId: {contact: "", tier: "", region: ""}
var scrims = {};
var tiers = ["Low", "Mid", "High", "High+", "High++"];
var regions = ["SEA", "NA", "EU"];

function message(header, body) {
    var m = {header: header.toUpperCase(), body: body, timestamp: +new Date()};
    try {
        m = JSON.stringify(m);
    } catch (e) {
        return {message: null, error: e};
    } finally {
        return {message: m, error: null};
    }
}

function send(sid, header, body) {
    var m = message(header, body);
    if (m.error) {
        console.log("Error:", errors.msgFailed, m.error);
        return;
    }
    if (!(sid in sessions)) {
        console.log("Error:", errors.sendFailed, "Session with that ID not found.", sid);
        return;
    }
    console.log(sid, "<-", header, body);
    sessions[sid].connections.forEach(function(c) {
        try {
            c.send(m.message);
        } catch(err) {
            console.log("Error:", errors.sendFailed, err);
        }
    });
}

function broadcast(header, body) {
    for (sid in sessions) {
        send(sid, header, body);
    }
}

function pinger() {
    setInterval(function () {
        broadcast("PING", null);
    }, settings.pingInterval);
}

function merge(conn, sid) {
    if (conn.sessionId === sid) return;
    if (!(sid in sessions)) {
        sessions[sid] = {connections: [conn], timeout: function() {}};
        delete scrims[conn.sessionId];
        delete sessions[conn.sessionId];
        conn.sessionId = sid;
        return;
    }

    delete sessions[conn.sessionId];
    clearTimeout(sessions[sid].timeout);
    sessions[sid].connections.push(conn);

    if (conn.sessionId in scrims) {
        scrims[sid] = scrims[conn.sessionId];
        delete scrims[conn.sessionId];
        update();
    }
    conn.sessionId = sid;
}

function update() {
    var data = [];
    for (k in scrims) {
        data.push(scrims[k]);
    }
    broadcast("UPDATE", data);
    console.log("Scrims:", data);
}

function handle(conn, data) {
    if (!("header" in data) || !("body" in data)) {
        send(conn.sessionId, "ERROR", errors.malformed);
        return;
    }
    data.header = data.header || "";
    data.body = data.body || "";

    switch (data.header.toUpperCase()) {
        case "IDENT":
            var oldSid = data.body;
            if (oldSid) {
                console.log("Switch", conn.sessionId, "to", oldSid);
                merge(conn, oldSid);
            }
            break;
        case "SET":
            if (typeof data.body !== "object") {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (!("tier" in data.body) || !("region" in data.body) || !("contact" in data.body)) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (tiers.indexOf(data.body.tier) < 0 || regions.indexOf(data.body.region) < 0 || data.body.contact.length > 20) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            scrims[conn.sessionId] = {contact: data.body.contact, region: data.body.region, tier: data.body.tier};
            update();
            break;
        case "CLEAR":
            delete scrims[conn.sessionId];
            update();
            break;
        case "PONG":
            break;
        case "SESSIONS":
            console.log(Object.keys(sessions));
            break;
        default:
            send(conn.sessionId, "ERROR", errors.unknownHeader + ": " + data.header);
    }
}

pinger();
wsServer = ws.createServer(function(conn) {
    conn.id = uuid();
    conn.sessionId = uuid();
    while (conn.readyState == conn.CONNECTING) {}
    sessions[conn.sessionId] = {connections: [conn], timeout: function() {}};
    console.log(conn.sessionId, "connected.");
    send(conn.sessionId, "IDENT", conn.sessionId);
    update();

    conn.on("text", function(str) {
        var data;
        try {
            data = JSON.parse(str);
        } catch(err) {
            console.log("Error:", errors.parseFailed, err);
            return;
        }
        if (!data) return;
        console.log("Received:", data);
        handle(conn, data);
    });

    conn.on("close", function(code, reason) {
        console.log(conn.id, "disconnected:", code, reason);
        if (conn.sessionId in sessions) {
            for (var i = 0; i < sessions[conn.sessionId].connections.length; i++) {
                var c = sessions[conn.sessionId].connections[i];
                if (c.id === conn.id) {
                    sessions[conn.sessionId].connections.splice(i, 1);
                    break;
                }
            }
            if (sessions[conn.sessionId].connections.length < 1) {
                sessions[conn.sessionId].timeout = setTimeout(function() {
                    delete scrims[conn.sessionId];
                    delete sessions[conn.sessionId];
                    update();
                }, settings.sessionTimeout);
            }
        }
    });
}).listen(httpServer);

function uuid(a){
    return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)
}
<|endoftext|>


<commit_before>import { promise } from "lively.lang";
import vdom from "virtual-dom";
import { addOrChangeCSSDeclaration } from "./dom-helper.js";

var {h, diff, patch, create} = vdom;

const defaultCSS = '.morph { box-sizing: border-box; }';

export class Renderer {

  static default() { return this._default || new this() }

  constructor(world, rootNode, domEnvironment) {
    if (!domEnvironment) {
      if (typeof window !== "undefined" && typeof document !== "undefined")
        domEnvironment = {window, document};
      else
        throw new Error("Morphic renderer cannot find DOM environment (window / document)!");
    }
    if (!world || !world.isMorph)
      throw new Error(`Trying to initialize renderer with an invalid world morph: ${world}`)
    if (!rootNode || !("nodeType" in rootNode))
      throw new Error(`Trying to initialize renderer with an invalid root node: ${rootNode}`)
    this.worldMorph = world;
    world._isWorld = true; // for world() method
    this.rootNode = rootNode;
    this.domNode = null;
    this.domEnvironment = domEnvironment;
    this.renderMap = new WeakMap();
    this.renderWorldLoopProcess = null;
  }

  clear() {
    this.stopRenderWorldLoop();
    this.domNode && this.domNode.parentNode.removeChild(this.domNode);
    this.domNode = null;
    this.renderMap = new WeakMap();
  }

  ensureDefaultCSS() {
    return promise.waitFor(3000, () => this.domNode.ownerDocument)
      .then(doc => addOrChangeCSSDeclaration("lively-morphic-css", defaultCSS, doc))
  }

  startRenderWorldLoop() {
    this.renderWorld();
    this.renderWorldLoopProcess = this.domEnvironment.window.requestAnimationFrame(() =>
      this.startRenderWorldLoop());
  }

  stopRenderWorldLoop() {
    this.domEnvironment.window.cancelAnimationFrame(this.renderWorldLoopProcess);
    this.renderWorldLoopProcess = null;
  }

  renderWorld() {
    var world = this.worldMorph;

    if (!world.needsRerender()) return;

    var tree = this.renderMap.get(world) || this.renderMorph(world),
        domNode = this.domNode || (this.domNode = create(tree, this.domEnvironment)),
        newTree = this.renderMorph(world),
        patches = diff(tree, newTree);

    if (!domNode.parentNode) {
      this.rootNode.appendChild(domNode);
      this.ensureDefaultCSS();
    }

    patch(domNode, patches);
  }

  renderMorph(morph) {
    if (!morph.needsRerender()) {
      var rendered = this.renderMap.get(morph);
      if (rendered) return rendered;
    }
    morph.aboutToRender();

    const shapedStyle = Object.assign({
        position: "absolute",
        visibility: morph.visible ? "visible" : "hidden",
        left: morph.position.x + 'px',
        top: morph.position.y + 'px',
        width: morph.extent.x + 'px',
        height: morph.extent.y + 'px',
        backgroundColor: morph.fill ? morph.fill.toString() : "",
        overflow: morph.clipMode,
        "pointer-events": morph.reactsToPointer ? "auto" : "none"
    }, morph.shape().style);

    const attributes = Object.assign(
      morph.shape(), {
        id: morph.id,
        className: "morph",
        style: shapedStyle
     });

    var tree = h(morph._nodeType,
                attributes,
                morph.submorphs.map(m => this.renderMorph(m)));

    this.renderMap.set(morph, tree);
    return tree;
  }

  getNodeForMorph(morph) {
    // Hmm, this also finds dom nodes not associated with this renderer, its
    // domNode... Is this a problem?
    return this.domNode.ownerDocument.getElementById(morph.id);
  }

  getMorphForNode(node) {
    return this.worldMorph ?
      this.worldMorph.withAllSubmorphsDetect(morph => morph.id === node.id) :
      null;
  }
}
<commit_msg>using box-sizing for all morphs<commit_after>import { promise } from "lively.lang";
import vdom from "virtual-dom";
import { addOrChangeCSSDeclaration } from "./dom-helper.js";

var {h, diff, patch, create} = vdom;

const defaultCSS = `.morph {
  box-sizing: border-box;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}`;

export class Renderer {

  static default() { return this._default || new this() }

  constructor(world, rootNode, domEnvironment) {
    if (!domEnvironment) {
      if (typeof window !== "undefined" && typeof document !== "undefined")
        domEnvironment = {window, document};
      else
        throw new Error("Morphic renderer cannot find DOM environment (window / document)!");
    }
    if (!world || !world.isMorph)
      throw new Error(`Trying to initialize renderer with an invalid world morph: ${world}`)
    if (!rootNode || !("nodeType" in rootNode))
      throw new Error(`Trying to initialize renderer with an invalid root node: ${rootNode}`)
    this.worldMorph = world;
    world._isWorld = true; // for world() method
    this.rootNode = rootNode;
    this.domNode = null;
    this.domEnvironment = domEnvironment;
    this.renderMap = new WeakMap();
    this.renderWorldLoopProcess = null;
  }

  clear() {
    this.stopRenderWorldLoop();
    this.domNode && this.domNode.parentNode.removeChild(this.domNode);
    this.domNode = null;
    this.renderMap = new WeakMap();
  }

  ensureDefaultCSS() {
    return promise.waitFor(3000, () => this.domNode.ownerDocument)
      .then(doc => addOrChangeCSSDeclaration("lively-morphic-css", defaultCSS, doc))
  }

  startRenderWorldLoop() {
    this.renderWorld();
    this.renderWorldLoopProcess = this.domEnvironment.window.requestAnimationFrame(() =>
      this.startRenderWorldLoop());
  }

  stopRenderWorldLoop() {
    this.domEnvironment.window.cancelAnimationFrame(this.renderWorldLoopProcess);
    this.renderWorldLoopProcess = null;
  }

  renderWorld() {
    var world = this.worldMorph;

    if (!world.needsRerender()) return;

    var tree = this.renderMap.get(world) || this.renderMorph(world),
        domNode = this.domNode || (this.domNode = create(tree, this.domEnvironment)),
        newTree = this.renderMorph(world),
        patches = diff(tree, newTree);

    if (!domNode.parentNode) {
      this.rootNode.appendChild(domNode);
      this.ensureDefaultCSS();
    }

    patch(domNode, patches);
  }

  renderMorph(morph) {
    if (!morph.needsRerender()) {
      var rendered = this.renderMap.get(morph);
      if (rendered) return rendered;
    }
    morph.aboutToRender();

    const shapedStyle = Object.assign({
        position: "absolute",
        visibility: morph.visible ? "visible" : "hidden",
        left: morph.position.x + 'px',
        top: morph.position.y + 'px',
        width: morph.extent.x + 'px',
        height: morph.extent.y + 'px',
        backgroundColor: morph.fill ? morph.fill.toString() : "",
        overflow: morph.clipMode,
        "pointer-events": morph.reactsToPointer ? "auto" : "none"
    }, morph.shape().style);

    const attributes = Object.assign(
      morph.shape(), {
        id: morph.id,
        className: "morph",
        draggable: false,
        style: shapedStyle
     });

    var tree = h(morph._nodeType,
                attributes,
                morph.submorphs.map(m => this.renderMorph(m)));

    this.renderMap.set(morph, tree);
    return tree;
  }

  getNodeForMorph(morph) {
    // Hmm, this also finds dom nodes not associated with this renderer, its
    // domNode... Is this a problem?
    return this.domNode.ownerDocument.getElementById(morph.id);
  }

  getMorphForNode(node) {
    return this.worldMorph ?
      this.worldMorph.withAllSubmorphsDetect(morph => morph.id === node.id) :
      null;
  }
}
<|endoftext|>


<commit_before>var PORT = process.env.PORT || process.argv[2] || 3000;
var DEBUG = true;

// dependencies
var express = require("express");
var nodetiles = require("nodetiles-core");
var projector = nodetiles.projector;
var fs = require("fs");
var cartoStyle = fs.readFileSync("./style.mss", "utf8");

// web serving
var app = module.exports = express();
app.use("/assets", express.static(__dirname + "/assets"));
app.use(express.bodyParser({limit: "10mb"}));

app.configure("development", function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure("production", function(){
  app.use(express.errorHandler());
});

// Serve index.html
app.get("/", function(req, res) {
  res.sendfile(__dirname + "/index.html");
});

// Post some GeoJSON data to a tile coordinate, get a rendered tile back!
app.post('/tiles/:zoom/:x/:y.png', function(req, res) {
  var data = req.is("json") ? req.body : JSON.parse(req.body.data);
  var zoom = parseInt(req.params.zoom, 10),
      x = parseInt(req.params.x, 10),
      y = parseInt(req.params.y, 10),
      bounds = projector.util.tileToMeters(x, y, zoom);

  var map = new nodetiles.Map();
  map.addStyle(cartoStyle);
  map.addData({
    sourceName: "data", // for the stylesheet to use
    getShapes: function(minX, minY, maxX, maxY, mapProjection) {
      return projector.project.FeatureCollection("EPSG:4326", mapProjection, data);
    }
  });

  map.render({
    bounds: {minX: bounds[0], minY: bounds[1], maxX: bounds[2], maxY: bounds[3]},
    width: 256,
    height: 256,
    zoom: zoom,
    callback: function(err, canvas) {
      res.type("png");
      canvas.createPNGStream().pipe(res);
    }
  });
});

// GO GO GO!
app.listen(PORT);
console.log("Express server listening on port %d in %s mode", PORT, app.settings.env);
<commit_msg>Oh yeah, this should handle more than just feature collections<commit_after>var PORT = process.env.PORT || process.argv[2] || 3000;
var DEBUG = true;

// dependencies
var express = require("express");
var nodetiles = require("nodetiles-core");
var projector = nodetiles.projector;
var fs = require("fs");
var cartoStyle = fs.readFileSync("./style.mss", "utf8");

// web serving
var app = module.exports = express();
app.use("/assets", express.static(__dirname + "/assets"));
app.use(express.bodyParser({limit: "10mb"}));

app.configure("development", function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure("production", function(){
  app.use(express.errorHandler());
});

// Serve index.html
app.get("/", function(req, res) {
  res.sendfile(__dirname + "/index.html");
});

// Post some GeoJSON data to a tile coordinate, get a rendered tile back!
app.post('/tiles/:zoom/:x/:y.png', function(req, res) {
  var data = req.is("json") ? req.body : JSON.parse(req.body.data);
  var zoom = parseInt(req.params.zoom, 10),
      x = parseInt(req.params.x, 10),
      y = parseInt(req.params.y, 10),
      bounds = projector.util.tileToMeters(x, y, zoom);

  var map = new nodetiles.Map();
  map.addStyle(cartoStyle);
  map.addData({
    sourceName: "data", // for the stylesheet to use
    getShapes: function(minX, minY, maxX, maxY, mapProjection) {
      return projector.project[data.type]("EPSG:4326", mapProjection, data);
    }
  });

  map.render({
    bounds: {minX: bounds[0], minY: bounds[1], maxX: bounds[2], maxY: bounds[3]},
    width: 256,
    height: 256,
    zoom: zoom,
    callback: function(err, canvas) {
      res.type("png");
      canvas.createPNGStream().pipe(res);
    }
  });
});

// GO GO GO!
app.listen(PORT);
console.log("Express server listening on port %d in %s mode", PORT, app.settings.env);
<|endoftext|>


<commit_before>var restify = require('restify');
var fs = require('fs');

var server = restify.createServer({
  name: 'repkam09.com',
  version: '1.0.0'
});

var prefix = 'repserv';

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.CORS());
server.use(restify.fullResponse());
server.use(restify.bodyParser());

// Handles the configuration values for the tempmon service
server.get(prefix + '/tempmon/config', function (req, res, next) {

  // Create a new response object
  var response = {};
  response.reqtime = 6;
  response.emailarray = ['mark@repkam09.com', 'repkam09@gmail.com'];

  // Send the response to the client
  res.send(response);
  return next();
});

// Handles recording the temp value and timestamp for the tempmon service
server.get(prefix + '/tempmon/:temp', function (req, res, next) {
  var response = {};
  response.date = new Date().getTime();
  response.temp = req.params.temp

  // Write the results to a text file
  var fileString = response.date + " | " + response.temp;
  logfileout(fileString, "templogfile.txt");

  // Send the response to the client
  res.send(response);
  return next();
});

server.get(prefix + '/logging/:log', function (req, res, next) {
  var response = {};
  response.status = '200';
  response.msg = "OK";

  // Write the results to a text file
  logfileout(req.params.log, "loglogfile.txt");

  // Send the response to the client
  res.send(response);
  return next();
});

// Start the server:
server.listen(8080, function () {
  console.log('%s listening at %s', server.name, server.url);
});

// Helper function to write to a file
function logfileout(message, filename) {
  fs.appendFile(filename, message + '\r\n', function (err) {
    if (err) {
      console.log(err);
    }
  });
}<commit_msg>Changed port<commit_after>var restify = require('restify');
var fs = require('fs');

var server = restify.createServer({
  name: 'repkam09.com',
  version: '1.0.0'
});

var prefix = 'repserv';

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.CORS());
server.use(restify.fullResponse());
server.use(restify.bodyParser());

// Handles the configuration values for the tempmon service
server.get(prefix + '/tempmon/config', function (req, res, next) {

  // Create a new response object
  var response = {};
  response.reqtime = 6;
  response.emailarray = ['mark@repkam09.com', 'repkam09@gmail.com'];

  // Send the response to the client
  res.send(response);
  return next();
});

// Handles recording the temp value and timestamp for the tempmon service
server.get(prefix + '/tempmon/:temp', function (req, res, next) {
  var response = {};
  response.date = new Date().getTime();
  response.temp = req.params.temp

  // Write the results to a text file
  var fileString = response.date + " | " + response.temp;
  logfileout(fileString, "templogfile.txt");

  // Send the response to the client
  res.send(response);
  return next();
});

server.get(prefix + '/logging/:log', function (req, res, next) {
  var response = {};
  response.status = '200';
  response.msg = "OK";

  // Write the results to a text file
  logfileout(req.params.log, "loglogfile.txt");

  // Send the response to the client
  res.send(response);
  return next();
});

// Start the server:
server.listen(16000, function () {
  console.log('%s listening at %s', server.name, server.url);
});

// Helper function to write to a file
function logfileout(message, filename) {
  fs.appendFile(filename, message + '\r\n', function (err) {
    if (err) {
      console.log(err);
    }
  });
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');

class Reporter {

  constructor(options) {
    this.options = options;
    this._sequence = [];
    this._counts = {};

    if (!fs.existsSync(this.options.path)){
      fs.mkdirSync(this.options.path);
    }

  }

  nowString() {
    return (new Date()).toISOString();
  }

  jasmineStarted(suiteInfo) {
    //this._sequence.push(suiteInfo);
  };

  suiteStarted(result) {
    //this._sequence.push(result);
  };

  specStarted(result) {
    this._start = this.nowString();
    //this._sequence.push(result);
  };

  specDone(result) {
    result.stoped = this.nowString();
    result.started = this._start;
    this._sequence.push(result);
    this._counts[result.status] = (this._counts[result.status] || 0) + 1;
  };

  suiteDone(result) {
    //this._sequence.push(result);
  };

  jasmineDone() {
    let logEntry = {
      sequence: this._sequence,
      counts: this._counts
    };

    let template = path.resolve(__dirname, 'report.html');
    let destination = path.join(this.options.path, 'report.html');

    console.log(template);
    console.log(destination);
    fs.writeFileSync(path.resolve(this.options.path, 'results.json'), JSON.stringify(logEntry, null, 4), 'utf8');
    fs.createReadStream(template).pipe(fs.createWriteStream());
  };
}

module.exports = Reporter;<commit_msg>HTML template<commit_after>'use strict';

const fs = require('fs');
const path = require('path');

class Reporter {

  constructor(options) {
    this.options = options;
    this._sequence = [];
    this._counts = {};

    if (!fs.existsSync(this.options.path)){
      fs.mkdirSync(this.options.path);
    }

  }

  nowString() {
    return (new Date()).toISOString();
  }

  jasmineStarted(suiteInfo) {
    //this._sequence.push(suiteInfo);
  };

  suiteStarted(result) {
    //this._sequence.push(result);
  };

  specStarted(result) {
    this._start = this.nowString();
    //this._sequence.push(result);
  };

  specDone(result) {
    result.stoped = this.nowString();
    result.started = this._start;
    this._sequence.push(result);
    this._counts[result.status] = (this._counts[result.status] || 0) + 1;
  };

  suiteDone(result) {
    //this._sequence.push(result);
  };

  jasmineDone() {
    let logEntry = {
      sequence: this._sequence,
      counts: this._counts
    };

    let template = path.resolve(__dirname, 'report.html');
    let destination = path.join(this.options.path, 'report.html');

    console.log(template);
    console.log(destination);
    fs.writeFileSync(path.resolve(this.options.path, 'results.json'), JSON.stringify(logEntry, null, 4), 'utf8');
    fs.createReadStream(template).pipe(fs.createWriteStream(destination));
  };
}

module.exports = Reporter;<|endoftext|>


<commit_before>/**
 * Created by saubhagya on 28/7/17.
 */
import React, { Component } from 'react'

class ActivityLogCollaborator extends Component{
    constructor(props) {
        super(props);
    }

    onCollaboratorChange = (index, event) => {
        let newArray = this.props.collaborators;
        newArray[index] = event.target.value;
        this.props.onCollabChange(newArray);
    }

    render()
    {
        return (

                {this.props.editable ?

                        Collaborators:{this.props.collaborators.map((collaborator, index) => {
                                return (<input type="text"
                                               value={collaborator}
                                               onChange={(value) => {this.onCollaboratorChange(index, value)}}/>)
                            }
                        )}

 :
                    Collaborators:{this.props.collaborators.map((collaborator, index) => {
                            return (
{collaborator}
)
                        }
                    )}

                }

        )
    }
}

export default ActivityLogCollaborator;
<commit_msg>Refactor ActivityLogCollaborator<commit_after>/**
 * Created by saubhagya on 28/7/17.
 */
import React, { Component } from 'react'

class ActivityLogCollaborator extends Component{
    constructor(props) {
        super(props);
    }

    render()
    {
        return (

                Collaborators:{this.props.collaborators.map((collaborator, index) => {
                        return (
{collaborator}
)
                    }
                )}

        )
    }
}

export default ActivityLogCollaborator;
<|endoftext|>


<commit_before>window.MembranePanel = {
  // private
  cachedConfig: null,

  // private
  isInitialized: false,

  initialize: function() {
    "use strict";

    this.passThroughEditor = CodeMirrorManager.buildNewEditor(
      this.passThroughTextarea
    );

    // CodeMirror uses 0 for the first line of text.
    CodeMirrorManager.getTextLock(this.passThroughEditor, 3, Infinity);
    this.primordialsTextSet = CodeMirrorManager.getTextLock(
      this.passThroughEditor, 0, 2
    );

    this.primordialsCheckbox.addEventListener("change", this, true);
    this.handlePrimordials({target: this.primordialsCheckbox});

    this.passThroughCheckbox.addEventListener("change", this, true);
    this.handlePassThrough({target: this.passThroughCheckbox});

    this.isInitialized = true;
    window.LoadPanel.notifyTestOfInit("MembranePanel");
  },

  handlePrimordials: function(event) {
    const checked = event.target.checked;
    let source = `const PassThroughFilter = (function() {\n  const items = `;
    source += (checked ? "Membrane.Primordials.slice(0)" : "[]") + ";\n";
    this.primordialsTextSet(source);
  },

  handlePassThrough: function(event) {
    const checked = event.target.checked;
    this.primordialsCheckbox.disabled = !checked;
    CodeMirrorManager.setEditorEnabled(this.passThroughEditor, checked);
  },

  handleEvent: function(event) {
    if (event.target === this.primordialsCheckbox)
      return this.handlePrimordials(event);
    if (event.target === this.passThroughCheckbox)
      return this.handlePassThrough(event);
  },

  getPassThrough: function(fullSource = false) {
    if (!fullSource) {
      let lines = this.passThroughEditor.getValue().split("\n");
      lines = lines.slice(2, -6);
      return lines.join("\n");
    }

    let value = this.passThroughEditor.getValue();
    value = value.substr(value.indexOf("("));
    value = value.replace(/;\n$/, ",\n");
    return value;
  },

  update: async function() {
    if (!this.isInitialized)
      this.initialize();

    if (!this.cachedConfig) {
      await this.reset();
      if (this.cachedConfig && this.cachedConfig.membrane) {
        const cf = this.cachedConfig.membrane;
        this.primordialsCheckbox.checked = cf.primordialsPass;
        this.passThroughCheckbox.checked = cf.passThroughEnabled;
        CodeMirrorManager.replaceLineWithSource(
          this.passThroughEditor,
          cf.passThroughSource || "",
          2
        );
      }
    }

    if (LoadPanel.testMode) {
      window.postMessage("MembranePanel updated", window.location.origin);
    }
  },

  reset: async function() {
    try {
      this.cachedConfig = await window.LoadPanel.getConfiguration();
      this.validity.setCustomValidity("");
    }
    catch (e) {
      this.cachedConfig = null;
      this.validity.setCustomValidity(e.message);
      if (window.LoadPanel.testMode) {
        window.postMessage(
          "MembranePanel exception thrown in reset", window.location.origin
        );
      }
      throw e;
    }

    if (window.LoadPanel.testMode) {
      window.postMessage(
        "MembranePanel cached configuration reset", window.location.origin
      );
    }
  },
};

{
  let elems = {
    "form": "grid-outer-membrane-configForm",
    "submitButton": "grid-outer-membrane-graphnames-submit",
    "passThroughCheckbox": "grid-outer-membrane-enablePT",
    "passThroughTextarea": "grid-outer-membrane-passthrough",
    "primordialsCheckbox": "grid-outer-membrane-primordials",
    "validity": "grid-outer-membrane-graphnames-validity",
  };
  let keys = Reflect.ownKeys(elems);
  keys.forEach(function(key) {
    defineElementGetter(window.MembranePanel, key, elems[key]);
  });
}
<commit_msg>#161 GUI, fix Membrane panel import of config, correctly this time.<commit_after>window.MembranePanel = {
  // private
  cachedConfig: null,

  // private
  isInitialized: false,

  initialize: function() {
    "use strict";

    this.passThroughEditor = CodeMirrorManager.buildNewEditor(
      this.passThroughTextarea
    );

    // CodeMirror uses 0 for the first line of text.
    CodeMirrorManager.getTextLock(this.passThroughEditor, 3, Infinity);
    this.primordialsTextSet = CodeMirrorManager.getTextLock(
      this.passThroughEditor, 0, 2
    );

    this.primordialsCheckbox.addEventListener("change", this, true);
    this.handlePrimordials({target: this.primordialsCheckbox});

    this.passThroughCheckbox.addEventListener("change", this, true);
    this.handlePassThrough({target: this.passThroughCheckbox});

    this.importConfig();

    this.isInitialized = true;
    window.LoadPanel.notifyTestOfInit("MembranePanel");
  },

  handlePrimordials: function(event) {
    const checked = event.target.checked;
    let source = `const PassThroughFilter = (function() {\n  const items = `;
    source += (checked ? "Membrane.Primordials.slice(0)" : "[]") + ";\n";
    this.primordialsTextSet(source);
  },

  handlePassThrough: function(event) {
    const checked = event.target.checked;
    this.primordialsCheckbox.disabled = !checked;
    CodeMirrorManager.setEditorEnabled(this.passThroughEditor, checked);
  },

  handleEvent: function(event) {
    if (event.target === this.primordialsCheckbox)
      return this.handlePrimordials(event);
    if (event.target === this.passThroughCheckbox)
      return this.handlePassThrough(event);
  },

  getPassThrough: function(fullSource = false) {
    if (!fullSource) {
      let lines = this.passThroughEditor.getValue().split("\n");
      lines = lines.slice(2, -6);
      return lines.join("\n");
    }

    let value = this.passThroughEditor.getValue();
    value = value.substr(value.indexOf("("));
    value = value.replace(/;\n$/, ",\n");
    return value;
  },

  importConfig: function() {
    if (this.cachedConfig && this.cachedConfig.membrane) {
      const cf = this.cachedConfig.membrane;
      this.primordialsCheckbox.checked = cf.primordialsPass;
      this.passThroughCheckbox.checked = cf.passThroughEnabled;
      CodeMirrorManager.replaceLineWithSource(
        this.passThroughEditor,
        cf.passThroughSource || "",
        2
      );
    }
  },

  update: async function() {
    if (!this.isInitialized)
      this.initialize();

    if (!this.cachedConfig) {
      await this.reset();
      this.importConfig();
    }

    if (LoadPanel.testMode) {
      window.postMessage("MembranePanel updated", window.location.origin);
    }
  },

  reset: async function() {
    try {
      this.cachedConfig = await window.LoadPanel.getConfiguration();
      this.validity.setCustomValidity("");
    }
    catch (e) {
      this.cachedConfig = null;
      this.validity.setCustomValidity(e.message);
      if (window.LoadPanel.testMode) {
        window.postMessage(
          "MembranePanel exception thrown in reset", window.location.origin
        );
      }
      throw e;
    }

    if (window.LoadPanel.testMode) {
      window.postMessage(
        "MembranePanel cached configuration reset", window.location.origin
      );
    }
  },
};

{
  let elems = {
    "form": "grid-outer-membrane-configForm",
    "submitButton": "grid-outer-membrane-graphnames-submit",
    "passThroughCheckbox": "grid-outer-membrane-enablePT",
    "passThroughTextarea": "grid-outer-membrane-passthrough",
    "primordialsCheckbox": "grid-outer-membrane-primordials",
    "validity": "grid-outer-membrane-graphnames-validity",
  };
  let keys = Reflect.ownKeys(elems);
  keys.forEach(function(key) {
    defineElementGetter(window.MembranePanel, key, elems[key]);
  });
}
<|endoftext|>


<commit_before>function Person(name, age) {
    // if object created without the 'new' keyword old browsers
    if (!(this instanceof arguments.callee)) {
        return new arguments.callee(name, age)
    }
    this._name = name;
    this._age = age;
}

// Module pattern
var Module = (function () {

    // Functions here
    var firstFunc = function firstFunc(param) {
        return 'first function';
    }

    var secondFunc = function secondFunc(param) {
        return 'second function';
    }

    // Private functions here
    var _thirdFunc = function _thirdFunc(param) {
        return 'hiden function';
    }

    return {
        firstFunction: firstFunc,
        secondFunction: secondFunc
    }
});
console.log(Module().firstFunction());

// Extend object
// Student.extends(Person);
Object.prototype.extends = function (parent) {
    this.prototype = Object.create(parent.prototype);
    this.prototype.constructor.this;
}

// Console color
console.log("%cBlue!", "color: blue;");

// do something on click
$(".element").live("click", function () {

});

var count = 0;
function myFunction() {
    count++;
    if (count > 5) clearInterval(timeout);
    //do something
}
var timeout = setInterval(myFunction, 20000);

if ($("#elementid").length) {
    //it does!
}

$(document).ready(function () {
    $("a.topLink").click(function () {
        $("html, body").animate({
            scrollTop: $($(this).attr("href")).offset().top + "px"
        }, {
            duration: 500,
            easing: "swing"
        });
        return false;
    });
});

var max_height = 0;
$("div.col").each(function () {
    if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);

jQuery.fn.centerElement = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px")
    return this;
}
$('#item').centerElement();<commit_msg>Method Chaining<commit_after>function Person(name, age) {
    // if object created without the 'new' keyword old browsers
    if (!(this instanceof arguments.callee)) {
        return new arguments.callee(name, age)
    }
    this._name = name;
    this._age = age;
}

// Module pattern
var Module = (function () {

    // Functions here
    var firstFunc = function firstFunc(param) {
        return 'first function';
    }

    var secondFunc = function secondFunc(param) {
        return 'second function';
    }

    // Private functions here
    var _thirdFunc = function _thirdFunc(param) {
        return 'hiden function';
    }

    return {
        firstFunction: firstFunc,
        secondFunction: secondFunc
    }
});
//console.log(Module().firstFunction());

// Method Chaining
var Dog = (function () {

    function Dog() {

    }

    Dog.prototype.setName = function setName(name) {
        this._name = name;
        return this;
    }

    Dog.prototype.setColor = function setColor(color) {
        this._color = color;
        return this;
    }

    return Dog;
}());

var fluffy = new Dog()
    .setName('fluffy')
    .setColor('brown');

console.log(fluffy);

// Extend object
// Student.extends(Person);
Object.prototype.extends = function (parent) {
    this.prototype = Object.create(parent.prototype);
    this.prototype.constructor.this;
}

// Console color
console.log("%cBlue!", "color: blue;");

// do something on click
$(".element").live("click", function () {

});

var count = 0;
function myFunction() {
    count++;
    if (count > 5) clearInterval(timeout);
    //do something
}
var timeout = setInterval(myFunction, 20000);

if ($("#elementid").length) {
    //it does!
}

$(document).ready(function () {
    $("a.topLink").click(function () {
        $("html, body").animate({
            scrollTop: $($(this).attr("href")).offset().top + "px"
        }, {
            duration: 500,
            easing: "swing"
        });
        return false;
    });
});

var max_height = 0;
$("div.col").each(function () {
    if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);

jQuery.fn.centerElement = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px")
    return this;
}
$('#item').centerElement();<|endoftext|>