<commit_before>'use strict'

var gulp = require('gulp')
var rimraf = require('gulp-rimraf')
var tslint = require('gulp-tslint')
var ts = require('gulp-typescript')
var sourcemaps = require('gulp-sourcemaps')
var bowerfiles = require('main-bower-files')
var concat = require('gulp-concat')
var cssmin = require('gulp-cssmin')
var uglify = require('gulp-uglify')
var flatten = require('gulp-flatten')
var util = require('gulp-util')
var watch = require('gulp-watch')
var batch = require('gulp-batch')

var paths = {
  wwwroot: './wwwroot/',
  src: './src/',
  test: './test/'
}

paths.srcTs = paths.src + '**/*.ts'
paths.testTs = paths.test + '**/*.ts'
paths.srcCss = paths.src + '**/*.css'
paths.srcJs = paths.src + '**/*.js'
paths.testJs = paths.test + '**/*.js'
paths.srcJsMap = paths.src + '**/*.js.map'
paths.testJsMap = paths.test + '**/*.js.map'
paths.assets = paths.wwwroot + '**/*.{html,ico}' // Far from perfect :(

paths.concatJsDest = paths.wwwroot + 'js/site.min.js'
paths.concatVendorJsDest = paths.wwwroot + 'js/vendor.min.js'
paths.concatCssDest = paths.wwwroot + 'css/site.min.css'
paths.concatVendorCssDest = paths.wwwroot + 'css/vendor.min.css'
paths.vendorAssets = paths.wwwroot + '**/*.{eot,svg,ttf,woff,woff2}' // Far from perfect :(

var tsProject = ts.createProject('tsconfig.json')
var bootstrapFiles = ['./dist/css/bootstrap.css', './dist/css/bootstrap-theme.css', './dist/fonts/*.*']
var fontawesomeFiles = ['./css/font-awesome.css', './fonts/*.*']

gulp.task('clean:js', function () {
  return gulp.src([
    paths.srcJs,
    paths.srcJsMap,
    paths.testJs,
    paths.testJsMap,
    paths.concatJsDest + '*'], { read: false })
    .pipe(rimraf())
})

gulp.task('clean:css', function () {
  return gulp.src(paths.concatCssDest + '*', { read: false })
    .pipe(rimraf())
})

gulp.task('clean:assets', function () {
  return gulp.src(paths.assets, { read: false })
    .pipe(rimraf())
})

gulp.task('clean:vendor', function () {
  return gulp.src([
    paths.concatVendorJsDest + '*',
    paths.concatVendorCssDest + '*',
    paths.vendorAssets], { read: false })
    .pipe(rimraf())
})

gulp.task('clean:all', function () {
  return gulp.src(paths.wwwroot, { read: false })
    .pipe(rimraf())
})

gulp.task('tslint', function () {
  return gulp.src([paths.srcTs, paths.testTs])
    .pipe(tslint())
    .pipe(tslint.report('verbose'))
})

gulp.task('tscompile', ['tslint', 'clean:js'], function () {
  var tsResult = tsProject.src()
    .pipe(sourcemaps.init())
    .pipe(ts(tsProject))

  return tsResult.js
    .pipe(sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var truncatedSourcePath = sourcePath.substr(sourcePath.lastIndexOf('/') + 1)
        util.log('SourcePath within source map truncated to:', util.colors.cyan(truncatedSourcePath))
        return truncatedSourcePath
      }
    }))
    .pipe(gulp.dest('.'))
})

gulp.task('min:js', ['tscompile'], function () {
  gulp.src([paths.srcJs], { base: '.' })
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(concat(paths.concatJsDest))
    .pipe(sourcemaps.write())
    .pipe(sourcemaps.init())
    // Note that compress: true and mangle: true gives you uglier code,
    // but makes debugging in the browser debugger more difficult.
    .pipe(uglify({compress: false, mangle: false}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('.'))
})

gulp.task('min:css', ['clean:css'], function () {
  gulp.src(paths.srcCss)
    .pipe(sourcemaps.init())
    .pipe(concat(paths.concatCssDest))
    .pipe(cssmin())
    .pipe(sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var extendedSourcePath = paths.src.substr(2) + sourcePath
        util.log('SourcePath within source map extended to:', util.colors.cyan(extendedSourcePath))
        return extendedSourcePath
      }
    }))
    .pipe(gulp.dest('.'))
})

gulp.task('assets', ['clean:assets'], function () {
  gulp.src([paths.src + '**/*', '!' + paths.srcTs, '!' + paths.srcJs, '!' + paths.srcJsMap, '!' + paths.srcCss])
    .pipe(gulp.dest(paths.wwwroot))
})

gulp.task('min:vendorjs', ['clean:vendor'], function () {
  gulp.src(bowerfiles('**/*.js'), { base: '.' })
    .pipe(sourcemaps.init())
    .pipe(concat(paths.concatVendorJsDest))
    .pipe(sourcemaps.write())
    .pipe(sourcemaps.init())
    // Note that compress: true and mangle: true gives you uglier code,
    // but makes debugging in the browser debugger more difficult.
    .pipe(uglify({compress: false, mangle: false}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('.'))
})

gulp.task('min:vendorcss', ['clean:vendor'], function () {
  gulp.src(bowerfiles('**/*.css',
    {overrides: {
      'bootstrap': {main: bootstrapFiles},
      'font-awesome': {main: fontawesomeFiles}
    }}), { base: '.' })
    .pipe(sourcemaps.init())
    .pipe(concat(paths.concatVendorCssDest))
    .pipe(cssmin())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('.'))
})

gulp.task('vendorassets', ['clean:vendor'], function () {
  gulp.src(bowerfiles(['**/*.eot', '**/*.svg', '**/*.ttf', '**/*.woff', '**/*.woff2'],
    {overrides: {
      'bootstrap': {main: bootstrapFiles},
      'font-awesome': {main: fontawesomeFiles}
    }}), { base: '.' })
    .pipe(flatten({includeParents: -1}))
    .pipe(gulp.dest(paths.wwwroot))
})

gulp.task('build:app', ['min:js', 'min:css', 'assets'])

gulp.task('build:vendor', ['min:vendorjs', 'min:vendorcss', 'vendorassets'])

gulp.task('build', ['clean:all'], function (cb) {
  gulp.start('build:app', cb)
  gulp.start('build:vendor', cb)
})

gulp.task('default', ['build'])

// Watch tasks

gulp.task('watch:js', function () {
  watch(paths.srcTs, batch(function (events, done) {
    gulp.start('min:js', done)
  }))
})

gulp.task('watch:css', function () {
  watch(paths.srcCss, batch(function (events, done) {
    gulp.start('min:css', done)
  }))
})

gulp.task('watch:assets', function () {
  watch([paths.src + '**/*', '!' + paths.srcTs, '!' + paths.srcJs, '!' + paths.srcJsMap, '!' + paths.srcCss], batch(function (events, done) {
    gulp.start('assets', done)
  }))
})

gulp.task('watch', ['watch:js', 'watch:css', 'watch:assets'])
<commit_msg>Formatting.<commit_after>'use strict'

var gulp = require('gulp')
var rimraf = require('gulp-rimraf')
var tslint = require('gulp-tslint')
var ts = require('gulp-typescript')
var sourcemaps = require('gulp-sourcemaps')
var bowerfiles = require('main-bower-files')
var concat = require('gulp-concat')
var cssmin = require('gulp-cssmin')
var uglify = require('gulp-uglify')
var flatten = require('gulp-flatten')
var util = require('gulp-util')
var watch = require('gulp-watch')
var batch = require('gulp-batch')

var paths = {
  wwwroot: './wwwroot/',
  src: './src/',
  test: './test/'
}

paths.srcTs = paths.src + '**/*.ts'
paths.testTs = paths.test + '**/*.ts'
paths.srcCss = paths.src + '**/*.css'
paths.srcJs = paths.src + '**/*.js'
paths.testJs = paths.test + '**/*.js'
paths.srcJsMap = paths.src + '**/*.js.map'
paths.testJsMap = paths.test + '**/*.js.map'
paths.assets = paths.wwwroot + '**/*.{html,ico}' // Far from perfect :(

paths.concatJsDest = paths.wwwroot + 'js/site.min.js'
paths.concatVendorJsDest = paths.wwwroot + 'js/vendor.min.js'
paths.concatCssDest = paths.wwwroot + 'css/site.min.css'
paths.concatVendorCssDest = paths.wwwroot + 'css/vendor.min.css'
var vendorExtensions = '**/*.{eot,svg,ttf,woff,woff2}'
paths.vendorAssets = paths.wwwroot + vendorExtensions // Far from perfect :(

var tsProject = ts.createProject('tsconfig.json')
var bootstrapFiles = ['./dist/css/bootstrap.css', './dist/css/bootstrap-theme.css', './dist/fonts/*.*']
var fontawesomeFiles = ['./css/font-awesome.css', './fonts/*.*']

gulp.task('clean:js', function () {
  return gulp.src([
    paths.srcJs,
    paths.srcJsMap,
    paths.testJs,
    paths.testJsMap,
    paths.concatJsDest + '*'], { read: false })
    .pipe(rimraf())
})

gulp.task('clean:css', function () {
  return gulp.src(paths.concatCssDest + '*', { read: false })
    .pipe(rimraf())
})

gulp.task('clean:assets', function () {
  return gulp.src(paths.assets, { read: false })
    .pipe(rimraf())
})

gulp.task('clean:vendor', function () {
  return gulp.src([
    paths.concatVendorJsDest + '*',
    paths.concatVendorCssDest + '*',
    paths.vendorAssets], { read: false })
    .pipe(rimraf())
})

gulp.task('clean:all', function () {
  return gulp.src(paths.wwwroot, { read: false })
    .pipe(rimraf())
})

gulp.task('tslint', function () {
  return gulp.src([paths.srcTs, paths.testTs])
    .pipe(tslint())
    .pipe(tslint.report('verbose'))
})

gulp.task('tscompile', ['tslint', 'clean:js'], function () {
  var tsResult = tsProject.src()
    .pipe(sourcemaps.init())
    .pipe(ts(tsProject))

  return tsResult.js
    .pipe(sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var truncatedSourcePath = sourcePath.substr(sourcePath.lastIndexOf('/') + 1)
        util.log('SourcePath within source map truncated to:', util.colors.cyan(truncatedSourcePath))
        return truncatedSourcePath
      }
    }))
    .pipe(gulp.dest('.'))
})

gulp.task('min:js', ['tscompile'], function () {
  gulp.src([paths.srcJs], { base: '.' })
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(concat(paths.concatJsDest))
    .pipe(sourcemaps.write())
    .pipe(sourcemaps.init())
    // Note that compress: true and mangle: true gives you uglier code,
    // but makes debugging in the browser debugger more difficult.
    .pipe(uglify({compress: false, mangle: false}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('.'))
})

gulp.task('min:css', ['clean:css'], function () {
  gulp.src(paths.srcCss)
    .pipe(sourcemaps.init())
    .pipe(concat(paths.concatCssDest))
    .pipe(cssmin())
    .pipe(sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var extendedSourcePath = paths.src.substr(2) + sourcePath
        util.log('SourcePath within source map extended to:', util.colors.cyan(extendedSourcePath))
        return extendedSourcePath
      }
    }))
    .pipe(gulp.dest('.'))
})

gulp.task('assets', ['clean:assets'], function () {
  gulp.src([paths.src + '**/*', '!' + paths.srcTs, '!' + paths.srcJs, '!' + paths.srcJsMap, '!' + paths.srcCss])
    .pipe(gulp.dest(paths.wwwroot))
})

gulp.task('min:vendorjs', ['clean:vendor'], function () {
  gulp.src(bowerfiles('**/*.js'), { base: '.' })
    .pipe(sourcemaps.init())
    .pipe(concat(paths.concatVendorJsDest))
    .pipe(sourcemaps.write())
    .pipe(sourcemaps.init())
    // Note that compress: true and mangle: true gives you uglier code,
    // but makes debugging in the browser debugger more difficult.
    .pipe(uglify({compress: false, mangle: false}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('.'))
})

gulp.task('min:vendorcss', ['clean:vendor'], function () {
  gulp.src(bowerfiles('**/*.css',
    {overrides: {
      'bootstrap': {main: bootstrapFiles},
      'font-awesome': {main: fontawesomeFiles}
    }}), { base: '.' })
    .pipe(sourcemaps.init())
    .pipe(concat(paths.concatVendorCssDest))
    .pipe(cssmin())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('.'))
})

gulp.task('vendorassets', ['clean:vendor'], function () {
  gulp.src(bowerfiles(vendorExtensions,
    {overrides: {
      'bootstrap': {main: bootstrapFiles},
      'font-awesome': {main: fontawesomeFiles}
    }}), { base: '.' })
    .pipe(flatten({includeParents: -1}))
    .pipe(gulp.dest(paths.wwwroot))
})

gulp.task('build:app', ['min:js', 'min:css', 'assets'])

gulp.task('build:vendor', ['min:vendorjs', 'min:vendorcss', 'vendorassets'])

gulp.task('build', ['clean:all'], function (cb) {
  gulp.start('build:app', cb)
  gulp.start('build:vendor', cb)
})

gulp.task('default', ['build'])

// Watch tasks

gulp.task('watch:js', function () {
  watch(paths.srcTs, batch(function (events, done) {
    gulp.start('min:js', done)
  }))
})

gulp.task('watch:css', function () {
  watch(paths.srcCss, batch(function (events, done) {
    gulp.start('min:css', done)
  }))
})

gulp.task('watch:assets', function () {
  watch([paths.src + '**/*', '!' + paths.srcTs, '!' + paths.srcJs, '!' + paths.srcJsMap, '!' + paths.srcCss], batch(function (events, done) {
    gulp.start('assets', done)
  }))
})

gulp.task('watch', ['watch:js', 'watch:css', 'watch:assets'])
<|endoftext|>


<commit_before>module.exports = function (config) {
  require('./karma.conf.js')(config);
  config.set({
    coverageReporter: {
      reporters: [{
        type: 'text'
      }, {
        type: 'lcov'
      }]
    }
  });
};
<commit_msg>Update lcov reporter to put data in the same place Travis was expecting it before.<commit_after>module.exports = function (config) {
  require('./karma.conf.js')(config);
  config.set({
    coverageReporter: {
      reporters: [{
        type: 'text'
      }, {
        type: 'lcovonly',
        subdir: '.'
      }]
    }
  });
};
<|endoftext|>


<commit_before>var HOST = 'localhost';
var PORT = 1337;

var request = require('request');
var url = require('url');

var express = require('express');
var app = express();

var Twig = require('twig');
app.set('views', __dirname);
app.set('view engine', 'twig');

var router = require('../index.js');
router(app, {
    host: HOST,
    port: PORT,
    baseDir: __dirname,
    file: './routing/main_routing.json'
});

/**
 * @func
 * @param {string} path
 * @returns {string} Absolute URI to path
 */
function getAbsoluteURL(path) {
    return url.format({
        protocol: 'http',
        hostname: HOST,
        port: PORT,
        pathname: (path || '')
    });
}

/**
 * @returns {function}
 */
var counter = (function () {
    var count = 0;

    return function () {
        return count++;
    };
}())

describe('Response from', function () {
    beforeEach(function () {
        // Start server before each test
        this.server = app.listen(PORT, function () {
            this._id = counter();
            console.log('\n[' + this._id + '] expressjs server listening on port ' + PORT + '.');
        });
    });

    afterEach(function (done) {
        // Stop server after each test
        this.server.close(function () {
            console.log('[' + this._id + '] expressjs server on port ' + PORT + ' was stopped!');
            done();
        });
    });

    describe('non-existing URL', function () {
        it('returns status code 404', function (done) {
            request.get(getAbsoluteURL('/non-existent-page/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });
    });

    describe('route without requirement attribute "defaults._controller"', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response, body) {
                expect(body).toMatch(/Could not load controller "" for route "route_without_controller"\./i);
                done();
            });
        });
    });

    describe('simple route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('route for HTML but without template', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response, body) {
                expect(body).toMatch(/Template for route "route_for_html_without_template" is not defined./i);
                done();
            });
        });
    });

    describe('route with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Hello, World!"', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response, body) {
                expect(body).toBe('Hello, World!');
                done();
            });
        });
    });

    describe('route for JSON with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.headers['content-type']).toMatch(/application\/json/i);
                done();
            });
        });

        // @todo: this suit crushes server
        xit('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('route with param', function () {
        it('returns status code 404 for not matched "val3"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val3/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });

        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });

        it('returns status code 200 for matched "val2"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val2\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val2\'');
                done();
            });
        });
    });

    describe('route Only POST method is allowed', function () {
        it('returns status code 405 for GET', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(405);
                done();
            });
        });

        it('returns status code 200 for POST', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });
    });

    // Routes from external_routing.json
    describe('simple external route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('external route with param', function () {
        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });
    });
});
<commit_msg>small fix in test<commit_after>var HOST = 'localhost';
var PORT = 1337;

var request = require('request');
var url = require('url');

var express = require('express');
var app = express();

var Twig = require('twig');
app.set('views', __dirname);
app.set('view engine', 'twig');

var router = require('../index.js');
router(app, {
    host: HOST,
    port: PORT,
    baseDir: __dirname,
    file: './routing/main_routing.json'
});

/**
 * @func
 * @param {string} path
 * @returns {string} Absolute URI to path
 */
function getAbsoluteURL(path) {
    return url.format({
        protocol: 'http',
        hostname: HOST,
        port: PORT,
        pathname: (path || '')
    });
}

/**
 * @returns {function}
 */
var counter = (function () {
    var count = 0;

    return function () {
        return count++;
    };
}())

describe('Response from', function () {
    beforeEach(function () {
        // Start server before each test
        this.server = app.listen(PORT, function () {
            this._id = counter();
            console.log('\n[' + this._id + '] expressjs server listening on port ' + PORT + '.');
        });
    });

    afterEach(function (done) {
        // Stop server after each test
        this.server.close(function () {
            console.log('[' + this._id + '] expressjs server on port ' + PORT + ' was stopped!');
            done();
        });
    });

    describe('non-existing URL', function () {
        it('returns status code 404', function (done) {
            request.get(getAbsoluteURL('/non-existent-page/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });
    });

    describe('route without requirement attribute "defaults._controller"', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-without-controller/'), function (error, response, body) {
                expect(body).toMatch(/Could not load controller "" for route "route_without_controller"\./i);
                done();
            });
        });
    });

    describe('simple route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('route for HTML but without template', function () {
        it('returns status code 500', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response) {
                expect(response.statusCode).toBe(500);
                done();
            });
        });

        it('returns error message', function (done) {
            request.get(getAbsoluteURL('/route-for-html-without-template/'), function (error, response, body) {
                expect(body).toMatch(/Template for route "route_for_html_without_template" is not defined\./i);
                done();
            });
        });
    });

    describe('route with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Hello, World!"', function (done) {
            request.get(getAbsoluteURL('/route-with-template-without-format/'), function (error, response, body) {
                expect(body).toBe('Hello, World!');
                done();
            });
        });
    });

    describe('route for JSON with template', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response) {
                expect(response.headers['content-type']).toMatch(/application\/json/i);
                done();
            });
        });

        // @todo: this suit crushes server
        xit('returns JSON', function (done) {
            request.get(getAbsoluteURL('/route-with-template-for-json/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('route with param', function () {
        it('returns status code 404 for not matched "val3"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val3/'), function (error, response) {
                expect(response.statusCode).toBe(404);
                done();
            });
        });

        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });

        it('returns status code 200 for matched "val2"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val2\'"', function (done) {
            request.get(getAbsoluteURL('/route-with-param/val2/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val2\'');
                done();
            });
        });
    });

    describe('route Only POST method is allowed', function () {
        it('returns status code 405 for GET', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(405);
                done();
            });
        });

        it('returns status code 200 for POST', function (done) {
            request.get(getAbsoluteURL('/only-post-method-allowing/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });
    });

    // Routes from external_routing.json
    describe('simple external route with requirement attributes only', function () {
        it('returns status code 200', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns JSON', function (done) {
            request.get(getAbsoluteURL('/external-route-simple/'), function (error, response, body) {
                expect(JSON.parse(body)).toEqual({
                    data: {}
                });
                done();
            });
        });
    });

    describe('external route with param', function () {
        it('returns status code 200 for matched "val1"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response) {
                expect(response.statusCode).toBe(200);
                done();
            });
        });

        it('returns "Parameter from URL is \'val1\'"', function (done) {
            request.get(getAbsoluteURL('/external-route-with-param/val1/'), function (error, response, body) {
                expect(body).toBe('Parameter from URL is \'val1\'');
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>/*globals window document*/
(function plainOldJs(window, document) {
  'use strict';

  var createChannelButtonElement = document.getElementById('create-channel')
    , joinChannelButtonElement = document.getElementById('join-channel')
    , leaveChannelButtonElement = document.getElementById('leave-channel')
    , userIdentifierTextElement = document.getElementById('user-identifier')
    , roomIdentifierTextElement = document.getElementById('room-identifier')
    , domEvent = 'comunicator:ready'
    , signaler = new window.Signaler([domEvent], 'ws://151.62.53.103:9876', {
        'audio': true,
        'video': false
      }, {
        'mandatory': {
          'OfferToReceiveAudio': true,
          'OfferToReceiveVideo': false
        }
      })
    , token
    , userIdentifier
    , kickOffEvent;

  window.fetch('/token').then(function onSuccess(data) {

    if (data &&
      data.ok) {

      return data.json();
    }
    return {};
  }, function onFailure(failure) {

    window.console.error(failure);
  }).then(function onJsonResponse(jsonResponse) {

    if (jsonResponse &&
      jsonResponse.token &&
      jsonResponse.userID) {

      token = jsonResponse.token;
      userIdentifier = jsonResponse.userID;
      userIdentifierTextElement.value = userIdentifier;
      kickOffEvent = new window.Event(domEvent);

      window.dispatchEvent(kickOffEvent);
    }
  }, function onFailure(failure) {

    window.console.log(failure);
  });

  signaler.then(function onSignalerReady(theSignaler) {

    if (theSignaler) {

      theSignaler.userIsPresent(userIdentifier, token);
      createChannelButtonElement.onclick = function onCreateChannelClick() {

        if (roomIdentifierTextElement &&
          roomIdentifierTextElement.value) {

          theSignaler.createChannel(roomIdentifierTextElement.value);
        } else {

          window.console.error('Manadatory channel name missing.');
        }
      };

      joinChannelButtonElement.onclick = function onJoinChannelClick() {

        if (roomIdentifierTextElement &&
          roomIdentifierTextElement.value) {

          theSignaler.joinChannel(roomIdentifierTextElement.value);
        } else {

          window.console.error('Manadatory channel name missing.');
        }
      };

      leaveChannelButtonElement.onclick = function onLeaveChannelClick() {

        if (roomIdentifierTextElement &&
          roomIdentifierTextElement.value) {

          theSignaler.leaveChannel(roomIdentifierTextElement.value);
          roomIdentifierTextElement.value = '';
        } else {

          window.console.error('Manadatory channel name missing.');
        }
      };
    }
  });

  window.addEventListener('stream:arrive', function onStreamArrival(event) {

    if (event &&
      event.detail &&
      event.detail.mediaElement &&
      event.detail.userid) {

      var audioElement = document.createElement('audio')
        , audioParentElement = document.getElementById('audio');

      window.attachMediaStream(audioElement, event.detail.mediaElement);
      audioElement.id = event.detail.userid;
      audioElement.controls = 'true';
      audioElement.play();

      audioParentElement.appendChild(audioElement);
    }
  }, false);

  window.addEventListener('stream:data-arrived', function onStreamDataArrival(event) {

    if (event &&
      event.detail &&
      event.detail.mediaElement &&
      event.detail.userid) {

      var dataChannelTextElement = document.getElementById('message-on-datachannel');

      dataChannelTextElement.innerHTML(event.detail);
    }
  }, false);

}(window, document));
<commit_msg>little fix<commit_after>/*globals window document*/
(function plainOldJs(window, document) {
  'use strict';

  var createChannelButtonElement = document.getElementById('create-channel')
    , joinChannelButtonElement = document.getElementById('join-channel')
    , leaveChannelButtonElement = document.getElementById('leave-channel')
    , userIdentifierTextElement = document.getElementById('user-identifier')
    , roomIdentifierTextElement = document.getElementById('room-identifier')
    , domEvent = 'comunicator:ready'
    , signaler = new window.Signaler([domEvent], 'ws://151.62.53.103:9876', {
        'audio': true,
        'video': false
      }, {
        'mandatory': {
          'OfferToReceiveAudio': true,
          'OfferToReceiveVideo': false
        }
      })
    , token
    , userIdentifier
    , kickOffEvent;

  window.fetch('/token').then(function onSuccess(data) {

    if (data &&
      data.ok) {

      return data.json();
    }
    return {};
  }, function onFailure(failure) {

    window.console.error(failure);
  }).then(function onJsonResponse(jsonResponse) {

    if (jsonResponse &&
      jsonResponse.token &&
      jsonResponse.userID) {

      token = jsonResponse.token;
      userIdentifier = jsonResponse.userID;
      userIdentifierTextElement.value = userIdentifier;
      kickOffEvent = new window.Event(domEvent);

      window.dispatchEvent(kickOffEvent);
    }
  }, function onFailure(failure) {

    window.console.log(failure);
  });

  signaler.then(function onSignalerReady(theSignaler) {

    if (theSignaler) {

      theSignaler.userIsPresent(userIdentifier, token);
      createChannelButtonElement.onclick = function onCreateChannelClick() {

        if (roomIdentifierTextElement &&
          roomIdentifierTextElement.value) {

          theSignaler.createChannel(roomIdentifierTextElement.value);
        } else {

          window.console.error('Manadatory channel name missing.');
        }
      };

      joinChannelButtonElement.onclick = function onJoinChannelClick() {

        if (roomIdentifierTextElement &&
          roomIdentifierTextElement.value) {

          theSignaler.joinChannel(roomIdentifierTextElement.value);
        } else {

          window.console.error('Manadatory channel name missing.');
        }
      };

      leaveChannelButtonElement.onclick = function onLeaveChannelClick() {

        if (roomIdentifierTextElement &&
          roomIdentifierTextElement.value) {

          theSignaler.leaveChannel(roomIdentifierTextElement.value);
          roomIdentifierTextElement.value = '';
        } else {

          window.console.error('Manadatory channel name missing.');
        }
      };
    }
  });

  window.addEventListener('stream:arrive', function onStreamArrival(event) {

    if (event &&
      event.detail &&
      event.detail.mediaElement &&
      event.detail.userid) {

      var audioElement = document.createElement('audio')
        , audioParentElement = document.getElementById('audio');

      window.attachMediaStream(audioElement, event.detail.mediaElement);
      audioElement.id = event.detail.userid;
      audioElement.controls = 'true';
      audioElement.play();

      audioParentElement.appendChild(audioElement);
    }
  }, false);

  window.addEventListener('stream:data-arrived', function onStreamDataArrival(event) {

    if (event &&
      event.detail &&
      event.detail.mediaElement &&
      event.detail.userid) {

      var dataChannelTextElement = document.getElementById('message-on-datachannel');

      dataChannelTextElement.innerHTML = event.detail;
    }
  }, false);

}(window, document));
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const _ = require('lodash');
const pluralize = require('pluralize');
const { isReservedTableName } = require('../jdl/jhipster/reserved-keywords');
const { stringify } = require('.');

function prepareRelationshipForTemplates(entityWithConfig, relationship, generator, ignoreMissingRequiredRelationship) {
    const entityName = entityWithConfig.name;
    const otherEntityName = relationship.otherEntityName;
    const jhiTablePrefix = entityWithConfig.jhiTablePrefix || generator.getTableName(entityWithConfig.jhiPrefix);

    _.defaults(relationship, {
        // otherEntityField should be id if not specified
        otherEntityField: 'id',
        // let ownerSide true when type is 'many-to-one' for convenience.
        // means that this side should control the reference.
        ownerSide:
            relationship.relationshipType !== 'one-to-many' && (relationship.ownerSide || relationship.relationshipType === 'many-to-one'),
    });

    relationship.otherSideReferenceExists = false;

    const otherEntityData = relationship.otherEntity;
    if (!otherEntityData) {
        throw new Error(`Error at entity ${entityName}: could not find the entity of the relationship ${stringify(relationship)}`);
    }
    otherEntityData.otherRelationships = otherEntityData.otherRelationships || [];
    otherEntityData.otherRelationships.push(relationship);

    relationship.otherEntityIsEmbedded = otherEntityData.embedded;

    if (relationship.otherEntity) {
        relationship.otherEntityPrimaryKeyType = relationship.otherEntity.primaryKeyType;
    }

    // Look for fields at the other other side of the relationship
    if (otherEntityData.relationships) {
        let otherRelationship;
        if (relationship.otherEntityRelationshipName) {
            otherRelationship = otherEntityData.relationships.find(otherSideRelationship => {
                if (_.upperFirst(otherSideRelationship.otherEntityName) !== _.upperFirst(entityName)) {
                    return false;
                }
                return otherSideRelationship.relationshipName === relationship.otherEntityRelationshipName;
            });
            if (
                otherRelationship &&
                otherRelationship.otherEntityRelationshipName &&
                otherRelationship.otherEntityRelationshipName !== relationship.relationshipName
            ) {
                throw new Error(
                    `Error at entity ${entityName}: relationship name is not synchronized ${stringify(relationship)} with ${stringify(
                        otherRelationship
                    )}`
                );
            }
        } else {
            otherRelationship = otherEntityData.relationships.find(otherSideRelationship => {
                if (_.upperFirst(otherSideRelationship.otherEntityName) !== _.upperFirst(entityName)) {
                    return false;
                }
                if (!otherSideRelationship.otherEntityRelationshipName) {
                    return false;
                }
                return otherSideRelationship.otherEntityRelationshipName === relationship.relationshipName;
            });
        }
        if (otherRelationship) {
            relationship.otherSideReferenceExists = true;
            if (
                !(relationship.relationshipType === 'one-to-one' && otherRelationship.relationshipType === 'one-to-one') &&
                !(relationship.relationshipType === 'many-to-one' && otherRelationship.relationshipType === 'one-to-many') &&
                !(relationship.relationshipType === 'one-to-many' && otherRelationship.relationshipType === 'many-to-one') &&
                !(relationship.relationshipType === 'many-to-many' && otherRelationship.relationshipType === 'many-to-many')
            ) {
                throw new Error(
                    `Error at entity ${entityName}: relationship type is not synchronized ${stringify(relationship)} with ${stringify(
                        otherRelationship
                    )}`
                );
            }
            _.defaults(relationship, {
                otherRelationship,
                otherEntityRelationshipName: otherRelationship.relationshipName,
                otherEntityRelationshipNamePlural: otherRelationship.relationshipNamePlural,
                otherEntityRelationshipNameCapitalized: otherRelationship.relationshipNameCapitalized,
                otherEntityRelationshipNameCapitalizedPlural: relationship.relationshipNameCapitalizedPlural,
            });
        } else if (
            !ignoreMissingRequiredRelationship &&
            generator.jhipsterConfig.databaseType !== 'neo4j' &&
            (relationship.relationshipType === 'one-to-many' || relationship.ownerSide === false)
        ) {
            throw new Error(`Error at entity ${entityName}: could not find the other side of the relationship ${stringify(relationship)}`);
        } else {
            generator.debug(`Entity ${entityName}: Could not find the other side of the relationship ${stringify(relationship)}`);
        }
        relationship.otherRelationship = otherRelationship;
    }

    if (relationship.otherEntity && relationship.otherEntityField && relationship.otherEntityField !== 'id') {
        relationship.relatedField = relationship.otherEntity.fields.find(field => field.fieldName === relationship.otherEntityField);
    }

    if (relationship.otherEntityRelationshipName !== undefined) {
        _.defaults(relationship, {
            otherEntityRelationshipNamePlural: pluralize(relationship.otherEntityRelationshipName),
            otherEntityRelationshipNameCapitalized: _.upperFirst(relationship.otherEntityRelationshipName),
        });
        _.defaults(relationship, {
            otherEntityRelationshipNameCapitalizedPlural: pluralize(relationship.otherEntityRelationshipNameCapitalized),
        });
    }

    const relationshipName = relationship.relationshipName;
    _.defaults(relationship, {
        relationshipNamePlural: pluralize(relationshipName),
        relationshipFieldName: _.lowerFirst(relationshipName),
        relationshipNameCapitalized: _.upperFirst(relationshipName),
        relationshipNameHumanized: _.startCase(relationshipName),
        columnName: generator.getColumnName(relationshipName),
        otherEntityNamePlural: pluralize(otherEntityName),
        otherEntityNameCapitalized: _.upperFirst(otherEntityName),
        otherEntityFieldCapitalized: _.upperFirst(relationship.otherEntityField),
        otherEntityTableName:
            otherEntityData.entityTableName ||
            generator.getTableName(generator.isBuiltInUser(otherEntityName) ? `${jhiTablePrefix}_${otherEntityName}` : otherEntityName),
    });

    _.defaults(relationship, {
        relationshipFieldNamePlural: pluralize(relationship.relationshipFieldName),
        relationshipNameCapitalizedPlural:
            relationship.relationshipName.length > 1
                ? pluralize(relationship.relationshipNameCapitalized)
                : _.upperFirst(pluralize(relationship.relationshipName)),
        otherEntityNameCapitalizedPlural: pluralize(relationship.otherEntityNameCapitalized),
    });

    if (entityWithConfig.dto === 'mapstruct') {
        if (otherEntityData.dto !== 'mapstruct' && !generator.isBuiltInUser(otherEntityName)) {
            generator.warning(
                `Entity ${entityName}: this entity has the DTO option, and it has a relationship with entity "${otherEntityName}" that doesn't have the DTO option. This will result in an error.`
            );
        }
    }

    if (isReservedTableName(relationship.otherEntityTableName, entityWithConfig.prodDatabaseType) && jhiTablePrefix) {
        const otherEntityTableName = relationship.otherEntityTableName;
        relationship.otherEntityTableName = `${jhiTablePrefix}_${otherEntityTableName}`;
    }

    if (relationship.otherEntityAngularName === undefined) {
        if (generator.isBuiltInUser(otherEntityName)) {
            relationship.otherEntityAngularName = 'User';
        } else {
            const otherEntityAngularSuffix = otherEntityData ? otherEntityData.angularJSSuffix || '' : '';
            relationship.otherEntityAngularName =
                _.upperFirst(relationship.otherEntityName) + generator.upperFirstCamelCase(otherEntityAngularSuffix);
        }
    }

    _.defaults(relationship, {
        otherEntityStateName: _.kebabCase(relationship.otherEntityAngularName),
        jpaMetamodelFiltering: otherEntityData.jpaMetamodelFiltering && !entityWithConfig.reactive,
    });

    if (!generator.isBuiltInUser(otherEntityName)) {
        _.defaults(relationship, {
            otherEntityFileName: _.kebabCase(relationship.otherEntityAngularName),
            otherEntityFolderName: _.kebabCase(relationship.otherEntityAngularName),
        });

        const otherEntityClientRootFolder = otherEntityData.clientRootFolder || otherEntityData.microserviceName || '';
        if (entityWithConfig.skipUiGrouping || !otherEntityClientRootFolder) {
            relationship.otherEntityClientRootFolder = '';
        } else {
            relationship.otherEntityClientRootFolder = `${otherEntityClientRootFolder}/`;
        }
        if (otherEntityClientRootFolder) {
            if (entityWithConfig.clientRootFolder === otherEntityClientRootFolder) {
                relationship.otherEntityModulePath = relationship.otherEntityFolderName;
            } else {
                relationship.otherEntityModulePath = `${
                    entityWithConfig.entityParentPathAddition ? `${entityWithConfig.entityParentPathAddition}/` : ''
                }${otherEntityClientRootFolder}/${relationship.otherEntityFolderName}`;
            }
            relationship.otherEntityModelName = `${otherEntityClientRootFolder}/${relationship.otherEntityFileName}`;
            relationship.otherEntityPath = `${otherEntityClientRootFolder}/${relationship.otherEntityFolderName}`;
        } else {
            relationship.otherEntityModulePath = `${
                entityWithConfig.entityParentPathAddition ? `${entityWithConfig.entityParentPathAddition}/` : ''
            }${relationship.otherEntityFolderName}`;
            relationship.otherEntityModelName = relationship.otherEntityFileName;
            relationship.otherEntityPath = relationship.otherEntityFolderName;
        }
    }

    // Load in-memory data for root
    if (relationship.relationshipType === 'many-to-many' && relationship.ownerSide) {
        entityWithConfig.fieldsContainOwnerManyToMany = true;
    } else if (relationship.relationshipType === 'one-to-one' && !relationship.ownerSide) {
        entityWithConfig.fieldsContainNoOwnerOneToOne = true;
    } else if (relationship.relationshipType === 'one-to-one' && relationship.ownerSide) {
        entityWithConfig.fieldsContainOwnerOneToOne = true;
    } else if (relationship.relationshipType === 'one-to-many') {
        entityWithConfig.fieldsContainOneToMany = true;
    } else if (relationship.relationshipType === 'many-to-one') {
        entityWithConfig.fieldsContainManyToOne = true;
    }
    if (relationship.otherEntityIsEmbedded) {
        entityWithConfig.fieldsContainEmbedded = true;
    }

    if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) {
        if (entityName.toLowerCase() === relationship.otherEntityName.toLowerCase()) {
            generator.warning(`Error at entity ${entityName}: required relationships to the same entity are not supported.`);
        } else {
            relationship.relationshipValidate = relationship.relationshipRequired = entityWithConfig.validation = true;
        }
    }
    relationship.nullable = !(relationship.relationshipValidate === true && relationship.relationshipRequired);

    const entityType = relationship.otherEntityNameCapitalized;
    if (!entityWithConfig.differentTypes.includes(entityType)) {
        entityWithConfig.differentTypes.push(entityType);
    }
    if (!entityWithConfig.differentRelationships[entityType]) {
        entityWithConfig.differentRelationships[entityType] = [];
    }
    entityWithConfig.differentRelationships[entityType].push(relationship);
    relationship.reference = relationshipToReference(entityWithConfig, relationship);
    return relationship;
}

function relationshipToReference(entity, relationship, pathPrefix = []) {
    const collection = relationship.relationshipType === 'one-to-many' || relationship.relationshipType === 'many-to-many';
    const name = collection ? relationship.relationshipNamePlural : relationship.relationshipName;
    const reference = {
        id: relationship.id,
        entity,
        relationship,
        owned: relationship.ownerSide,
        collection,
        doc: relationship.javaDoc,
        name,
        nameCapitalized: collection ? relationship.relationshipNameCapitalizedPlural : relationship.relationshipNameCapitalized,
        type: relationship.otherEntity.primaryKeyType,
        path: [...pathPrefix, name],
        idReferences: relationship.otherEntity.idFields ? relationship.otherEntity.idFields.map(field => field.reference) : [],
        valueReference: relationship.otherEntityField && relationship.otherEntityField.reference,
    };
    return reference;
}

module.exports = { prepareRelationshipForTemplates, relationshipToReference };
<commit_msg>Fix adding relationships twice to otherRelationships.<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const _ = require('lodash');
const pluralize = require('pluralize');
const { isReservedTableName } = require('../jdl/jhipster/reserved-keywords');
const { stringify } = require('.');

function prepareRelationshipForTemplates(entityWithConfig, relationship, generator, ignoreMissingRequiredRelationship) {
    const entityName = entityWithConfig.name;
    const otherEntityName = relationship.otherEntityName;
    const jhiTablePrefix = entityWithConfig.jhiTablePrefix || generator.getTableName(entityWithConfig.jhiPrefix);

    _.defaults(relationship, {
        // otherEntityField should be id if not specified
        otherEntityField: 'id',
        // let ownerSide true when type is 'many-to-one' for convenience.
        // means that this side should control the reference.
        ownerSide:
            relationship.relationshipType !== 'one-to-many' && (relationship.ownerSide || relationship.relationshipType === 'many-to-one'),
    });

    relationship.otherSideReferenceExists = false;

    const otherEntityData = relationship.otherEntity;
    if (!otherEntityData) {
        throw new Error(`Error at entity ${entityName}: could not find the entity of the relationship ${stringify(relationship)}`);
    }

    relationship.otherEntityIsEmbedded = otherEntityData.embedded;

    if (relationship.otherEntity) {
        relationship.otherEntityPrimaryKeyType = relationship.otherEntity.primaryKeyType;
    }

    // Look for fields at the other other side of the relationship
    if (otherEntityData.relationships) {
        let otherRelationship;
        if (relationship.otherEntityRelationshipName) {
            otherRelationship = otherEntityData.relationships.find(otherSideRelationship => {
                if (_.upperFirst(otherSideRelationship.otherEntityName) !== _.upperFirst(entityName)) {
                    return false;
                }
                return otherSideRelationship.relationshipName === relationship.otherEntityRelationshipName;
            });
            if (
                otherRelationship &&
                otherRelationship.otherEntityRelationshipName &&
                otherRelationship.otherEntityRelationshipName !== relationship.relationshipName
            ) {
                throw new Error(
                    `Error at entity ${entityName}: relationship name is not synchronized ${stringify(relationship)} with ${stringify(
                        otherRelationship
                    )}`
                );
            }
        } else {
            otherRelationship = otherEntityData.relationships.find(otherSideRelationship => {
                if (_.upperFirst(otherSideRelationship.otherEntityName) !== _.upperFirst(entityName)) {
                    return false;
                }
                if (!otherSideRelationship.otherEntityRelationshipName) {
                    return false;
                }
                return otherSideRelationship.otherEntityRelationshipName === relationship.relationshipName;
            });
        }
        if (otherRelationship) {
            relationship.otherSideReferenceExists = true;
            if (
                !(relationship.relationshipType === 'one-to-one' && otherRelationship.relationshipType === 'one-to-one') &&
                !(relationship.relationshipType === 'many-to-one' && otherRelationship.relationshipType === 'one-to-many') &&
                !(relationship.relationshipType === 'one-to-many' && otherRelationship.relationshipType === 'many-to-one') &&
                !(relationship.relationshipType === 'many-to-many' && otherRelationship.relationshipType === 'many-to-many')
            ) {
                throw new Error(
                    `Error at entity ${entityName}: relationship type is not synchronized ${stringify(relationship)} with ${stringify(
                        otherRelationship
                    )}`
                );
            }
            _.defaults(relationship, {
                otherRelationship,
                otherEntityRelationshipName: otherRelationship.relationshipName,
                otherEntityRelationshipNamePlural: otherRelationship.relationshipNamePlural,
                otherEntityRelationshipNameCapitalized: otherRelationship.relationshipNameCapitalized,
                otherEntityRelationshipNameCapitalizedPlural: relationship.relationshipNameCapitalizedPlural,
            });
        } else if (
            !ignoreMissingRequiredRelationship &&
            generator.jhipsterConfig.databaseType !== 'neo4j' &&
            (relationship.relationshipType === 'one-to-many' || relationship.ownerSide === false)
        ) {
            throw new Error(`Error at entity ${entityName}: could not find the other side of the relationship ${stringify(relationship)}`);
        } else {
            generator.debug(`Entity ${entityName}: Could not find the other side of the relationship ${stringify(relationship)}`);
        }
        relationship.otherRelationship = otherRelationship;
    }

    if (relationship.otherEntity && relationship.otherEntityField && relationship.otherEntityField !== 'id') {
        relationship.relatedField = relationship.otherEntity.fields.find(field => field.fieldName === relationship.otherEntityField);
    }

    if (relationship.otherEntityRelationshipName !== undefined) {
        _.defaults(relationship, {
            otherEntityRelationshipNamePlural: pluralize(relationship.otherEntityRelationshipName),
            otherEntityRelationshipNameCapitalized: _.upperFirst(relationship.otherEntityRelationshipName),
        });
        _.defaults(relationship, {
            otherEntityRelationshipNameCapitalizedPlural: pluralize(relationship.otherEntityRelationshipNameCapitalized),
        });
    }

    const relationshipName = relationship.relationshipName;
    _.defaults(relationship, {
        relationshipNamePlural: pluralize(relationshipName),
        relationshipFieldName: _.lowerFirst(relationshipName),
        relationshipNameCapitalized: _.upperFirst(relationshipName),
        relationshipNameHumanized: _.startCase(relationshipName),
        columnName: generator.getColumnName(relationshipName),
        otherEntityNamePlural: pluralize(otherEntityName),
        otherEntityNameCapitalized: _.upperFirst(otherEntityName),
        otherEntityFieldCapitalized: _.upperFirst(relationship.otherEntityField),
        otherEntityTableName:
            otherEntityData.entityTableName ||
            generator.getTableName(generator.isBuiltInUser(otherEntityName) ? `${jhiTablePrefix}_${otherEntityName}` : otherEntityName),
    });

    _.defaults(relationship, {
        relationshipFieldNamePlural: pluralize(relationship.relationshipFieldName),
        relationshipNameCapitalizedPlural:
            relationship.relationshipName.length > 1
                ? pluralize(relationship.relationshipNameCapitalized)
                : _.upperFirst(pluralize(relationship.relationshipName)),
        otherEntityNameCapitalizedPlural: pluralize(relationship.otherEntityNameCapitalized),
    });

    if (entityWithConfig.dto === 'mapstruct') {
        if (otherEntityData.dto !== 'mapstruct' && !generator.isBuiltInUser(otherEntityName)) {
            generator.warning(
                `Entity ${entityName}: this entity has the DTO option, and it has a relationship with entity "${otherEntityName}" that doesn't have the DTO option. This will result in an error.`
            );
        }
    }

    if (isReservedTableName(relationship.otherEntityTableName, entityWithConfig.prodDatabaseType) && jhiTablePrefix) {
        const otherEntityTableName = relationship.otherEntityTableName;
        relationship.otherEntityTableName = `${jhiTablePrefix}_${otherEntityTableName}`;
    }

    if (relationship.otherEntityAngularName === undefined) {
        if (generator.isBuiltInUser(otherEntityName)) {
            relationship.otherEntityAngularName = 'User';
        } else {
            const otherEntityAngularSuffix = otherEntityData ? otherEntityData.angularJSSuffix || '' : '';
            relationship.otherEntityAngularName =
                _.upperFirst(relationship.otherEntityName) + generator.upperFirstCamelCase(otherEntityAngularSuffix);
        }
    }

    _.defaults(relationship, {
        otherEntityStateName: _.kebabCase(relationship.otherEntityAngularName),
        jpaMetamodelFiltering: otherEntityData.jpaMetamodelFiltering && !entityWithConfig.reactive,
    });

    if (!generator.isBuiltInUser(otherEntityName)) {
        _.defaults(relationship, {
            otherEntityFileName: _.kebabCase(relationship.otherEntityAngularName),
            otherEntityFolderName: _.kebabCase(relationship.otherEntityAngularName),
        });

        const otherEntityClientRootFolder = otherEntityData.clientRootFolder || otherEntityData.microserviceName || '';
        if (entityWithConfig.skipUiGrouping || !otherEntityClientRootFolder) {
            relationship.otherEntityClientRootFolder = '';
        } else {
            relationship.otherEntityClientRootFolder = `${otherEntityClientRootFolder}/`;
        }
        if (otherEntityClientRootFolder) {
            if (entityWithConfig.clientRootFolder === otherEntityClientRootFolder) {
                relationship.otherEntityModulePath = relationship.otherEntityFolderName;
            } else {
                relationship.otherEntityModulePath = `${
                    entityWithConfig.entityParentPathAddition ? `${entityWithConfig.entityParentPathAddition}/` : ''
                }${otherEntityClientRootFolder}/${relationship.otherEntityFolderName}`;
            }
            relationship.otherEntityModelName = `${otherEntityClientRootFolder}/${relationship.otherEntityFileName}`;
            relationship.otherEntityPath = `${otherEntityClientRootFolder}/${relationship.otherEntityFolderName}`;
        } else {
            relationship.otherEntityModulePath = `${
                entityWithConfig.entityParentPathAddition ? `${entityWithConfig.entityParentPathAddition}/` : ''
            }${relationship.otherEntityFolderName}`;
            relationship.otherEntityModelName = relationship.otherEntityFileName;
            relationship.otherEntityPath = relationship.otherEntityFolderName;
        }
    }

    // Load in-memory data for root
    if (relationship.relationshipType === 'many-to-many' && relationship.ownerSide) {
        entityWithConfig.fieldsContainOwnerManyToMany = true;
    } else if (relationship.relationshipType === 'one-to-one' && !relationship.ownerSide) {
        entityWithConfig.fieldsContainNoOwnerOneToOne = true;
    } else if (relationship.relationshipType === 'one-to-one' && relationship.ownerSide) {
        entityWithConfig.fieldsContainOwnerOneToOne = true;
    } else if (relationship.relationshipType === 'one-to-many') {
        entityWithConfig.fieldsContainOneToMany = true;
    } else if (relationship.relationshipType === 'many-to-one') {
        entityWithConfig.fieldsContainManyToOne = true;
    }
    if (relationship.otherEntityIsEmbedded) {
        entityWithConfig.fieldsContainEmbedded = true;
    }

    if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) {
        if (entityName.toLowerCase() === relationship.otherEntityName.toLowerCase()) {
            generator.warning(`Error at entity ${entityName}: required relationships to the same entity are not supported.`);
        } else {
            relationship.relationshipValidate = relationship.relationshipRequired = entityWithConfig.validation = true;
        }
    }
    relationship.nullable = !(relationship.relationshipValidate === true && relationship.relationshipRequired);

    const entityType = relationship.otherEntityNameCapitalized;
    if (!entityWithConfig.differentTypes.includes(entityType)) {
        entityWithConfig.differentTypes.push(entityType);
    }
    if (!entityWithConfig.differentRelationships[entityType]) {
        entityWithConfig.differentRelationships[entityType] = [];
    }
    entityWithConfig.differentRelationships[entityType].push(relationship);
    relationship.reference = relationshipToReference(entityWithConfig, relationship);
    return relationship;
}

function relationshipToReference(entity, relationship, pathPrefix = []) {
    const collection = relationship.relationshipType === 'one-to-many' || relationship.relationshipType === 'many-to-many';
    const name = collection ? relationship.relationshipNamePlural : relationship.relationshipName;
    const reference = {
        id: relationship.id,
        entity,
        relationship,
        owned: relationship.ownerSide,
        collection,
        doc: relationship.javaDoc,
        name,
        nameCapitalized: collection ? relationship.relationshipNameCapitalizedPlural : relationship.relationshipNameCapitalized,
        type: relationship.otherEntity.primaryKeyType,
        path: [...pathPrefix, name],
        idReferences: relationship.otherEntity.idFields ? relationship.otherEntity.idFields.map(field => field.reference) : [],
        valueReference: relationship.otherEntityField && relationship.otherEntityField.reference,
    };
    return reference;
}

module.exports = { prepareRelationshipForTemplates, relationshipToReference };
<|endoftext|>


<commit_before>var labs = ["CF162:0:25", "CF164:0:25", "CF414:0:20", "CF416:1:20", "CF418:1:20", "CF405:1:25", "CF404:1:6", "CF409:1:5", "Linux:1:12"];

var countDown = 0;

// Check to see if the page needs to reload.
function checkRun() {
  if (countDown-- <= 0) {
    countDown = 15;
    allLoad();
  }

  document.getElementById("count").innerHTML = countDown + " seconds to next reload.";
}

function firstLoad() {
  var template = "

";
  for(l = 0; l < labs.length; l++) {
    var labData = labs[l].split(":");
    template += "";
    template += "
" + labData[0] + "
";
    for(i = labData[1]; i <= labData[2]; i++) {
      template += "<div id=\"" + labData[0] + ((i < 10) ? "-0" + i : "-" + i) + "\">";
      template += "
" + ((i < 10) ? "0" + i : i) + "

";
    }
    template += "	";
  }
  template += "

";
  document.getElementById("bodyMaster").innerHTML=template;
  setInterval(function(){checkRun()}, 1000); checkRun();
}

function allLoad() {
  for(l = 0; l < labs.length; l++) {
    labData = labs[l].split(":");
    labLoad(labData[0], labData[1], labData[2]);
  }
  d = new Date();
  document.getElementById("updated").innerHTML = "Last updated at " + d.toLocaleTimeString();
}

function labLoad(lab, start, end) {
  for(i = start; i <= end; i++) { machineLoad(lab + ((i < 10) ? "-0" + i : "-" + i)); }
}

function machineLoad(machine) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      var o = JSON.parse(xhr.responseText);
      var html  = "
" + o.m.split("-")[1];
      document.getElementById(o.m).innerHTML = html;
    }
  }
  xhr.open('GET', 'machineStat.php?machine='+machine, true);
  xhr.send(null);
}
<commit_msg>Stop splitting on colon. Make labs an array of objects.<commit_after>var labs = [
  { name: "CF162", first: 0, last: 25 },
  { name: "CF164", first: 0, last: 25 },
  { name: "CF414", first: 0, last: 20 },
  { name: "CF416", first: 1, last: 20 },
  { name: "CF418", first: 1, last: 20 },
  { name: "CF405", first: 1, last: 25 },
  { name: "CF404", first: 1, last: 6 },
  { name: "CF409", first: 1, last: 5 },
  { name: "Linux", first: 1, last: 12 },
]

var countDown = 0;

// Check to see if the page needs to reload.
function checkRun() {
  if (countDown-- <= 0) {
    countDown = 15;
    allLoad();
  }

  document.getElementById("count").innerHTML = countDown + " seconds to next reload.";
}

function firstLoad() {
  var template = "

";
  for(l = 0; l < labs.length; l++) {
    var labData = labs[l];
    template += "";
    template += "
" + labData.name + "
";
    for(i = labData.first; i <= labData.last; i++) {
      template += "<div id=\"" + labData.name + ((i < 10) ? "-0" + i : "-" + i) + "\">";
      template += "
" + ((i < 10) ? "0" + i : i) + "

";
    }
    template += "	";
  }
  template += "

";
  document.getElementById("bodyMaster").innerHTML=template;
  setInterval(function(){checkRun()}, 1000); checkRun();
}

function allLoad() {
  for(l = 0; l < labs.length; l++) {
    var labData = labs[l];
    labLoad(labData);
  }
  d = new Date();
  document.getElementById("updated").innerHTML = "Last updated at " + d.toLocaleTimeString();
}

function labLoad(lab) {
  for(i = lab.first; i <= lab.last; i++) { machineLoad(lab.name + ((i < 10) ? "-0" + i : "-" + i)); }
}

function machineLoad(machine) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      var o = JSON.parse(xhr.responseText);
      var html  = "
" + o.m.split("-")[1];
      document.getElementById(o.m).innerHTML = html;
    }
  }
  xhr.open('GET', 'machineStat.php?machine='+machine, true);
  xhr.send(null);
}
<|endoftext|>


<commit_before>var _ = require("./misc");

var schemeRe = /:\/\//;
var uniqSchemeRe = /:\//;
var selfDirRe = /\/\.\//g;
var prevDirRe = /\/\.\.\//;
var rmPrevDirRe = /[^\/]*\/+\.\.\//;
var slashesRe = /\/+/g;

function _joinUrl(base, part) {
  if (part.length === 0) return base;
  if (schemeRe.test(part)) {
    return part;
  } else {
    return base + "/" + part;
  }
}

function _normalizeUrl(str) {
  // remove ./ parts
  if (selfDirRe.test(str))
    str = str.replace(selfDirRe, "/");

  // remove foo/../ parts
  while(prevDirRe.test(str))
    str = str.replace(rmPrevDirRe, "/");

  // join multiple / except the scheme one
  return str
    .replace(slashesRe, "/")
    .replace(uniqSchemeRe, "://");
}

function resolveURL() {
  var args = _.compact(arguments);
  var len = args.length;
  if (len === 0)
    return "";
  else
    return _normalizeUrl(_.reduce(args, _joinUrl, ""));
}

function parseBaseURL(url) {
  var slash = url.lastIndexOf("/");
  if (slash >= 0) {
    return url.substring(0, slash + 1);
  } else {
    return url;
  }
}

module.exports = { resolveURL, parseBaseURL };
<commit_msg>uri: use URIjs for joining and resolving<commit_after>var _ = require("./misc");
var URIjs = require("URIjs");

function _joinUrl(baseUri, part) {
  if (part.length === 0)
    return baseUri;

  var partUri = new URIjs(part);
  if (partUri.is("relative")) {
    return partUri.absoluteTo(baseUri);
  } else {
    return partUri;
  }
}

function resolveURL() {
  var args = _.compact(arguments);
  var len = args.length;
  if (len === 0)
    return "";
  else {
    return URIjs.decode(_.reduce(args, _joinUrl, new URIjs("")));
  }
}

function parseBaseURL(url) {
  return URIjs.commonPath(url, url);
}

module.exports = { resolveURL, parseBaseURL };
<|endoftext|>


<commit_before>export function getProductThumbnail(product) {
  if (!product) return undefined;
  const defaultImages = product.appImages.default;
  for (const image of defaultImages) {
    if (image.thumbnail) return image;
  }
  return defaultImages[0];
}

export function getProductMainImage(product) {
  if (!product) return undefined;
  const defaultImages = product.appImages.default;
  for (const image of defaultImages) {
    if (image.mainImage) return image;
  }
  return defaultImages[0];
}

export function getProductMainPrice(product, currency) {
  if (!product.productVariants || product.productVariants.length < 1) {
    // TODO handle error
    return 0;
  }
  // TODO find default price
  return product.productVariants[0].price[currency];
}
<commit_msg>handle when product.appImages does not exists<commit_after>function getImages(product) {
  if (!product || !product.appImages) {
    return [];
  }
  return product.appImages.default || [];
}
export function getProductThumbnail(product) {
  const defaultImages = getImages(product);
  if (defaultImages.length < 1) {
    return undefined;
  }
  for (const image of defaultImages) {
    if (image.thumbnail) return image;
  }
  return defaultImages[0];
}

export function getProductMainImage(product) {
  const defaultImages = getImages(product);
  if (defaultImages.length < 1) {
    return undefined;
  }
  for (const image of defaultImages) {
    if (image.mainImage) return image;
  }
  return defaultImages[0];
}

export function getProductMainPrice(product, currency) {
  if (!product.productVariants || product.productVariants.length < 1) {
    // TODO handle error
    return 0;
  }
  // TODO find default price
  return product.productVariants[0].price[currency];
}
<|endoftext|>


<commit_before>Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <no-replay@example.com>";

// Welcome email after enrolled
Accounts.emailTemplates.enrollAccount.from = function() {
  return "AwesomeSite Admin <admin@example.com>";
}
Accounts.emailTemplates.enrollAccount.subject = function (user) {
  return "Welcome to Awesome Town, " + user.username;
};
Accounts.emailTemplates.enrollAccount.text = function (user, url) {
  return "You have been selected to participate in building a better future!"
    + " To activate your account, simply click the link below:\n\n"
    + url;
};

// Reset password E-mail
Accounts.emailTemplates.resetPassword.from = function() {
  return "AwesomeSite Admin <no-replay@example.com>";
}
Accounts.emailTemplates.resetPassword.subject = function (user) {
  return "How to reset your password on " + Meteor.absoluteUrl();
};
Accounts.emailTemplates.resetPassword.text = function (user, url) {
  url = url.replace('#/', '');
  return "Hello " + user.username + ",\n\nTo reset your password, simply click the link below.\n\n" + url + "\n\nThanks.";
};
<commit_msg>Added verifyEmail email template<commit_after>Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <no-replay@example.com>";

// Welcome email after enrolled
Accounts.emailTemplates.enrollAccount.from = function() {
  return "AwesomeSite Admin <admin@example.com>";
}
Accounts.emailTemplates.enrollAccount.subject = function (user) {
  return "Welcome to Awesome Town, " + user.username;
};
Accounts.emailTemplates.enrollAccount.text = function (user, url) {
  return "You have been selected to participate in building a better future!"
    + " To activate your account, simply click the link below:\n\n"
    + url;
};

// Verification email
Accounts.emailTemplates.verifyEmail.from = function() {
  return "AwesomeSite Admin <admin@example.com>";
}
Accounts.emailTemplates.verifyEmail.subject = function (user) {
  return "Please verify your email, " + user.username;
};
Accounts.emailTemplates.verifyEmail.text = function (user, url) {
  url = url.replace('#/', '');
  return "Hello " + user.username + ",\n\nTo verify your email, simply click the link below.\n\n" + url + "\n\nThanks.";
};

// Reset password E-mail
Accounts.emailTemplates.resetPassword.from = function() {
  return "AwesomeSite Admin <no-replay@example.com>";
}
Accounts.emailTemplates.resetPassword.subject = function (user) {
  return "How to reset your password on " + Meteor.absoluteUrl();
};
Accounts.emailTemplates.resetPassword.text = function (user, url) {
  url = url.replace('#/', '');
  return "Hello " + user.username + ",\n\nTo reset your password, simply click the link below.\n\n" + url + "\n\nThanks.";
};
<|endoftext|>


<commit_before>var _os = require('os');

exports.platform = function(){
    return process.platform;
}

exports.cpuCount = function(){
    return _os.cpus().length;
}

exports.sysUptime = function(){
    //seconds
    return _os.uptime();
}

exports.processUptime = function(){
    //seconds
    return process.uptime();
}

// Memory
exports.freemem = function(){
    return _os.freemem() / ( 1024 * 1024 );
}

exports.totalmem = function(){

    return _os.totalmem() / ( 1024 * 1024 );
}

exports.freememPercentage = function(){
    return _os.freemem() / _os.totalmem();
}

exports.freeCommand = function(callback){

    // Only Linux
    require('child_process').exec('free -m', function(error, stdout, stderr) {

       var lines = stdout.split("\n");

       var str_mem_info = lines[1].replace( /[\s\n\r]+/g,' ');

       var mem_info = str_mem_info.split(' ')

       total_mem    = parseFloat(mem_info[1])
       free_mem     = parseFloat(mem_info[3])
       buffers_mem  = parseFloat(mem_info[5])
       cached_mem   = parseFloat(mem_info[6])

       used_mem = total_mem - (free_mem + buffers_mem + cached_mem)

       callback(used_mem -2);
    });
}

// Hard Disk Drive
exports.harddrive = function(callback){

    require('child_process').exec('df -k', function(error, stdout, stderr) {

        var total = 0;
        var used = 0;
        var free = 0;

        var lines = stdout.split("\n");

        var str_disk_info = lines[1].replace( /[\s\n\r]+/g,' ');

        var disk_info = str_disk_info.split(' ');

        total = Math.ceil((disk_info[1] * 1024)/ Math.pow(1024,2));
        used = Math.ceil(disk_info[2] * 1024 / Math.pow(1024,2)) ;
        free = Math.ceil(disk_info[3] * 1024 / Math.pow(1024,2)) ;

        callback(total, free, used);
    });
}

// Return process running current
exports.getProcesses = function(nProcess, callback){

    // if nprocess is undefined then is function
    if(typeof nProcess === 'function'){

        callback =nProcess;
        nProcess = 0
    }

    command = 'ps -eo pcpu,pmem,time,args | sort -k 1 -r | head -n'+10
    //command = 'ps aux | head -n '+ 11
    //command = 'ps aux | head -n '+ (nProcess + 1)
    if (nProcess > 0)
        command = 'ps -eo pcpu,pmem,time,args | sort -k 1 -r | head -n'+(nProcess + 1)

    require('child_process').exec(command, function(error, stdout, stderr) {

        var that = this

        var lines = stdout.split("\n");
        lines.shift()
        lines.pop()

        var result = ''

        lines.forEach(function(_item,_i){

            var _str = _item.replace( /[\s\n\r]+/g,' ');

            _str = _str.split(' ')

            // result += _str[10]+" "+_str[9]+" "+_str[2]+" "+_str[3]+"\n";  // process
            result += _str[1]+" "+_str[2]+" "+_str[3]+" "+_str[4].substring((_str[4].length - 25))+"\n";  // process

        });

        callback(result);
    });
}

/*
* Returns All the load average usage for 1, 5 or 15 minutes.
*/
exports.allLoadavg = function(){

    var loads = _os.loadavg();

    return loads[0].toFixed(4)+','+loads[1].toFixed(4)+','+loads[2].toFixed(4);
}

/*
* Returns the load average usage for 1, 5 or 15 minutes.
*/
exports.loadavg = function(_time){

    if(_time === undefined || (_time !== 5 && _time !== 15) ) _time = 1;

    var loads = _os.loadavg();
    var v = 0;
    if(_time == 1) v = loads[0];
    if(_time == 5) v = loads[1];
    if(_time == 15) v = loads[2];

    return v;
}

exports.cpuFree = function(callback){
    getCPUUsage(callback, true);
}

exports.cpuUsage = function(callback){
    getCPUUsage(callback, false);
}

function getCPUUsage(callback, free){

    var stats1 = getCPUInfo();
    var startIdle = stats1.idle;
    var startTotal = stats1.total;

    setTimeout(function() {
        var stats2 = getCPUInfo();
        var endIdle = stats2.idle;
        var endTotal = stats2.total;

        var idle 	= endIdle - startIdle;
        var total 	= endTotal - startTotal;
        var perc	= idle / total;

        if(free === true)
            callback( perc );
        else
            callback( (1 - perc) );

    }, 1000 * 10 );
}

function getCPUInfo(callback){
    var cpus = _os.cpus();

    var user = 0;
    var nice = 0;
    var sys = 0;
    var idle = 0;
    var irq = 0;
    var total = 0;

    for(var cpu in cpus){

        user += cpus[cpu].times.user;
        nice += cpus[cpu].times.nice;
        sys += cpus[cpu].times.sys;
        irq += cpus[cpu].times.irq;
        idle += cpus[cpu].times.idle;
    }

    var total = user + nice + sys + idle + irq;

    return {
        'idle': idle,
        'total': total
    };
}

<commit_msg>update comments<commit_after>var _os = require('os');

exports.platform = function(){
    return process.platform;
}

exports.cpuCount = function(){
    return _os.cpus().length;
}

exports.sysUptime = function(){
    //seconds
    return _os.uptime();
}

exports.processUptime = function(){
    //seconds
    return process.uptime();
}

// Memory
exports.freemem = function(){
    return _os.freemem() / ( 1024 * 1024 );
}

exports.totalmem = function(){

    return _os.totalmem() / ( 1024 * 1024 );
}

exports.freememPercentage = function(){
    return _os.freemem() / _os.totalmem();
}

exports.freeCommand = function(callback){

    // Only Linux
    require('child_process').exec('free -m', function(error, stdout, stderr) {

       var lines = stdout.split("\n");

       var str_mem_info = lines[1].replace( /[\s\n\r]+/g,' ');

       var mem_info = str_mem_info.split(' ')

       total_mem    = parseFloat(mem_info[1])
       free_mem     = parseFloat(mem_info[3])
       buffers_mem  = parseFloat(mem_info[5])
       cached_mem   = parseFloat(mem_info[6])

       used_mem = total_mem - (free_mem + buffers_mem + cached_mem)

       callback(used_mem -2);
    });
}

// Hard Disk Drive
exports.harddrive = function(callback){

    require('child_process').exec('df -k', function(error, stdout, stderr) {

        var total = 0;
        var used = 0;
        var free = 0;

        var lines = stdout.split("\n");

        var str_disk_info = lines[1].replace( /[\s\n\r]+/g,' ');

        var disk_info = str_disk_info.split(' ');

        total = Math.ceil((disk_info[1] * 1024)/ Math.pow(1024,2));
        used = Math.ceil(disk_info[2] * 1024 / Math.pow(1024,2)) ;
        free = Math.ceil(disk_info[3] * 1024 / Math.pow(1024,2)) ;

        callback(total, free, used);
    });
}

// Return process running current
exports.getProcesses = function(nProcess, callback){

    // if nprocess is undefined then is function
    if(typeof nProcess === 'function'){

        callback =nProcess;
        nProcess = 0
    }

    command = 'ps -eo pcpu,pmem,time,args | sort -k 1 -r | head -n'+10
    //command = 'ps aux | head -n '+ 11
    //command = 'ps aux | head -n '+ (nProcess + 1)
    if (nProcess > 0)
        command = 'ps -eo pcpu,pmem,time,args | sort -k 1 -r | head -n'+(nProcess + 1)

    require('child_process').exec(command, function(error, stdout, stderr) {

        var that = this

        var lines = stdout.split("\n");
        lines.shift()
        lines.pop()

        var result = ''

        lines.forEach(function(_item,_i){

            var _str = _item.replace( /[\s\n\r]+/g,' ');

            _str = _str.split(' ')

            // result += _str[10]+" "+_str[9]+" "+_str[2]+" "+_str[3]+"\n";  // process
            result += _str[1]+" "+_str[2]+" "+_str[3]+" "+_str[4].substring((_str[4].length - 25))+"\n";  // process

        });

        callback(result);
    });
}

/*
* Returns All the load average usage for 1, 5 or 15 minutes.
*/
exports.allLoadavg = function(){

    var loads = _os.loadavg();

    return loads[0].toFixed(4)+','+loads[1].toFixed(4)+','+loads[2].toFixed(4);
}

/*
* Returns the load average usage for 1, 5 or 15 minutes.
*/
exports.loadavg = function(_time){

    if(_time === undefined || (_time !== 5 && _time !== 15) ) _time = 1;

    var loads = _os.loadavg();
    var v = 0;
    if(_time == 1) v = loads[0];
    if(_time == 5) v = loads[1];
    if(_time == 15) v = loads[2];

    return v;
}

exports.cpuFree = function(callback){
    getCPUUsage(callback, true);
}

exports.cpuUsage = function(callback){
    getCPUUsage(callback, false);
}

function getCPUUsage(callback, free){

    var stats1 = getCPUInfo();
    var startIdle = stats1.idle;
    var startTotal = stats1.total;

    setTimeout(function() {
        var stats2 = getCPUInfo();
        var endIdle = stats2.idle;
        var endTotal = stats2.total;

        var idle 	= endIdle - startIdle;
        var total 	= endTotal - startTotal;
        var perc	= idle / total;

        if(free === true)
            callback( perc );
        else
            callback( (1 - perc) );

    }, 1000 * 10 ); // capture CPU after 10 seconds, and measure the ticking between two sampling points.
}

function getCPUInfo(callback){
    var cpus = _os.cpus();

    var user = 0;
    var nice = 0;
    var sys = 0;
    var idle = 0;
    var irq = 0;
    var total = 0;

    for(var cpu in cpus){

        user += cpus[cpu].times.user;
        nice += cpus[cpu].times.nice;
        sys += cpus[cpu].times.sys;
        irq += cpus[cpu].times.irq;
        idle += cpus[cpu].times.idle;
    }

    var total = user + nice + sys + idle + irq;

    return {
        'idle': idle,
        'total': total
    };
}

<|endoftext|>


<commit_before>import Morph from "./Morph.js"

import { Graph } from 'src/client/triples/triples.js';
import lively from 'src/client/lively.js';

export default class AddTriple extends Morph {
  async initialize() {
    this.windowTitle = "Add Triple";

    let title = this.get("#title");
    title.addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.save();
      }
    });

    let input = this.get("#inpChocType");
    let list = this.get("#chocType");
    input.addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        var value = input.val();
        var option = this.ui.attributeList.find("[value='" + value + "']");

        if (option.length > 0) {
          var id = option.data("id");
          // do stuff with the id
        }
        lively.notify(list.value);
      }
    });

    let button = this.get('#save');
    button.addEventListener('click', event => this.save());

    this.prepareOptions('#subject');
    this.prepareOptions('#predicate');
    this.prepareOptions('#object');
  }

  async prepareOptions(listSelector) {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    let selection = this.get(listSelector);
    graph.getKnots().forEach(knot => {
      lively.notify('foo');
      let option = document.createElement('option');
      option.value = knot.url;
      option.text = knot.label();

      selection.appendChild(option);
    });
  }

  async save() {
    let graph = Graph.getInstance();

    let directory = this.get('#directory').value;
    let title = this.get('#title').value;
    let fileEnding = this.get('#file-ending').value;

    graph.createTriple(
      this.get('#subject').value,
      this.get('#predicate').value,
      this.get('#object').value
    );
  }
}
<commit_msg>AUTO-COMMIT templates/add-triple.js<commit_after>import Morph from "./Morph.js"

import { Graph } from 'src/client/triples/triples.js';
import lively from 'src/client/lively.js';

export default class AddTriple extends Morph {
  async initialize() {
    this.windowTitle = "Add Triple";

    let title = this.get("#title");
    title.addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.save();
      }
    });

    let input = this.get("#inpChocType");
    let list = this.get("#chocType");
    input.addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        var value = input.val();
        lively.notify(value);
        var option = this.ui.attributeList.find("[value='" + value + "']");

        if (option.length > 0) {
          var id = option.data("id");
          // do stuff with the id
        }
        lively.notify(list.value);
      }
    });

    let button = this.get('#save');
    button.addEventListener('click', event => this.save());

    this.prepareOptions('#subject');
    this.prepareOptions('#predicate');
    this.prepareOptions('#object');
  }

  async prepareOptions(listSelector) {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    let selection = this.get(listSelector);
    graph.getKnots().forEach(knot => {
      lively.notify('foo');
      let option = document.createElement('option');
      option.value = knot.url;
      option.text = knot.label();

      selection.appendChild(option);
    });
  }

  async save() {
    let graph = Graph.getInstance();

    let directory = this.get('#directory').value;
    let title = this.get('#title').value;
    let fileEnding = this.get('#file-ending').value;

    graph.createTriple(
      this.get('#subject').value,
      this.get('#predicate').value,
      this.get('#object').value
    );
  }
}
<|endoftext|>


<commit_before>// or see http://cors.io/
//const PROXY_CROSS_ORIGIN_ME = 'http://crossorigin.me/';
//const PROXY_CORS_IO = 'http://cors.io/?u=';
const GUERRILLA_API = 'https://api.guerrillamail.com/ajax.php';

var ninjaGuerrillaService = (function(){

  function fetchAction(a, ninja){
    var endpoint = `${GUERRILLA_API}?f=${a}`;

    console.log(`Requesting: ${endpoint}`);
    return fetch(endpoint, {mode: 'cors'})
    .then(rep => {
      return rep.json();
    })
    .then(json => {
      ninja.sidToken = json.sid_token;
      ninjaStorageService.updateNinja(ninja);
      return json;
    })
    .catch(err => {
      console.log('Error requesting guerrilla api ', err);
    }
  );
}

function getNewAddress(ninja){
  return fetchAction("get_email_address", ninja);
}

function getNewEmails( ninja ){
  var seq = 0;
  var lastEmail = ninja.mailbox[0];
  if( lastEmail ){
    seq = lastEmail.mail_id
  }
  return fetchAction(`check_email&seq=${seq}&sid_token=${ninja.sidToken}`, ninja)
  .then(json => {
    if( json.count == 0 )  {
      return Promise.reject("No new email");
    }

    var promises = _.map(json.list, mailExcerpt => fetchAndSaveFullEmail(mailExcerpt, ninja));
    return Promise.all(promises)
    .then(fullEmails => {
      ninjaStorageService.updateNinja(ninja);
      return fullEmails
    });
  });
}

function fetchAndSaveFullEmail(mailExcerpt, ninja){
  return fetchAction(`fetch_email&email_id=${mailExcerpt.mail_id}&sid_token=${ninja.sidToken}`, ninja)
  .then(email => {
    ninja.mailbox.unshift(email);
    return email;
  });
}

return {
  getNewAddress: getNewAddress,
  getNewEmails : getNewEmails
};

})();
<commit_msg>added custom ninjaccount.tk<commit_after>// or see http://cors.io/
//const PROXY_CROSS_ORIGIN_ME = 'http://crossorigin.me/';
//const PROXY_CORS_IO = 'http://cors.io/?u=';
const GUERRILLA_API = 'https://api.guerrillamail.com/ajax.php';
const GUERRILLA_SITE = "ekznp";
const NINJA_DOMAIN = "ninjaccount.tk";

var ninjaGuerrillaService = (function(){

  function fetchAction(a, ninja){
    var endpoint = `${GUERRILLA_API}?f=${a}`;

    console.log(`Requesting: ${endpoint}`);
    return fetch(endpoint, {mode: 'cors'})
    .then(rep => {
      return rep.json();
    })
    .then(json => {
      ninja.sidToken = json.sid_token;
      ninjaStorageService.updateNinja(ninja);
      return json;
    })
    .catch(err => {
      console.log('Error requesting guerrilla api ', err);
    }
  );
}

function getNewAddress(ninja){
  return fetchAction(`get_email_address&site=${GUERRILLA_SITE}`, ninja)
    .then( email => {
      //Does not use the custom domain but a default guerilla one.
      email.email_addr = email.email_addr.replace(/@.*/, '@'+NINJA_DOMAIN);
      return email;
    });
}

function getNewEmails( ninja ){
  var seq = 0;
  var lastEmail = ninja.mailbox[0];
  if( lastEmail ){
    seq = lastEmail.mail_id
  }
  return fetchAction(`check_email&seq=${seq}&sid_token=${ninja.sidToken}`, ninja)
  .then(json => {
    if( json.count == 0 )  {
      return Promise.reject("No new email");
    }

    var promises = _.map(json.list, mailExcerpt => fetchAndSaveFullEmail(mailExcerpt, ninja));
    return Promise.all(promises)
    .then(fullEmails => {
      ninjaStorageService.updateNinja(ninja);
      return fullEmails
    });
  });
}

function fetchAndSaveFullEmail(mailExcerpt, ninja){
  return fetchAction(`fetch_email&email_id=${mailExcerpt.mail_id}&sid_token=${ninja.sidToken}`, ninja)
  .then(email => {
    ninja.mailbox.unshift(email);
    return email;
  });
}

return {
  getNewAddress: getNewAddress,
  getNewEmails : getNewEmails
};

})();
<|endoftext|>


<commit_before>!function(e){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],e):e(ko,ko.mapping={})}(function(e,n){var t={},r=Array.prototype.forEach,o=Object.prototype.toString,i=Array.isArray||function(e){return"[object Array]"===o.call(e)},u=function(e){return"[object String]"===o.call(e)},f=function(e){return e===Object(e)},c=function(e){return e===!0||e===!1||"[object Boolean]"===o.call(e)},a=function(e){return o.call(e)==="[object "+Number+"]"||!isNaN(e)},l=function(e){return o.call(e)==="[object "+Function+"]"},p=function(e){return o.call(e)==="[object "+Date+"]"};"function"!=typeof/./&&(l=function(e){return"function"==typeof e});var s=function(e,n,o){if(null!==e)if(r&&e.forEach===r)e.forEach(n,o);else if(i(e)){for(var u=0,f=e.length;f>u;u+=1)if(n.call(o,e[u],u,e)===t)return}else for(var c in e)if(n.call(o,e[c],c,e)===t)return};n.toJSONByPrototype=e.toJSONByPrototype=function(e,n){var t=e,r=function(e,n,t){return Object.keys(n).forEach(function(o){if(t[o]){var p=n[o];if(i(p))if(e[o]=[],i(t[o]))e[o]=t[o];else{var b=t[o](),d=p.length>0&&p[0]&&f(p[0]);d?s(b,function(n){e[o].push(r({},p[0],n))}):s(b,function(n){e[o].push(l(n)?n():n)})}else if(u(p)||a(p)||c(p))e[o]=l(t[o])?t[o]():t[o];else{if(l(p))return;if(f(p)&&l(p.read)&&l(p.write))return;f(p)&&(e[o]={},r(e[o],p,p._observable?t[o]():t[o]))}}}),e};return r({},n,t)},n.resetViewModel=e.resetViewModel=function(e){var n=e,t=function(e){return e?(l(e)?e.originalValue&&e(e.originalValue()):f(e)&&s(e,function(n,r){t(e[r])}),e):void 0};t(n)},n.updateViewModel=e.updateViewModel=function(e,t){var r=e,o=function(e,t,r){return e&&t&&s(e,function(e,p){if(t[p]){var b=r+"."+p;if(i(e)&&t[p]){t[p]([]);var d=e.length>0&&e[0]&&f(e[0]);d?s(e,function(e){t[p].push(n.mapObject({},e))}):t[p](e)}else if(u(e)||a(e)||c(e))t[p]&&l(t[p])&&t[p](e);else{if(l(e))return;if(f(e)&&l(e.read)&&l(e.write))return;f(e)&&o(e,t[p],b)}}}),t};o(t,r,"")},e.extenders.originalValue=function(n,t){n.originalValue||(n.originalValue=e.observable(t))},n.mapObject=e.mapObject=function(n,t,r,o,b){var d=n,v=t,y=r||{},h=o||{},g=b||{},j=function(n,t,r,o){var b=r||{};return s(n,function(n,r){if("_observable"!==r)if(i(n)){t[r]=e.observableArray(),b[r]&&t[r].extend(i(b[r])&&b[r].length>0?b[r][0]:b[r]);var d=n.length>0&&n[0]&&f(n[0]);d?s(n,function(e){t[r].push(j(e,{},{},o))}):s(n,function(e){t[r].push(e)})}else if(u(n)||a(n)||c(n)||p(n))t[r]=e.observable(n).extend({originalValue:n}),b[r]&&t[r].extend(b[r]);else{if(l(n))return;if(f(n)&&l(n.read)&&l(n.write))return;f(n)&&(t[r]=n._observable?e.observable():{},j(n,t[r],b[r],o))}}),t},V=function(n,t,r){return s(n,function(n,o){if(i(n)){var b=n.length>0&&n[0]&&f(n[0]);b&&s(n,function(e){j(e,{},r)})}else{if(u(n)||a(n)||c(n)||p(n))return;l(n)?t[o]=e.pureComputed(n,r):f(n)&&l(n.read)&&l(n.write)?t[o]=e.pureComputed(n,r):f(n)&&V(n,t[o],r)}}),t},m=function(e,n,t){s(e,function(e,r){i(e)?(n[r]=[],s(e,function(e){n[r].push(l(e)?e.bind(t):e)})):l(e)?n[r]=e.bind(t):f(e)&&(n[r]||(n[r]={}),m(e,n[r],t))})};return s(g,function(e,n){d[n]=e}),j(v,d,y,d),V(v,d,d),m(h,d,d),d.init&&d.init(),d}});<commit_msg>custom functions as extension added<commit_after>!function(e){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],e):e(ko,ko.mapping={})}(function(e,n){function t(e,n){e.extend(p(n)?{fn:n,priority:256}:n)}var r={},o=Array.prototype.forEach,i=Object.prototype.toString,u=Array.isArray||function(e){return"[object Array]"===i.call(e)},f=function(e){return"[object String]"===i.call(e)},c=function(e){return e===Object(e)},a=function(e){return e===!0||e===!1||"[object Boolean]"===i.call(e)},l=function(e){return i.call(e)==="[object "+Number+"]"||!isNaN(e)},p=function(e){return i.call(e)==="[object "+Function+"]"},s=function(e){return i.call(e)==="[object "+Date+"]"};"function"!=typeof/./&&(p=function(e){return"function"==typeof e});var b=function(e,n,t){if(null!==e)if(o&&e.forEach===o)e.forEach(n,t);else if(u(e)){for(var i=0,f=e.length;f>i;i+=1)if(n.call(t,e[i],i,e)===r)return}else for(var c in e)if(n.call(t,e[c],c,e)===r)return};n.toJSONByPrototype=e.toJSONByPrototype=function(e,n){var t=e,r=function(e,n,t){return Object.keys(n).forEach(function(o){if(t[o]){var i=n[o];if(u(i))if(e[o]=[],u(t[o]))e[o]=t[o];else{var s=t[o](),d=i.length>0&&i[0]&&c(i[0]);d?b(s,function(n){e[o].push(r({},i[0],n))}):b(s,function(n){e[o].push(p(n)?n():n)})}else if(f(i)||l(i)||a(i))e[o]=p(t[o])?t[o]():t[o];else{if(p(i))return;if(c(i)&&p(i.read)&&p(i.write))return;c(i)&&(e[o]={},r(e[o],i,i._observable?t[o]():t[o]))}}}),e};return r({},n,t)},n.resetViewModel=e.resetViewModel=function(e){var n=e,t=function(e){return e?(p(e)?e.originalValue&&e(e.originalValue()):c(e)&&b(e,function(n,r){t(e[r])}),e):void 0};t(n)},n.updateViewModel=e.updateViewModel=function(e,t){var r=e,o=function(e,t,r){return e&&t&&b(e,function(e,i){if(t[i]){var s=r+"."+i;if(u(e)&&t[i]){t[i]([]);var d=e.length>0&&e[0]&&c(e[0]);d?b(e,function(e){t[i].push(n.mapObject({},e))}):t[i](e)}else if(f(e)||l(e)||a(e))t[i]&&p(t[i])&&t[i](e);else{if(p(e))return;if(c(e)&&p(e.read)&&p(e.write))return;c(e)&&o(e,t[i],s)}}}),t};o(t,r,"")},e.extenders.originalValue=function(n,t){n.originalValue||(n.originalValue=e.observable(t))},n.mapObject=e.mapObject=function(n,r,o,i,d){var v=n,y=r,h=o||{},g=i||{},j=d||{},V=function(n,r,o,i){var d=o||{};return b(n,function(n,o){if("_observable"!==o)if(u(n)){r[o]=e.observableArray(),d[o]&&t(r[o],u(d[o])&&d[o].length>0?d[o][0]:d[o]);var v=n.length>0&&n[0]&&c(n[0]);v?b(n,function(e){r[o].push(V(e,{},{},i))}):b(n,function(e){r[o].push(e)})}else if(f(n)||l(n)||a(n)||s(n))r[o]=e.observable(n).extend({originalValue:n}),d[o]&&t(r[o],d[o]);else{if(p(n))return;if(c(n)&&p(n.read)&&p(n.write))return;c(n)&&(r[o]=n._observable?e.observable():{},V(n,r[o],d[o],i))}}),r},m=function(n,t,r){return b(n,function(n,o){if(u(n)){var i=n.length>0&&n[0]&&c(n[0]);i&&b(n,function(e){V(e,{},r)})}else{if(f(n)||l(n)||a(n)||s(n))return;p(n)?t[o]=e.pureComputed(n,r):c(n)&&p(n.read)&&p(n.write)?t[o]=e.pureComputed(n,r):c(n)&&m(n,t[o],r)}}),t},w=function(e,n,t){b(e,function(e,r){u(e)?(n[r]=[],b(e,function(e){n[r].push(p(e)?e.bind(t):e)})):p(e)?n[r]=e.bind(t):c(e)&&(n[r]||(n[r]={}),w(e,n[r],t))})};return b(j,function(e,n){v[n]=e}),V(y,v,h,v),m(y,v,v),w(g,v,v),v.init&&v.init(),v}});<|endoftext|>