<commit_before>var mapnik = require('../');
var assert = require('assert');
var fs = require('fs');
var path = require('path');

describe('mapnik.Image ', function() {
    it('should throw with invalid usage', function() {
        // no 'new' keyword
        assert.throws(function() { mapnik.Image(1, 1); });

        // invalid args
        assert.throws(function() { new mapnik.Image(); });
        assert.throws(function() { new mapnik.Image(1); });
        assert.throws(function() { new mapnik.Image('foo'); });
        assert.throws(function() { new mapnik.Image('a', 'b', 'c'); });
    });

    it('should throw with filename lacking an extension', function() {
        var im = new mapnik.Image(256, 256);
        assert.throws(function() { im.save('foo'); });
    });

    it('should throw with invalid encoding format 1', function() {
        var im = new mapnik.Image(256, 256);
        assert.throws(function() { im.encodeSync('foo'); });
    });

    it('should throw with invalid encoding format 2', function() {
        var im = new mapnik.Image(256, 256);
        assert.throws(function() { im.save('foo','foo'); });
    });

    it('should throw with invalid binary read from buffer', function() {
        assert.throws(function() { new mapnik.Image.fromBytesSync(new Buffer(0)); });
        assert.throws(function() { new mapnik.Image.fromBytesSync(new Buffer(1024)); });
        var buffer = new Buffer('\x89\x50\x4E\x47\x0D\x0A\x1A\x0A' + Array(48).join('\0'), 'binary');
        assert.throws(function() { new mapnik.Image.fromBytesSync(buffer); });
        buffer = new Buffer('\x89\x50\x4E\x47\x0D\x0A\x1A\x0A', 'binary');
        assert.throws(function() { new mapnik.Image.fromBytesSync(buffer); });
    });

    it('should throw with invalid encoding format 3', function(done) {
        var im = new mapnik.Image(256, 256);
        im.encode('foo',function(err) {
            assert.ok(err);
            done();
        })
    });

    it('should be initialized properly', function() {
        var im = new mapnik.Image(256, 256);
        assert.ok(im instanceof mapnik.Image);

        assert.equal(im.width(), 256);
        assert.equal(im.height(), 256);
        var v = im.view(0, 0, 256, 256);
        assert.ok(v instanceof mapnik.ImageView);
        assert.equal(v.width(), 256);
        assert.equal(v.height(), 256);
        assert.equal(im.encodeSync().length, v.encodeSync().length);

        im.save('./test/tmp/image.png');

        var im2 = new mapnik.Image.open('./test/tmp/image.png');
        assert.ok(im2 instanceof mapnik.Image);

        assert.equal(im2.width(), 256);
        assert.equal(im2.height(), 256);

        assert.equal(im.encodeSync().length, im2.encodeSync().length);
    });

    it('should be able to open via byte stream', function(done) {
        var im = new mapnik.Image(256, 256);
        // png
        var filename = './test/tmp/image2.png'
        im.save(filename);
        var buffer = fs.readFileSync(filename);
        var im2 = new mapnik.Image.fromBytesSync(buffer);
        assert.ok(im2 instanceof mapnik.Image);
        assert.equal(im2.width(), 256);
        assert.equal(im2.height(), 256);
        assert.equal(im.encodeSync().length, im2.encodeSync().length);
        // jpeg
        var filename2 = './test/tmp/image2.jpeg'
        im.save(filename2);
        var buffer = fs.readFileSync(filename);
        var im3 = new mapnik.Image.fromBytesSync(buffer);
        assert.ok(im3 instanceof mapnik.Image);
        assert.equal(im3.width(), 256);
        assert.equal(im3.height(), 256);
        assert.equal(im.encodeSync().length, im3.encodeSync().length);
        done();
    });

    it('should be initialized properly via async constructors', function(done) {
        var im = new mapnik.Image(256, 256);
        im.save('./test/tmp/image3.png');

        mapnik.Image.open('./test/tmp/image3.png',function(err,im2) {
            if (err) throw err;
            assert.ok(im2 instanceof mapnik.Image);
            assert.equal(im2.width(), 256);
            assert.equal(im2.height(), 256);
            assert.equal(im.encodeSync().length, im2.encodeSync().length);
            mapnik.Image.fromBytes(im.encodeSync(),function(err,im3) {
                if (err) throw err;
                assert.ok(im3 instanceof mapnik.Image);
                assert.equal(im3.width(), 256);
                assert.equal(im3.height(), 256);
                assert.equal(im.encodeSync().length, im3.encodeSync().length);
                done();
            });
        });
    });

    it('should not be painted after rendering', function(done) {
        var im_blank = new mapnik.Image(4, 4);
        assert.equal(im_blank.painted(), false);
        assert.equal(im_blank.background, undefined);

        var m = new mapnik.Map(4, 4);

        m.render(im_blank, {},function(err,im_blank) {
            assert.equal(im_blank.painted(), false);
            assert.equal(im_blank.background, undefined);
            done();
        });
    });

    it('should have background set after rendering', function(done) {
        var im_blank2 = new mapnik.Image(4, 4);
        assert.equal(im_blank2.painted(), false);
        assert.equal(im_blank2.background, undefined);

        var m2 = new mapnik.Map(4, 4);

        m2.background = new mapnik.Color('green');
        m2.render(im_blank2, {},function(err,im_blank2) {
            assert.equal(im_blank2.painted(), false);
            assert.ok(im_blank2.background);
            done();
        });
    });

    it('should be painted after rendering', function(done) {

        var im_blank3 = new mapnik.Image(4, 4);
        assert.equal(im_blank3.painted(), false);
        assert.equal(im_blank3.background, undefined);

        var m3 = new mapnik.Map(4, 4);
        var s = '<Map>';
        s += '<Style name="points">';
        s += ' <Rule>';
        s += '  <PointSymbolizer />';
        s += ' </Rule>';
        s += '</Style>';
        s += '</Map>';
        m3.fromStringSync(s);

        var mem_datasource = new mapnik.MemoryDatasource({'extent': '-180,-90,180,90'});
        mem_datasource.add({ 'x': 0, 'y': 0 });
        mem_datasource.add({ 'x': 1, 'y': 1 });
        mem_datasource.add({ 'x': 2, 'y': 2 });
        mem_datasource.add({ 'x': 3, 'y': 3 });
        var l = new mapnik.Layer('test');
        l.srs = m3.srs;
        l.styles = ['points'];
        l.datasource = mem_datasource;
        m3.add_layer(l);
        m3.zoomAll();
        m3.render(im_blank3, {},function(err,im_blank3) {
            assert.equal(im_blank3.painted(), true);
            assert.equal(im_blank3.background, undefined);
            done();
        });
    });

    it('should support setting the alpha channel based on the amount of gray', function() {
        var gray = new mapnik.Image(256, 256);
        gray.background = new mapnik.Color('white');
        gray.setGrayScaleToAlpha();
        var gray_view = gray.view(0, 0, gray.width(), gray.height());
        assert.equal(gray_view.isSolidSync(), true);
        var pixel = gray.getPixel(0, 0);
        assert.equal(pixel.r, 255);
        assert.equal(pixel.g, 255);
        assert.equal(pixel.b, 255);
        assert.equal(pixel.a, 255);

        gray.background = new mapnik.Color('black');
        gray.setGrayScaleToAlpha();
        var pixel2 = gray.getPixel(0, 0);
        assert.equal(pixel2.r, 255);
        assert.equal(pixel2.g, 255);
        assert.equal(pixel2.b, 255);
        assert.equal(pixel2.a, 0);

        gray.setGrayScaleToAlpha(new mapnik.Color('green'));
        var pixel3 = gray.getPixel(0, 0);
        assert.equal(pixel3.r, 0);
        assert.equal(pixel3.g, 128);
        assert.equal(pixel3.b, 0);
        assert.equal(pixel3.a, 255);
    });

    it('should support setting an individual pixel', function() {
        var gray = new mapnik.Image(256, 256);
        gray.setPixel(0,0,new mapnik.Color('white'));
        var pixel = gray.getPixel(0,0);
        assert.equal(pixel.r, 255);
        assert.equal(pixel.g, 255);
        assert.equal(pixel.b, 255);
        assert.equal(pixel.a, 255);
    });

    it('should support comparing images', function() {
        // if width/height don't match should throw
        assert.throws(function() { new mapnik.Image(256, 256).compare(new mapnik.Image(256, 255)) });
        var one = new mapnik.Image(256, 256);
        // two blank images should exactly match
        assert.equal(one.compare(new mapnik.Image(256, 256)),0);
        // here we set one pixel different
        one.setPixel(0,0,new mapnik.Color('white'));
        assert.equal(one.compare(new mapnik.Image(256, 256)),1);
        // here we set all pixels to be different
        one.background = new mapnik.Color('white');
        assert.equal(one.compare(new mapnik.Image(256, 256)),one.width()*one.height());
        // now lets test comparing just rgb and not alpha
        var two = new mapnik.Image(256, 256);
        // white image but fully alpha
        two.background = new mapnik.Color('rgba(255,255,255,0)');
        // if we consider alpha all pixels should be different
        assert.equal(one.compare(two),one.width()*one.height());
        // but ignoring alpha all pixels should pass as the same
        assert.equal(one.compare(two,{alpha:false}),0);
        // now lets test the threshold option
        // a minorly different color should trigger differences
        var blank = new mapnik.Image(256, 256);
        var blank2 = new mapnik.Image(256, 256);
        blank2.setPixel(0,0,new mapnik.Color('rgba(16,16,16,0)'));
        // should pass because threshold is 16 by default
        assert.equal(blank.compare(blank2),0);
        // with 15 or below threshold should fail
        assert.equal(blank.compare(blank2,{threshold:15}),1);
    });

});
<commit_msg>more image i/o tests (jpeg+tiff+webp)<commit_after>var mapnik = require('../');
var assert = require('assert');
var fs = require('fs');
var path = require('path');

describe('mapnik.Image ', function() {
    it('should throw with invalid usage', function() {
        // no 'new' keyword
        assert.throws(function() { mapnik.Image(1, 1); });

        // invalid args
        assert.throws(function() { new mapnik.Image(); });
        assert.throws(function() { new mapnik.Image(1); });
        assert.throws(function() { new mapnik.Image('foo'); });
        assert.throws(function() { new mapnik.Image('a', 'b', 'c'); });
    });

    it('should throw with filename lacking an extension', function() {
        var im = new mapnik.Image(256, 256);
        assert.throws(function() { im.save('foo'); });
    });

    it('should throw with invalid encoding format 1', function() {
        var im = new mapnik.Image(256, 256);
        assert.throws(function() { im.encodeSync('foo'); });
    });

    it('should throw with invalid encoding format 2', function() {
        var im = new mapnik.Image(256, 256);
        assert.throws(function() { im.save('foo','foo'); });
    });

    it('should throw with invalid binary read from buffer', function() {
        assert.throws(function() { new mapnik.Image.fromBytesSync(new Buffer(0)); });
        assert.throws(function() { new mapnik.Image.fromBytesSync(new Buffer(1024)); });
        var buffer = new Buffer('\x89\x50\x4E\x47\x0D\x0A\x1A\x0A' + Array(48).join('\0'), 'binary');
        assert.throws(function() { new mapnik.Image.fromBytesSync(buffer); });
        buffer = new Buffer('\x89\x50\x4E\x47\x0D\x0A\x1A\x0A', 'binary');
        assert.throws(function() { new mapnik.Image.fromBytesSync(buffer); });
    });

    it('should throw with invalid encoding format 3', function(done) {
        var im = new mapnik.Image(256, 256);
        im.encode('foo',function(err) {
            assert.ok(err);
            done();
        })
    });

    it('should be initialized properly', function() {
        var im = new mapnik.Image(256, 256);
        assert.ok(im instanceof mapnik.Image);

        assert.equal(im.width(), 256);
        assert.equal(im.height(), 256);
        var v = im.view(0, 0, 256, 256);
        assert.ok(v instanceof mapnik.ImageView);
        assert.equal(v.width(), 256);
        assert.equal(v.height(), 256);
        assert.equal(im.encodeSync().length, v.encodeSync().length);

        im.save('./test/tmp/image.png');

        var im2 = new mapnik.Image.open('./test/tmp/image.png');
        assert.ok(im2 instanceof mapnik.Image);

        assert.equal(im2.width(), 256);
        assert.equal(im2.height(), 256);

        assert.equal(im.encodeSync().length, im2.encodeSync().length);
    });

    it('should be able to open via byte stream', function(done) {
        var im = new mapnik.Image(256, 256);
        // png
        var filename = './test/tmp/image2.png'
        im.save(filename);
        var buffer = fs.readFileSync(filename);
        var im2 = new mapnik.Image.fromBytesSync(buffer);
        assert.ok(im2 instanceof mapnik.Image);
        assert.equal(im2.width(), 256);
        assert.equal(im2.height(), 256);
        assert.equal(im.encodeSync().length, im2.encodeSync().length);
        // jpeg
        var filename2 = './test/tmp/image2.jpeg'
        im.save(filename2);
        var buffer = fs.readFileSync(filename);
        var im3 = new mapnik.Image.fromBytesSync(buffer);
        assert.ok(im3 instanceof mapnik.Image);
        assert.equal(im3.width(), 256);
        assert.equal(im3.height(), 256);
        assert.equal(im.encodeSync().length, im3.encodeSync().length);
        done();
    });

    it('should be initialized properly via async constructors', function(done) {
        var im = new mapnik.Image(256, 256);
        im.save('./test/tmp/image3.png');

        mapnik.Image.open('./test/tmp/image3.png',function(err,im2) {
            if (err) throw err;
            assert.ok(im2 instanceof mapnik.Image);
            assert.equal(im2.width(), 256);
            assert.equal(im2.height(), 256);
            assert.equal(im.encodeSync().length, im2.encodeSync().length);
            mapnik.Image.fromBytes(im.encodeSync(),function(err,im3) {
                if (err) throw err;
                assert.ok(im3 instanceof mapnik.Image);
                assert.equal(im3.width(), 256);
                assert.equal(im3.height(), 256);
                assert.equal(im.encodeSync().length, im3.encodeSync().length);
                done();
            });
        });
    });

    it('should not be painted after rendering', function(done) {
        var im_blank = new mapnik.Image(4, 4);
        assert.equal(im_blank.painted(), false);
        assert.equal(im_blank.background, undefined);

        var m = new mapnik.Map(4, 4);

        m.render(im_blank, {},function(err,im_blank) {
            assert.equal(im_blank.painted(), false);
            assert.equal(im_blank.background, undefined);
            done();
        });
    });

    it('should have background set after rendering', function(done) {
        var im_blank2 = new mapnik.Image(4, 4);
        assert.equal(im_blank2.painted(), false);
        assert.equal(im_blank2.background, undefined);

        var m2 = new mapnik.Map(4, 4);

        m2.background = new mapnik.Color('green');
        m2.render(im_blank2, {},function(err,im_blank2) {
            assert.equal(im_blank2.painted(), false);
            assert.ok(im_blank2.background);
            done();
        });
    });

    it('should be painted after rendering', function(done) {

        var im_blank3 = new mapnik.Image(4, 4);
        assert.equal(im_blank3.painted(), false);
        assert.equal(im_blank3.background, undefined);

        var m3 = new mapnik.Map(4, 4);
        var s = '<Map>';
        s += '<Style name="points">';
        s += ' <Rule>';
        s += '  <PointSymbolizer />';
        s += ' </Rule>';
        s += '</Style>';
        s += '</Map>';
        m3.fromStringSync(s);

        var mem_datasource = new mapnik.MemoryDatasource({'extent': '-180,-90,180,90'});
        mem_datasource.add({ 'x': 0, 'y': 0 });
        mem_datasource.add({ 'x': 1, 'y': 1 });
        mem_datasource.add({ 'x': 2, 'y': 2 });
        mem_datasource.add({ 'x': 3, 'y': 3 });
        var l = new mapnik.Layer('test');
        l.srs = m3.srs;
        l.styles = ['points'];
        l.datasource = mem_datasource;
        m3.add_layer(l);
        m3.zoomAll();
        m3.render(im_blank3, {},function(err,im_blank3) {
            assert.equal(im_blank3.painted(), true);
            assert.equal(im_blank3.background, undefined);
            done();
        });
    });

    it('should support setting the alpha channel based on the amount of gray', function() {
        var gray = new mapnik.Image(256, 256);
        gray.background = new mapnik.Color('white');
        gray.setGrayScaleToAlpha();
        var gray_view = gray.view(0, 0, gray.width(), gray.height());
        assert.equal(gray_view.isSolidSync(), true);
        var pixel = gray.getPixel(0, 0);
        assert.equal(pixel.r, 255);
        assert.equal(pixel.g, 255);
        assert.equal(pixel.b, 255);
        assert.equal(pixel.a, 255);

        gray.background = new mapnik.Color('black');
        gray.setGrayScaleToAlpha();
        var pixel2 = gray.getPixel(0, 0);
        assert.equal(pixel2.r, 255);
        assert.equal(pixel2.g, 255);
        assert.equal(pixel2.b, 255);
        assert.equal(pixel2.a, 0);

        gray.setGrayScaleToAlpha(new mapnik.Color('green'));
        var pixel3 = gray.getPixel(0, 0);
        assert.equal(pixel3.r, 0);
        assert.equal(pixel3.g, 128);
        assert.equal(pixel3.b, 0);
        assert.equal(pixel3.a, 255);
    });

    it('should support setting an individual pixel', function() {
        var gray = new mapnik.Image(256, 256);
        gray.setPixel(0,0,new mapnik.Color('white'));
        var pixel = gray.getPixel(0,0);
        assert.equal(pixel.r, 255);
        assert.equal(pixel.g, 255);
        assert.equal(pixel.b, 255);
        assert.equal(pixel.a, 255);
    });

    it('should support comparing images', function() {
        // if width/height don't match should throw
        assert.throws(function() { new mapnik.Image(256, 256).compare(new mapnik.Image(256, 255)) });
        var one = new mapnik.Image(256, 256);
        // two blank images should exactly match
        assert.equal(one.compare(new mapnik.Image(256, 256)),0);
        // here we set one pixel different
        one.setPixel(0,0,new mapnik.Color('white'));
        assert.equal(one.compare(new mapnik.Image(256, 256)),1);
        // here we set all pixels to be different
        one.background = new mapnik.Color('white');
        assert.equal(one.compare(new mapnik.Image(256, 256)),one.width()*one.height());
        // now lets test comparing just rgb and not alpha
        var two = new mapnik.Image(256, 256);
        // white image but fully alpha
        two.background = new mapnik.Color('rgba(255,255,255,0)');
        // if we consider alpha all pixels should be different
        assert.equal(one.compare(two),one.width()*one.height());
        // but ignoring alpha all pixels should pass as the same
        assert.equal(one.compare(two,{alpha:false}),0);
        // now lets test the threshold option
        // a minorly different color should trigger differences
        var blank = new mapnik.Image(256, 256);
        var blank2 = new mapnik.Image(256, 256);
        blank2.setPixel(0,0,new mapnik.Color('rgba(16,16,16,0)'));
        // should pass because threshold is 16 by default
        assert.equal(blank.compare(blank2),0);
        // with 15 or below threshold should fail
        assert.equal(blank.compare(blank2,{threshold:15}),1);
    });

    it('should be able to open jpeg', function(done) {
        var im = new mapnik.Image(10,10);
        im.background = new mapnik.Color('green');
        var filename = './test/data/images/10x10.png';
        // sync open
        assert.equal(0,im.compare(new mapnik.Image.open(filename)));
        // sync fromBytes
        assert.equal(0,im.compare(new mapnik.Image.fromBytesSync(im.encodeSync())));
        // async open
        mapnik.Image.open(filename,function(err,im2) {
            if (err) throw err;
            assert.equal(0,im.compare(im2));
            // async fromBytes
            mapnik.Image.fromBytes(im.encodeSync(),function(err,im3) {
                if (err) throw err;
                assert.equal(0,im.compare(im3));
                done();
            });
        });
    });

    it('should be able to open tiff', function(done) {
        var im = new mapnik.Image(10,10);
        im.background = new mapnik.Color('green');
        var filename = './test/data/images/10x10.tiff';
        // sync open
        assert.equal(0,im.compare(new mapnik.Image.open(filename)));
        // sync fromBytes
        assert.equal(0,im.compare(new mapnik.Image.fromBytesSync(im.encodeSync())));
        // async open
        mapnik.Image.open(filename,function(err,im2) {
            if (err) throw err;
            assert.equal(0,im.compare(im2));
            // async fromBytes
            mapnik.Image.fromBytes(im.encodeSync(),function(err,im3) {
                if (err) throw err;
                assert.equal(0,im.compare(im3));
                done();
            });
        });
    });

    it('should be able to open webp', function(done) {
        var im = new mapnik.Image(10,10);
        im.background = new mapnik.Color('green');
        var filename = './test/data/images/10x10.webp';
        // sync open
        assert.equal(0,im.compare(new mapnik.Image.open(filename)));
        // sync fromBytes
        assert.equal(0,im.compare(new mapnik.Image.fromBytesSync(im.encodeSync())));
        // async open
        mapnik.Image.open(filename,function(err,im2) {
            if (err) throw err;
            assert.equal(0,im.compare(im2));
            // async fromBytes
            mapnik.Image.fromBytes(im.encodeSync(),function(err,im3) {
                if (err) throw err;
                assert.equal(0,im.compare(im3));
                done();
            });
        });
    });

});
<|endoftext|>


<commit_before>import Request from './request';
import notify from './notify';
import { options } from './config';

export default class {
    constructor(notifyVue) {
        this.notify = notifyVue;
    }

    getUrl(url, query) {
        url += '?';
        Object.keys(query).map(k => url += k + '=' + query[k] + '&');

        return url.substring(url.length - 1, -1);
    }

    async fetch(query) {
        const resp = await Request.exec(this.getUrl('/list.json', query), options);

        return await resp.json();
    }

    async beforeCreate(sid, type, payload, success, complete, append) {
        let opt = options;
        if (typeof append !== 'undefined') {
            opt = Object.assign(opt, append);
        }

        try {
            const query = { 'sid': sid, 'type': type, 'p': payload };
            const resp = await Request.exec(this.getUrl('/fetch', query), opt);
            success(await resp.json());
        } catch (e) {
            notify(this.notify, e);
        } finally {
            complete();
        }
    }

    async create(sid, payload) {
        try {
            const body = { 'sid': sid, 'p': payload };
            const resp = await Request.exec('/create', Request.postOptions(body));
            notify(this.notify, resp);

            return await resp.json();
        } catch (e) {
            notify(this.notify, e);
        }
    }

    async delete(ids) {
        return await Request.exec('/delete', Request.postOptions({ ids: ids }));
    }

    async edit(entry) {
        return await Request.exec('/edit', Request.postOptions(entry));
    }
}
<commit_msg>構文を微修正<commit_after>import Request from './request';
import notify from './notify';
import { options } from './config';

export default class {
    constructor(notifyVue) {
        this.notify = notifyVue;
    }

    getUrl(url, query) {
        url += '?';
        Object.keys(query).map(k => url += k + '=' + query[k] + '&');

        return url.substring(url.length - 1, -1);
    }

    async fetch(query) {
        const resp = await Request.exec(this.getUrl('/list.json', query), options);

        return await resp.json();
    }

    async beforeCreate(sid, type, payload, success, complete, append) {
        let opt = options;
        if (typeof append !== 'undefined') {
            opt = { ...opt, ...append };
        }

        try {
            const query = { 'sid': sid, 'type': type, 'p': payload };
            const resp = await Request.exec(this.getUrl('/fetch', query), opt);
            success(await resp.json());
        } catch (e) {
            notify(this.notify, e);
        } finally {
            complete();
        }
    }

    async create(sid, payload) {
        try {
            const body = { 'sid': sid, 'p': payload };
            const resp = await Request.exec('/create', Request.postOptions(body));
            notify(this.notify, resp);

            return await resp.json();
        } catch (e) {
            notify(this.notify, e);
        }
    }

    async delete(ids) {
        return await Request.exec('/delete', Request.postOptions({ ids: ids }));
    }

    async edit(entry) {
        return await Request.exec('/edit', Request.postOptions(entry));
    }
}
<|endoftext|>


<commit_before>'use strict';
var express = require('express')
  , M       = express()
  , fs      = require('fs')
  , async   = require('async')
  , path    = require('path')
  , hosts   = require('magic-hosts')
  , log     = require('magic-log')
  , db      = require('magic-db')
  , auth    = require('magic-auth')
  , users   = require('magic-users')
  , magic   = {}
  , env     = ( M.get('env') || 'production' )
  , cwd     = process.cwd()
  , config  = require( path.join(cwd, 'config') )
  , conf    = config.defaults[env] || false
;

magic.spawn = function(cb) {
  //default env is production
  M.set('env', env );

  M.set('port', ( process.env.PORT || 5000) );

  M.set('dirs', {
    'hosts' : path.join( cwd, 'hosts' )
  } );

  if ( conf && conf.db ) {
    let schema = db(conf.db);
    M.set('schema', schema);

    M.use( function(req, res, next) {
      //creates the user database models
      users.init(schema, next);
      auth.init(schema, next);
    } );
  }

  log('M spawned, env = ' + M.get('env'));
  cb(null, M);
}

magic.autoload = function (M, cb) {
  log('autoload mounts');
  hosts.mount(M, function (err, results) {
    log(results);
    cb(err, M);
  } );
}

magic.listen = function (M, cb) {
  M.use(function (req, res, next) {
    if ( conf.host ) {
      res.redirect(conf.host);
    }
  });

  M.listen( M.get('port'), function() {
    if ( typeof cb === 'function' ) { cb(null, M); }
  } );
}

module.exports = function init(cb) {
  async.waterfall([
      magic.spawn
    , magic.autoload
    , magic.listen
  ]
  , function (err, M) {
      if ( err ) { log(err, 'error'); }
      log( 'Magic listening to port:' + M.get('port') );

      if ( typeof cb === 'function') {
        cb(null, M);
      }
    }
  );
}

<commit_msg>updated for new version of magic-log<commit_after>'use strict';
var express = require('express')
  , M       = express()
  , fs      = require('fs')
  , async   = require('async')
  , path    = require('path')
  , hosts   = require('magic-hosts')
  , log     = require('magic-log')
  , db      = require('magic-db')
  , auth    = require('magic-auth')
  , users   = require('magic-users')
  , magic   = {}
  , env     = ( M.get('env') || 'production' )
  , cwd     = process.cwd()
  , config  = require( path.join(cwd, 'config') )
  , conf    = config.defaults[env] || false
;

magic.spawn = function(cb) {
  //default env is production
  M.set('env', env );

  M.set('port', ( process.env.PORT || 5000) );

  M.set('dirs', {
    'hosts' : path.join( cwd, 'hosts' )
  } );

  if ( conf && conf.db ) {
    let schema = db(conf.db);
    M.set('schema', schema);

    M.use( function(req, res, next) {
      //creates the user database models
      users.init(schema, next);
      auth.init(schema, next);
    } );
  }

  log('M spawned, env = ' + M.get('env'));
  cb(null, M);
}

magic.autoload = function (M, cb) {
  log('autoload mounts');
  hosts.mount(M, function (err, results) {
    log(results);
    cb(err, M);
  } );
}

magic.listen = function (M, cb) {
  M.use(function (req, res, next) {
    if ( conf.host ) {
      res.redirect(conf.host);
    }
  });

  M.listen( M.get('port'), function() {
    if ( typeof cb === 'function' ) { cb(null, M); }
  } );
}

module.exports = function init(cb) {
  async.waterfall([
      magic.spawn
    , magic.autoload
    , magic.listen
  ]
  , function (err, M) {
      if ( err ) { log.error(err); }
      log.success( 'Magic listening to port:', M.get('port') );

      if ( typeof cb === 'function') {
        cb(null, M);
      }
    }
  );
}

<|endoftext|>


<commit_before>'use strict';

var assert      = require( 'assert' );
var expect      = require( 'chai' ).expect;
var gutil       = require( 'gulp-util' );
var include     = require( '../index' );
var path        = require( 'path' );

var JS_INCLUDE          = '<script src="include/path/javascript.js"></script>';
var CSS_INCLUDE         = '<link href="include/path/style.css" rel="stylesheet">';
var CSS_INCLUDE_XHTML   = '<link href="include/path/style.css" rel="stylesheet" />';
var JS_ROOT             = '<script src="/javascript.js"></script>';
var CSS_ROOT            = '<link href="/style.css" rel="stylesheet">';
var CSS_ROOT_XHTML      = '<link href="/style.css" rel="stylesheet" />';
var DEFAULT_JS_DEST     = 'javascript.js.html';
var DEFAULT_CSS_DEST    = 'style.css.html';

var out = process.stdout.write;

beforeEach(function () {
    process.stdout.write = function () {};
});

afterEach(function () {
    process.stdout.write = out;
});

describe('File Generation', function () {

    it('should generate HTML files to include JS files', function ( done ) {
        var stream = include({ path: 'include/path' });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_JS_DEST );
            expect( file.contents.toString() ).to.equal( JS_INCLUDE );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

    it('should generate HTML files to include CSS files', function ( done ) {
        var stream = include({ path: 'include/path' });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_CSS_DEST );
            expect( file.contents.toString() ).to.equal( CSS_INCLUDE );
            done();
        });

        stream.write( new gutil.File({
            path: 'style.css',
            contents: new Buffer( '' )
        }));
    });

    it('should generate XHTML-compliant files to include CSS files', function ( done ) {
        var stream = include({ path: 'include/path', xhtml: true });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_CSS_DEST );
            expect( file.contents.toString() ).to.equal( CSS_INCLUDE_XHTML );
            done();
        });

        stream.write( new gutil.File({
            path: 'style.css',
            contents: new Buffer( '' )
        }));
    });

});

describe('Include Pathing', function () {

    it('should default the path to the root directory', function ( done ) {
        var stream = include();

        stream.on( 'data', function ( file ) {
            expect( file.contents.toString() ).to.equal( JS_ROOT );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

    it('should normalize paths', function ( done ) {
        var stream = include({ path: 'include/path' });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_JS_DEST );
            expect( file.contents.toString() ).to.equal( JS_INCLUDE );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

});

describe('Output Destinations', function () {

    it('should default the destination to the current directory', function ( done ) {
        var stream = include();

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_JS_DEST );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

    it('should use provided destinations', function ( done ) {
        var stream = include({ dest: '../static/'});

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( path.normalize( '../static/javascript.js.html' ));
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

});<commit_msg>Remove unused assert library to appease JSHint<commit_after>'use strict';

var expect      = require( 'chai' ).expect;
var gutil       = require( 'gulp-util' );
var include     = require( '../index' );
var path        = require( 'path' );

var JS_INCLUDE          = '<script src="include/path/javascript.js"></script>';
var CSS_INCLUDE         = '<link href="include/path/style.css" rel="stylesheet">';
var CSS_INCLUDE_XHTML   = '<link href="include/path/style.css" rel="stylesheet" />';
var JS_ROOT             = '<script src="/javascript.js"></script>';
var CSS_ROOT            = '<link href="/style.css" rel="stylesheet">';
var CSS_ROOT_XHTML      = '<link href="/style.css" rel="stylesheet" />';
var DEFAULT_JS_DEST     = 'javascript.js.html';
var DEFAULT_CSS_DEST    = 'style.css.html';

var out = process.stdout.write;

beforeEach(function () {
    process.stdout.write = function () {};
});

afterEach(function () {
    process.stdout.write = out;
});

describe('File Generation', function () {

    it('should generate HTML files to include JS files', function ( done ) {
        var stream = include({ path: 'include/path' });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_JS_DEST );
            expect( file.contents.toString() ).to.equal( JS_INCLUDE );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

    it('should generate HTML files to include CSS files', function ( done ) {
        var stream = include({ path: 'include/path' });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_CSS_DEST );
            expect( file.contents.toString() ).to.equal( CSS_INCLUDE );
            done();
        });

        stream.write( new gutil.File({
            path: 'style.css',
            contents: new Buffer( '' )
        }));
    });

    it('should generate XHTML-compliant files to include CSS files', function ( done ) {
        var stream = include({ path: 'include/path', xhtml: true });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_CSS_DEST );
            expect( file.contents.toString() ).to.equal( CSS_INCLUDE_XHTML );
            done();
        });

        stream.write( new gutil.File({
            path: 'style.css',
            contents: new Buffer( '' )
        }));
    });

});

describe('Include Pathing', function () {

    it('should default the path to the root directory', function ( done ) {
        var stream = include();

        stream.on( 'data', function ( file ) {
            expect( file.contents.toString() ).to.equal( JS_ROOT );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

    it('should normalize paths', function ( done ) {
        var stream = include({ path: 'include/path' });

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_JS_DEST );
            expect( file.contents.toString() ).to.equal( JS_INCLUDE );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

});

describe('Output Destinations', function () {

    it('should default the destination to the current directory', function ( done ) {
        var stream = include();

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( DEFAULT_JS_DEST );
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

    it('should use provided destinations', function ( done ) {
        var stream = include({ dest: '../static/'});

        stream.on( 'data', function ( file ) {
            expect( file.path ).to.equal( path.normalize( '../static/javascript.js.html' ));
            done();
        });

        stream.write( new gutil.File({
            path: 'javascript.js',
            contents: new Buffer( '' )
        }));
    });

});<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016, OCEAN
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Created by Il Yeup, Ahn in KETI on 2016-10-18.
 */

/**
 * @file
 * @copyright KETI Korea 2016, OCEAN
 * @author Il Yeup Ahn [iyahn@keti.re.kr]
 */

var fs = require('fs');
var http = require('http');
var https = require('https');
var coap = require('coap');
var util = require('util');
var xml2js = require('xml2js');
var url = require('url');
var xmlbuilder = require('xmlbuilder');
var moment = require('moment');
var ip = require("ip");

global.NOPRINT = 'true';

var _this = this;

var coap_state = 'init';

//var custom = new process.EventEmitter();
var events = require('events');
var coap_custom = new events.EventEmitter();

var usecoapcbhost = 'localhost'; // pxycoap to mobius

var coap_rsc_code = {
    '2000': '2.05',
    '2001': '2.01',
    '2002': '2.02',
    '2004': '2.04',
    '4000': '4.00',
    '4004': '4.04',
    '4005': '4.05',
    '4008': '4.04',
    '4101': '4.03',
    '4102': '4.00',
    '4103': '4.03',
    '4104': '4.00',
    '4105': '4.03',
    '5000': '5.00',
    '5001': '5.01',
    '5103': '4.04',
    '5105': '4.03',
    '5106': '5.06',
    '5203': '4.03',
    '5204': '5.00',
    '5205': '4.03',
    '5206': '5.00',
    '5207': '4.06',
    '6003': '4.04',
    '6005': '4.04',
    '6010': '4.00',
    '6011': '4.00',
    '6020': '5.00',
    '6021': '5.00',
    '6022': '4.00',
    '6023': '4.00',
    '6024': '4.00',
    '6025': '5.00',
    '6026': '5.00',
    '6028': '4.00',
    '6029': '4.00'
};

coap_state = 'init';

//setInterval(function () {
//    coap_custom.emit('coap_watchdog');
//}, 2000);

var pxycoap_server = null;

//coap_custom.on('coap_watchdog', function() {
exports.coap_watchdog = function () {
    if(coap_state === 'init') {
        coap_state = 'connect';
    }
    else if(coap_state === 'connect') {
        if(pxycoap_server == null) {
            pxycoap_server = coap.createServer();
            pxycoap_server.listen(usecsebaseport, function() {
                // var options = {
                //     host: 'localhost',
                //     port: usecsebaseport,
                //     pathname: '/'+usecsebase,
                //     method: 'get',
                //     confirmable: 'false',
                //     options: {
                //         'Accept': 'application/json'
                //     }
                // };
                //
                // var bodyString = '';
                // var responseBody = '';
                // var req = coap.request(options);
                // req.setOption("256", new Buffer(usecseid));      // X-M2M-Origin
                // req.setOption("257", new Buffer('hello'));    // X-M2M-RI
                // req.on('response', function (res) {
                //     res.on('data', function () {
                //         responseBody += res.payload.toString();
                //     });
                //
                //     res.on('end', function () {
                //         if(res.code == '2.05') {
                //             coap_state = 'ready';
                //             console.log('[pxy_coap] coap ready');
                //         }
                //     });
                // });
                // req.on('error', function (e) {
                //     console.log(e);
                // });
                //
                // req.write(bodyString);
                // req.end();
            });

            pxycoap_server.on('request', coap_message_handler);

            pxycoap_server.on('error', function (e) {
                console.log(e);
            });
        }
    }
};

var coap_tid = require('shortid').generate();
wdt.set_wdt(coap_tid, 2, _this.coap_watchdog);

function coap_message_handler(request, response) {

    var headers = {};
    headers['X-M2M-TY'] = '';

    // check coap options
    for (var idx in request.options) {
        if (request.options.hasOwnProperty(idx)) {
            if (request.options[idx].name == '256') { // 'X-M2M-Origin
                headers['X-M2M-Origin'] = request.options[idx].value.toString();
            }
            else if (request.options[idx].name == '257') { // 'X-M2M-RI
                headers['X-M2M-RI'] = request.options[idx].value.toString();
            }
            else if (request.options[idx].name == '267') { // 'X-M2M-TY
                headers['X-M2M-TY'] = Buffer.isBuffer(request.options[idx].value) ? request.options[idx].value[0].toString() : request.options[idx].value.toString();
            }
        }
    }

    if(request.headers['Accept'])
    {
        headers['Accept'] = request.headers['Accept'];
    }

    if(request.headers['Content-Type'])
    {
        if(headers['X-M2M-TY'] == '') {
            headers['Content-Type'] = request.headers['Content-Type'];
        }
        else {
            headers['Content-Type'] = request.headers['Content-Type'] + ';ty=' + headers['X-M2M-TY'];
        }
    }

    delete headers['X-M2M-TY'];

    var responseBody = '';

    if(usesecure === 'disable') {
        var options = {
            hostname: usecoapcbhost,
            port: usecsebaseport,
            path: request.url,
            method: request.method,
            headers: headers
        };

        var req = http.request(options, function (res) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                responseBody += chunk;
            });

            res.on('end', function () {
                console.log('<----- [pxy_coap]');
                console.log(responseBody);

                var rsc = new Buffer(2);
                rsc.writeUInt16BE(parseInt(res.headers['x-m2m-rsc'], 'hex'), 0);
                response.setOption("265", rsc);    // X-M2M-RSC
                //var rqi = new Buffer(2);
                //rqi.writeUInt16BE(parseInt(res.headers['x-m2m-ri'], 'hex'), 0);
                var rqi = res.headers['x-m2m-ri'];
                response.setOption("257", rqi);    // X-M2M-RQI
                if (res.headers['content-type']) {
                    response.setOption("Content-Format", res.headers['content-type']);
                }
                response.code = coap_rsc_code[res.headers['x-m2m-rsc']];
                response.end(responseBody);
            });
        });
    }
    else if(usesecure === 'enable') {
        options = {
            hostname: usecoapcbhost,
            port: usecsebaseport,
            path: request.url,
            method: request.method,
            headers: headers,
            ca: fs.readFileSync('ca-crt.pem')
        };

        req = https.request(options, function (res) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                responseBody += chunk;
            });

            res.on('end', function () {
                console.log('<----- [pxy_coap]');
                console.log(responseBody);

                var rsc = new Buffer(2);
                rsc.writeUInt16BE(parseInt(res.headers['x-m2m-rsc'], 'hex'), 0);
                response.setOption("265", rsc);    // X-M2M-RSC
                var rqi = new Buffer(2);
                rqi.writeUInt16BE(parseInt(res.headers['x-m2m-ri'], 'hex'), 0);
                response.setOption("257", rqi);    // X-M2M-RQI
                if (res.headers['content-type']) {
                    response.setOption("Content-Format", res.headers['content-type']);
                }
                response.code = coap_rsc_code[res.headers['x-m2m-rsc']];
                response.end(responseBody);
            });
        });

    }

    req.on('error', function (e) {
        if (e.message !== 'read ECONNRESET') {
            console.log('[pxycoap - http_retrieve_CSEBase] problem with request: ' + e.message);
        }
    });

    var bodyString = request.payload.toString();
    console.log('-----> [pxy_coap]');
    console.log(bodyString);

    // write data to request body
    req.write(bodyString);
    req.end();
}
<commit_msg>- update coap code that modified making message of coap<commit_after>/**
 * Copyright (c) 2016, OCEAN
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Created by Il Yeup, Ahn in KETI on 2016-10-18.
 */

/**
 * @file
 * @copyright KETI Korea 2016, OCEAN
 * @author Il Yeup Ahn [iyahn@keti.re.kr]
 */

var fs = require('fs');
var http = require('http');
var https = require('https');
var coap = require('coap');
var util = require('util');
var xml2js = require('xml2js');
var url = require('url');
var xmlbuilder = require('xmlbuilder');
var moment = require('moment');
var ip = require("ip");

global.NOPRINT = 'true';

var _this = this;

var coap_state = 'init';

//var custom = new process.EventEmitter();
var events = require('events');
var coap_custom = new events.EventEmitter();

var usecoapcbhost = 'localhost'; // pxycoap to mobius

var coap_rsc_code = {
    '2000': '2.05',
    '2001': '2.01',
    '2002': '2.02',
    '2004': '2.04',
    '4000': '4.00',
    '4004': '4.04',
    '4005': '4.05',
    '4008': '4.04',
    '4101': '4.03',
    '4102': '4.00',
    '4103': '4.03',
    '4104': '4.00',
    '4105': '4.03',
    '5000': '5.00',
    '5001': '5.01',
    '5103': '4.04',
    '5105': '4.03',
    '5106': '5.06',
    '5203': '4.03',
    '5204': '5.00',
    '5205': '4.03',
    '5206': '5.00',
    '5207': '4.06',
    '6003': '4.04',
    '6005': '4.04',
    '6010': '4.00',
    '6011': '4.00',
    '6020': '5.00',
    '6021': '5.00',
    '6022': '4.00',
    '6023': '4.00',
    '6024': '4.00',
    '6025': '5.00',
    '6026': '5.00',
    '6028': '4.00',
    '6029': '4.00'
};

coap_state = 'init';

//setInterval(function () {
//    coap_custom.emit('coap_watchdog');
//}, 2000);

var pxycoap_server = null;

//coap_custom.on('coap_watchdog', function() {
exports.coap_watchdog = function () {
    if(coap_state === 'init') {
        coap_state = 'connect';
    }
    else if(coap_state === 'connect') {
        if(pxycoap_server == null) {
            pxycoap_server = coap.createServer();
            pxycoap_server.listen(usecsebaseport, function() {
                // var options = {
                //     host: 'localhost',
                //     port: usecsebaseport,
                //     pathname: '/'+usecsebase,
                //     method: 'get',
                //     confirmable: 'false',
                //     options: {
                //         'Accept': 'application/json'
                //     }
                // };
                //
                // var bodyString = '';
                // var responseBody = '';
                // var req = coap.request(options);
                // req.setOption("256", new Buffer(usecseid));      // X-M2M-Origin
                // req.setOption("257", new Buffer('hello'));    // X-M2M-RI
                // req.on('response', function (res) {
                //     res.on('data', function () {
                //         responseBody += res.payload.toString();
                //     });
                //
                //     res.on('end', function () {
                //         if(res.code == '2.05') {
                //             coap_state = 'ready';
                //             console.log('[pxy_coap] coap ready');
                //         }
                //     });
                // });
                // req.on('error', function (e) {
                //     console.log(e);
                // });
                //
                // req.write(bodyString);
                // req.end();
            });

            pxycoap_server.on('request', coap_message_handler);

            pxycoap_server.on('error', function (e) {
                console.log(e);
            });
        }
    }
};

var coap_tid = require('shortid').generate();
wdt.set_wdt(coap_tid, 2, _this.coap_watchdog);

function coap_message_handler(request, response) {

    var headers = {};
    headers['X-M2M-TY'] = '';

    // check coap options
    for (var idx in request.options) {
        if (request.options.hasOwnProperty(idx)) {
            if (request.options[idx].name == '256') { // 'X-M2M-Origin
                headers['X-M2M-Origin'] = request.options[idx].value.toString();
            }
            else if (request.options[idx].name == '257') { // 'X-M2M-RI
                headers['X-M2M-RI'] = request.options[idx].value.toString();
            }
            else if (request.options[idx].name == '267') { // 'X-M2M-TY
                headers['X-M2M-TY'] = Buffer.isBuffer(request.options[idx].value) ? request.options[idx].value[0].toString() : request.options[idx].value.toString();
            }
        }
    }

    if(request.headers['Accept'])
    {
        headers['Accept'] = request.headers['Accept'];
    }

    if(request.headers['Content-Type'])
    {
        if(headers['X-M2M-TY'] == '') {
            headers['Content-Type'] = request.headers['Content-Type'];
        }
        else {
            headers['Content-Type'] = request.headers['Content-Type'] + ';ty=' + headers['X-M2M-TY'];
        }
    }

    delete headers['X-M2M-TY'];

    var responseBody = '';

    if(usesecure === 'disable') {
        var options = {
            hostname: usecoapcbhost,
            port: usecsebaseport,
            path: request.url,
            method: request.method,
            headers: headers
        };

        var req = http.request(options, function (res) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                responseBody += chunk;
            });

            res.on('end', function () {
                console.log('<----- [pxy_coap]');
                console.log(responseBody);

                var rsc = new Buffer(2);
                rsc.writeUInt16BE(parseInt(res.headers['x-m2m-rsc'], 'hex'), 0);
                response.setOption("265", rsc);    // X-M2M-RSC
                //var rqi = new Buffer(2);
                //rqi.writeUInt16BE(parseInt(res.headers['x-m2m-ri'], 'hex'), 0);
                //var rqi = res.headers['x-m2m-ri'];
                var rqi = Buffer.from(res.headers['x-m2m-ri'], 'utf-8');
                response.setOption("257", rqi);    // X-M2M-RQI
                if (res.headers['content-type']) {
                    response.setOption("Content-Format", res.headers['content-type']);
                }
                response.code = coap_rsc_code[res.headers['x-m2m-rsc']];
                response.end(responseBody);
            });
        });
    }
    else if(usesecure === 'enable') {
        options = {
            hostname: usecoapcbhost,
            port: usecsebaseport,
            path: request.url,
            method: request.method,
            headers: headers,
            ca: fs.readFileSync('ca-crt.pem')
        };

        req = https.request(options, function (res) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                responseBody += chunk;
            });

            res.on('end', function () {
                console.log('<----- [pxy_coap]');
                console.log(responseBody);

                var rsc = new Buffer(2);
                rsc.writeUInt16BE(parseInt(res.headers['x-m2m-rsc'], 'hex'), 0);
                response.setOption("265", rsc);    // X-M2M-RSC
                var rqi = new Buffer(2);
                rqi.writeUInt16BE(parseInt(res.headers['x-m2m-ri'], 'hex'), 0);
                response.setOption("257", rqi);    // X-M2M-RQI
                if (res.headers['content-type']) {
                    response.setOption("Content-Format", res.headers['content-type']);
                }
                response.code = coap_rsc_code[res.headers['x-m2m-rsc']];
                response.end(responseBody);
            });
        });

    }

    req.on('error', function (e) {
        if (e.message !== 'read ECONNRESET') {
            console.log('[pxycoap - http_retrieve_CSEBase] problem with request: ' + e.message);
        }
    });

    var bodyString = request.payload.toString();
    console.log('-----> [pxy_coap]');
    console.log(bodyString);

    // write data to request body
    req.write(bodyString);
    req.end();
}
<|endoftext|>


<commit_before>var canvas, ctx, w, h, world, planeBody, boxBody, boxShape;
var pogo;
var data = [];
var heightfield = new Object();
init();
requestAnimationFrame(animate);

function init() {
	// Init canvas
	canvas = document.getElementById("myCanvas");
	w = canvas.width;
	h = canvas.height;
	ctx = canvas.getContext("2d");
	ctx.lineWidth = 0.05;
	// Init p2.js
	world = new p2.World({
		gravity : [ 0, -7 ]
	});

	world.defaultContactMaterial.friction = 100;
	world.defaultContactMaterial.restitution = 0.1;

	pogo = {
		stick : new Object(),
		frame : new Object(),
		spring : null
	// ,tip: new Object()
	};

	// pogo.tip.shape = new p2.Circle({ radius: 0.3 })
	//
	// pogo.tip.body = new p2.Body({
	// mass: 1,
	// position: [0,2],
	// angularVelocity: -0.5
	// });

	var av = -0.25

	pogo.stick.shape = new p2.Box({
		width : 0.25,
		height : 1
	});

	pogo.stick.body = new p2.Body({
		mass : 0.25,
//		damping: 0.2,
		position : [ 0, 1 ],
		angularVelocity : av,
		velocity : [ 5, 0 ]
	});

	pogo.frame.shape = new p2.Box({
		width : 0.5,
		height : 1.5
	});

	pogo.frame.body = new p2.Body({
		mass : 3,
		position : [ 0, 3 ],
		angularVelocity : av,
		velocity : [ 5, 0 ]
	});

	pogo.frame.body.addShape(pogo.frame.shape);
	pogo.stick.body.addShape(pogo.stick.shape);

	// world.addBody(pogo.tip.body);
	world.addBody(pogo.frame.body);
	world.addBody(pogo.stick.body);

	var stiffness = 350, damping = 0.5, restLength = 1

	var c1 = new p2.PrismaticConstraint(pogo.frame.body, pogo.stick.body, {
		localAnchorA : [ 0, 0.5 ],
		localAnchorB : [ 0, 0.5 ],
		localAxisA : [ 0, 1 ],
		disableRotationalLock : true,
	});
	var c2 = new p2.PrismaticConstraint(pogo.frame.body, pogo.stick.body, {
		localAnchorA : [ 0, 0 ],
		localAnchorB : [ 0, 1 ],
		localAxisA : [ 0, 1 ],
		disableRotationalLock : true,
	});
	 c1.setLimits(-1.5, 0.5);
	 c2.setLimits(-1.5, 0.5);
	world.addConstraint(c2);
	world.addConstraint(c1);

	// world.addSpring(new p2.LinearSpring(pogo.frame.body, pogo.stick.body, {
	// restLength : restLength,
	// stiffness : stiffness,
	// damping : damping,
	// localAnchorA : [0,0],
	// localAnchorB : [0,0],
	// }));

	pogo.spring = new p2.LinearSpring(pogo.frame.body, pogo.stick.body, {
		restLength : restLength,
		stiffness : stiffness,
		damping : damping,
		localAnchorA : [ 0, 0 ],
		localAnchorB : [ 0, 0 ],
	});

	world.addSpring(pogo.spring);

	// Add a box
	// boxShape = pogo.frame.shape
	// boxBody = pogo.frame.body
	// boxShape = new p2.Box({
	// width: 0.5,
	// height: 1.5
	// });
	// boxBody = new p2.Body({
	// mass: 1,
	// position: [0,3],
	// angularVelocity: -0.5
	// });
	// boxBody.addShape(boxShape);
	// world.addBody(boxBody);
	// Add a plane
	// planeShape = new p2.Plane();
	// planeBody = new p2.Body();
	// planeBody.addShape(planeShape);

	noise.seed(Math.random());
	data.push(0)
	var numDataPoints = 500;
	for (var i = 0; i < numDataPoints; i++) {
		v = i / 10
		var value = noise.simplex2(v, 0);
		var value1 = noise.perlin2(v, 0);
		// data.push(0.5*Math.cos(0.2*i) * Math.sin(0.5*i) + 0.6*Math.sin(0.1*i)
		// * Math.sin(0.05*i));
		data.push(value * 1.75)
	}
	heightfield.shape = new p2.Heightfield({
		heights : data,
		elementWidth : 2
	});
	heightfield.body = new p2.Body({
		position : [ -1, -1 ]
	});
	heightfield.body.addShape(heightfield.shape);
	world.addBody(heightfield.body);

	// world.addBody(planeBody);

	// Setup Collisions
	var FRAME = 1, STICK = 2, GROUND = 4;

	// pogo.tip.shape.collisionGroup = TIP;
	pogo.frame.shape.collisionGroup = FRAME;
	pogo.stick.shape.collisionGroup = STICK;
	heightfield.shape.collisionGroup = GROUND;

	// pogo.tip.shape.collisionMask = ~STICK;
	pogo.frame.shape.collisionMask = ~STICK;
	pogo.stick.shape.collisionMask = ~FRAME;
	heightfield.shape.collisionMask = -1;

	window.addEventListener("keydown", keydown, false);
	window.addEventListener("keyup", keyup, false);
	window.addEventListener("keypress", keypress, false);
}

function keydown(evt) {
	// t = 5;
	// switch(evt.keyCode){
	// case 39: // right
	// torque = -t;
	// break;
	// case 37: // left
	// torque = t;
	// break;
	// }

//	alert(evt.charCode)
	if (evt.keyCode == 65) {
		pogo.spring.restLength = 1.25;
		pogo.spring.applyForce();
	}

	if (evt.keyCode == 83) {
		// alert("Hi")
		pogo.frame.body.angularVelocity = +twistval
		// pogo.stick.body.angularVelocity+=twistval
	}
	if (evt.keyCode == 68) {
		// alert("Hi")
		pogo.frame.body.angularVelocity = -twistval
		// pogo.stick.body.angularVelocity+=twistval
	}
}

function keyup(evt) {
	// t = 5;
	// switch(evt.keyCode){
	// case 39: // right
	// torque = -t;
	// break;
	// case 37: // left
	// torque = t;
	// break;
	// }

	if (evt.keyCode == 65) {
		pogo.spring.restLength = 0.25;
		pogo.spring.applyForce();
	}

	if (evt.keyCode == 83 || evt.keyCode == 68) {
		// alert("Hi")
		pogo.frame.body.angularVelocity = 0
		// pogo.stick.body.angularVelocity+=twistval
	}
//	if (evt.keyCode == 100) {
//		// alert("Hi")
//		pogo.frame.body.angularVelocity = -twistval
//		// pogo.stick.body.angularVelocity+=twistval
//	}

}
var twistval = 5;
function keypress(evt) {
	// alert(evt.keyCode)
	 if (evt.keyCode == 115) {
	 // alert("Hi")
	 pogo.frame.body.angularVelocity=twistval
	 // pogo.stick.body.angularVelocity+=twistval
	 }
	 if (evt.keyCode == 100) {
	 // alert("Hi")
	 pogo.frame.body.angularVelocity=-twistval
	 // pogo.stick.body.angularVelocity+=twistval
	 }
}

function drawpogo() {
	drawbox(pogo.stick)
	drawbox(pogo.frame)
	// drawBox({body: boxBody, shape: boxShape})
}

// function drawcircle(obj) {
// var x = obj.body.interpolatedPosition[0],
// y = obj.body.interpolatedPosition[1];
// ctx.arc(95,50,40,0,2*Math.PI);
// ctx.stroke();
// }

function drawbox(obj) {
	ctx.beginPath();
	var x = obj.body.interpolatedPosition[0], y = obj.body.interpolatedPosition[1];
	ctx.save();
	ctx.translate(x, y); // Translate to the center of the box
	ctx.rotate(obj.body.angle); // Rotate to the box body frame
	ctx.rect(-obj.shape.width / 2, -obj.shape.height / 2, obj.shape.width,
			obj.shape.height);
	ctx.stroke();
	ctx.restore();
}
function drawPlane() {
	var y = planeBody.interpolatedPosition[1];
	ctx.moveTo(-w, y);
	ctx.lineTo(w, y);
	ctx.stroke();
}

var xscroll = 0
function render() {
	// Clear the canvas
	ctx.clearRect(0, 0, w, h);
	// Transform the canvas
	// Note that we need to flip the y axis since Canvas pixel coordinates
	// goes from top to bottom, while physics does the opposite.

	ctx.save();
	xscroll = -pogo.frame.body.position[0]
//	ctx.translate(xscroll, 0)

	ctx.translate(w / 2, h / 2); // Translate to the center
	ctx.scale(50, -50); // Zoom in and flip y axis

	ctx.translate(xscroll, 0)
	// Draw all bodies
	// drawbox(pogo.frame);
	drawpogo();
	// drawBox(pogo.frame)
	// drawPlane();
	var y = heightfield.body.position[1]
	// y = -1
	var x = heightfield.body.position[0]

//	x+=xscroll
	// x = 0

	// ctx.beginPath();
	ctx.moveTo(x, y + data[0]);

	var i = 0;
	for ( var d in data) {
		ctx.lineTo(x + i * heightfield.shape.elementWidth, y + data[i]);
		i += 1;
	}
	// ctx.lineTo(gameWidth/2,gameHeight/2);
	// ctx.lineTo(-gameWidth/2,gameHeight/2);
	// ctx.lineTo(-gameWidth/2,-gameHeight/2);
	ctx.stroke();
	// Restore transform
	ctx.restore();
}
// Animation loop

speed = 60*5
//speed = 1/speed
var lastTime;
var maxSubSteps = 5; // Max physics ticks per render frame
var fixedDeltaTime = 1 / speed; // Physics "tick" delta time
function animate(time) {
	requestAnimationFrame(animate);
	// Get the elapsed time since last frame, in seconds
	var deltaTime = lastTime ? (time - lastTime) / 1000 : 0;
	lastTime = time;
	// Make sure the time delta is not too big (can happen if user switches
	// browser tab)
	deltaTime = Math.min(1 / 10, deltaTime);
	// Move physics bodies forward in time
	world.step(fixedDeltaTime, deltaTime, maxSubSteps);
	// Render scene
	render();
}<commit_msg>changed controls to arrow keys<commit_after>var canvas, ctx, w, h, world, planeBody, boxBody, boxShape;
var pogo;
var data = [];
var heightfield = new Object();
init();
requestAnimationFrame(animate);

function init() {
	// Init canvas
	canvas = document.getElementById("myCanvas");
	w = canvas.width;
	h = canvas.height;
	ctx = canvas.getContext("2d");
	ctx.lineWidth = 0.05;
	// Init p2.js
	world = new p2.World({
		gravity : [ 0, -7 ]
	});

	world.defaultContactMaterial.friction = 100;
	world.defaultContactMaterial.restitution = 0.1;

	pogo = {
		stick : new Object(),
		frame : new Object(),
		spring : null
	// ,tip: new Object()
	};

	// pogo.tip.shape = new p2.Circle({ radius: 0.3 })
	//
	// pogo.tip.body = new p2.Body({
	// mass: 1,
	// position: [0,2],
	// angularVelocity: -0.5
	// });

	var av = -0.25

	pogo.stick.shape = new p2.Box({
		width : 0.25,
		height : 1
	});

	pogo.stick.body = new p2.Body({
		mass : 0.25,
//		damping: 0.2,
		position : [ 0, 1 ],
		angularVelocity : av,
		velocity : [ 5, 0 ]
	});

	pogo.frame.shape = new p2.Box({
		width : 0.5,
		height : 1.5
	});

	pogo.frame.body = new p2.Body({
		mass : 3,
		position : [ 0, 3 ],
		angularVelocity : av,
		velocity : [ 5, 0 ]
	});

	pogo.frame.body.addShape(pogo.frame.shape);
	pogo.stick.body.addShape(pogo.stick.shape);

	// world.addBody(pogo.tip.body);
	world.addBody(pogo.frame.body);
	world.addBody(pogo.stick.body);

	var stiffness = 350, damping = 0.5, restLength = 1

	var c1 = new p2.PrismaticConstraint(pogo.frame.body, pogo.stick.body, {
		localAnchorA : [ 0, 0.5 ],
		localAnchorB : [ 0, 0.5 ],
		localAxisA : [ 0, 1 ],
		disableRotationalLock : true,
	});
	var c2 = new p2.PrismaticConstraint(pogo.frame.body, pogo.stick.body, {
		localAnchorA : [ 0, 0 ],
		localAnchorB : [ 0, 1 ],
		localAxisA : [ 0, 1 ],
		disableRotationalLock : true,
	});
	 c1.setLimits(-1.5, 0.5);
	 c2.setLimits(-1.5, 0.5);
	world.addConstraint(c2);
	world.addConstraint(c1);

	// world.addSpring(new p2.LinearSpring(pogo.frame.body, pogo.stick.body, {
	// restLength : restLength,
	// stiffness : stiffness,
	// damping : damping,
	// localAnchorA : [0,0],
	// localAnchorB : [0,0],
	// }));

	pogo.spring = new p2.LinearSpring(pogo.frame.body, pogo.stick.body, {
		restLength : restLength,
		stiffness : stiffness,
		damping : damping,
		localAnchorA : [ 0, 0 ],
		localAnchorB : [ 0, 0 ],
	});

	world.addSpring(pogo.spring);

	// Add a box
	// boxShape = pogo.frame.shape
	// boxBody = pogo.frame.body
	// boxShape = new p2.Box({
	// width: 0.5,
	// height: 1.5
	// });
	// boxBody = new p2.Body({
	// mass: 1,
	// position: [0,3],
	// angularVelocity: -0.5
	// });
	// boxBody.addShape(boxShape);
	// world.addBody(boxBody);
	// Add a plane
	// planeShape = new p2.Plane();
	// planeBody = new p2.Body();
	// planeBody.addShape(planeShape);

	noise.seed(Math.random());
	data.push(0)
	var numDataPoints = 500;
	for (var i = 0; i < numDataPoints; i++) {
		v = i / 10
		var value = noise.simplex2(v, 0);
		var value1 = noise.perlin2(v, 0);
		// data.push(0.5*Math.cos(0.2*i) * Math.sin(0.5*i) + 0.6*Math.sin(0.1*i)
		// * Math.sin(0.05*i));
		data.push(value * 1.75)
	}
	heightfield.shape = new p2.Heightfield({
		heights : data,
		elementWidth : 2
	});
	heightfield.body = new p2.Body({
		position : [ -1, -1 ]
	});
	heightfield.body.addShape(heightfield.shape);
	world.addBody(heightfield.body);

	// world.addBody(planeBody);

	// Setup Collisions
	var FRAME = 1, STICK = 2, GROUND = 4;

	// pogo.tip.shape.collisionGroup = TIP;
	pogo.frame.shape.collisionGroup = FRAME;
	pogo.stick.shape.collisionGroup = STICK;
	heightfield.shape.collisionGroup = GROUND;

	// pogo.tip.shape.collisionMask = ~STICK;
	pogo.frame.shape.collisionMask = ~STICK;
	pogo.stick.shape.collisionMask = ~FRAME;
	heightfield.shape.collisionMask = -1;

	window.addEventListener("keydown", keydown, false);
	window.addEventListener("keyup", keyup, false);
	window.addEventListener("keypress", keypress, false);
}

var keys = {
	left: 37,
	right: 39,
	up: 38
}

function keydown(evt) {
	// t = 5;
	// switch(evt.keyCode){
	// case 39: // right
	// torque = -t;
	// break;
	// case 37: // left
	// torque = t;
	// break;
	// }

	if([32, 37, 38, 39, 40].indexOf(evt.keyCode) > -1) {
        evt.preventDefault();
    }

//	alert(evt.keyCode)
	if (evt.keyCode == keys.up) {
		pogo.spring.restLength = 1.25;
		pogo.spring.applyForce();
	}

	if (evt.keyCode == keys.left) {
		// alert("Hi")
		pogo.frame.body.angularVelocity = +twistval
		// pogo.stick.body.angularVelocity+=twistval
	}
	if (evt.keyCode == keys.right) {
		// alert("Hi")
		pogo.frame.body.angularVelocity = -twistval
		// pogo.stick.body.angularVelocity+=twistval
	}
}

function keyup(evt) {
	// t = 5;
	// switch(evt.keyCode){
	// case 39: // right
	// torque = -t;
	// break;
	// case 37: // left
	// torque = t;
	// break;
	// }

//	if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
//        e.preventDefault();
//    }

	if (evt.keyCode == keys.up) {
		pogo.spring.restLength = 0.25;
		pogo.spring.applyForce();
	}

	if (evt.keyCode == keys.left || evt.keyCode == keys.right) {
		// alert("Hi")
		pogo.frame.body.angularVelocity = 0
		// pogo.stick.body.angularVelocity+=twistval
	}
//	if (evt.keyCode == 100) {
//		// alert("Hi")
//		pogo.frame.body.angularVelocity = -twistval
//		// pogo.stick.body.angularVelocity+=twistval
//	}

}
var twistval = 5;
function keypress(evt) {
	// alert(evt.keyCode)
//	if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
//        e.preventDefault();
//    }

	 if (evt.keyCode == keys.left) {
	 // alert("Hi")
	 pogo.frame.body.angularVelocity=twistval
	 // pogo.stick.body.angularVelocity+=twistval
	 }
	 if (evt.keyCode == keys.right) {
	 // alert("Hi")
	 pogo.frame.body.angularVelocity=-twistval
	 // pogo.stick.body.angularVelocity+=twistval
	 }
}

function drawpogo() {
	drawbox(pogo.stick)
	drawbox(pogo.frame)
	// drawBox({body: boxBody, shape: boxShape})
}

// function drawcircle(obj) {
// var x = obj.body.interpolatedPosition[0],
// y = obj.body.interpolatedPosition[1];
// ctx.arc(95,50,40,0,2*Math.PI);
// ctx.stroke();
// }

function drawbox(obj) {
	ctx.beginPath();
	var x = obj.body.interpolatedPosition[0], y = obj.body.interpolatedPosition[1];
	ctx.save();
	ctx.translate(x, y); // Translate to the center of the box
	ctx.rotate(obj.body.angle); // Rotate to the box body frame
	ctx.rect(-obj.shape.width / 2, -obj.shape.height / 2, obj.shape.width,
			obj.shape.height);
	ctx.stroke();
	ctx.restore();
}
function drawPlane() {
	var y = planeBody.interpolatedPosition[1];
	ctx.moveTo(-w, y);
	ctx.lineTo(w, y);
	ctx.stroke();
}

var xscroll = 0
function render() {
	// Clear the canvas
	ctx.clearRect(0, 0, w, h);
	// Transform the canvas
	// Note that we need to flip the y axis since Canvas pixel coordinates
	// goes from top to bottom, while physics does the opposite.

	ctx.save();
	xscroll = -pogo.frame.body.position[0]
//	ctx.translate(xscroll, 0)

	ctx.translate(w / 2, h / 2); // Translate to the center
	ctx.scale(50, -50); // Zoom in and flip y axis

	ctx.translate(xscroll, 0)
	// Draw all bodies
	// drawbox(pogo.frame);
	drawpogo();
	// drawBox(pogo.frame)
	// drawPlane();
	var y = heightfield.body.position[1]
	// y = -1
	var x = heightfield.body.position[0]

//	x+=xscroll
	// x = 0

	// ctx.beginPath();
	ctx.moveTo(x, y + data[0]);

	var i = 0;
	for ( var d in data) {
		ctx.lineTo(x + i * heightfield.shape.elementWidth, y + data[i]);
		i += 1;
	}
	// ctx.lineTo(gameWidth/2,gameHeight/2);
	// ctx.lineTo(-gameWidth/2,gameHeight/2);
	// ctx.lineTo(-gameWidth/2,-gameHeight/2);
	ctx.stroke();
	// Restore transform
	ctx.restore();
}
// Animation loop

speed = 60*5
//speed = 1/speed
var lastTime;
var maxSubSteps = 5; // Max physics ticks per render frame
var fixedDeltaTime = 1 / speed; // Physics "tick" delta time
function animate(time) {
	requestAnimationFrame(animate);
	// Get the elapsed time since last frame, in seconds
	var deltaTime = lastTime ? (time - lastTime) / 1000 : 0;
	lastTime = time;
	// Make sure the time delta is not too big (can happen if user switches
	// browser tab)
	deltaTime = Math.min(1 / 10, deltaTime);
	// Move physics bodies forward in time
	world.step(fixedDeltaTime, deltaTime, maxSubSteps);
	// Render scene
	render();
}<|endoftext|>


<commit_before>function addModal(element){
  var modals = document.querySelector(".modals");
  modals.appendChild(element);
  modals.style.display = null;
}

function removeModal(element){
  var modals = document.querySelector(".modals");
  modals.removeChild(element);
  if(modals.childNodes.length===0){
    modals.style.display = "none";
  }
}

function getUserInput(prompt,type){
  return new Promise(function(good,bad){
    var modal = document.createElement("form"),
        input = document.createElement("input");
    input.type = type;
    input.placeholder = prompt;
    modal.onsubmit = function(){
      good(input.value);
      removeModal(modal);
      return false;
    };
    modal.appendChild(input);
    addModal(modal);
    input.focus();
  });
}

function getUserSelection(prompt,options){
  return new Promise(function(good,bad){
    var modal = document.createElement("form"),
        submit = function(val){
          good(val);
          removeModal(modal);
          return false;
        };
    modal.textContent = prompt;
    options.forEach(function(n){
      var selection = document.createElement("button");
      selection.textContent = n.text;
      selection.onclick = submit.bind(null,n.value);
      modal.appendChild(selection);
    });
    addModal(modal);
  });
}

function showError(err){
  var modal = document.createElement("div");
  modal.onclick = function(){
    removeModal(modal);
  };
  modal.textContent = err;
  addModal(modal);
}

var ws;
try {
  ws = new WebSocket("ws://" + location.host + location.search);
} catch(e) {
  ws = new LongPoll("../ws",location.search);
}
ws.onmessage = function(msg){
  var data = JSON.parse(msg.data),
      handler = handlers[data.type];
  if(typeof(data) !== 'object'){
    console.warn("Data is not a object origional data:",msg.data);
  }
  if(handler === undefined){
    console.warn("No handler for ",data.type,data);
  } else {
    handlers[data.type](data);
  }
};

ws._send = ws.send;
ws.send = function(data){
  ws._send(JSON.stringify(data));
};

document.querySelector("#chat form").onsubmit = function(e){
  ws.send({type:"chat",msg:this.childNodes[0].value});
  this.childNodes[0].value = "";
  return false;
};
<commit_msg>Added warn message to notify of longpoll<commit_after>function addModal(element){
  var modals = document.querySelector(".modals");
  modals.appendChild(element);
  modals.style.display = null;
}

function removeModal(element){
  var modals = document.querySelector(".modals");
  modals.removeChild(element);
  if(modals.childNodes.length===0){
    modals.style.display = "none";
  }
}

function getUserInput(prompt,type){
  return new Promise(function(good,bad){
    var modal = document.createElement("form"),
        input = document.createElement("input");
    input.type = type;
    input.placeholder = prompt;
    modal.onsubmit = function(){
      good(input.value);
      removeModal(modal);
      return false;
    };
    modal.appendChild(input);
    addModal(modal);
    input.focus();
  });
}

function getUserSelection(prompt,options){
  return new Promise(function(good,bad){
    var modal = document.createElement("form"),
        submit = function(val){
          good(val);
          removeModal(modal);
          return false;
        };
    modal.textContent = prompt;
    options.forEach(function(n){
      var selection = document.createElement("button");
      selection.textContent = n.text;
      selection.onclick = submit.bind(null,n.value);
      modal.appendChild(selection);
    });
    addModal(modal);
  });
}

function showError(err){
  var modal = document.createElement("div");
  modal.onclick = function(){
    removeModal(modal);
  };
  modal.textContent = err;
  addModal(modal);
}

var ws;
try {
  ws = new WebSocket("ws://" + location.host + location.search);
} catch(e) {
  console.warn("Websocket failed, trying longpoll fallback");
  ws = new LongPoll("../ws",location.search);
}
ws.onmessage = function(msg){
  var data = JSON.parse(msg.data),
      handler = handlers[data.type];
  if(typeof(data) !== 'object'){
    console.warn("Data is not a object origional data:",msg.data);
  }
  if(handler === undefined){
    console.warn("No handler for ",data.type,data);
  } else {
    handlers[data.type](data);
  }
};

ws._send = ws.send;
ws.send = function(data){
  ws._send(JSON.stringify(data));
};

document.querySelector("#chat form").onsubmit = function(e){
  ws.send({type:"chat",msg:this.childNodes[0].value});
  this.childNodes[0].value = "";
  return false;
};
<|endoftext|>


<commit_before>
/**
 * First we will load all of this project's JavaScript dependencies which
 * include Vue and Vue Resource. This gives a great starting point for
 * building robust, powerful web applications using Vue and Laravel.
 */

//require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the body of the page. From here, you may begin adding components to
 * the application, or feel free to tweak this setup for your needs.
 */

//Vue.component('example', require('./components/Example.vue'));

var filemanager = new Vue({
	mounted: function(){
    	console.log("VueJS: FileManager started");
        this.open($(this.$el).data('start'),false);
        console.log('Directory: '+this.$data.currentDirectory);
    },
    name: 'FileManager',
    el: '#filemanager',
    data:{
        _csrfToken: $('[name="_token"]').val(),
        previousDirectory: null,
        currentDirectory: 'storage',
        folders: [],
        files: [],
        knownFileExtensions: ['jpg','png','jpeg'],
        messages: []
    },
    watch:{

    },
    computed: {
        breadcrumb: function(){
            var here = this.$data.currentDirectory.split('/');

            var parts = [];

            for( var i = 0; i < here.length; i++ ) {
                var part = here[i];
                var text = part;
                var link = '' + here.slice( 0, i + 1 ).join('/');
                parts.push({ "text": text, "link": link });
            }

            return parts;
        }
    },
    methods:{
        open: function(folder, useCurrent = true){

           if(useCurrent){
              var folderToOpen = this.$data.currentDirectory+'/'+folder;
           }else{
              var folderToOpen = folder;
           }

           $.ajax({
                  url: 'admin/file-manager/index',
                  type: 'GET',
                  data:{
                    path: folderToOpen
                  },
                  success: function (data) {

                    filemanager.$data.previousDirectory = filemanager.$data.currentDirectory;
                    filemanager.$data.currentDirectory = data.current_dir;
                    filemanager.$data.folders = [];
                    filemanager.$data.files = [];

                     console.log(data);

                     if(typeof data.dirs !== 'undefined' && data.dirs.length > 0){

                         data.dirs.forEach(function(each){
                            filemanager.$data.folders.push(each);
                         });
                     }

                    if(typeof data.files !== 'undefined' && data.files.length > 0){

                        data.files.forEach(function(each){
                            filemanager.$data.files.push(each);
                         });

                        }

                        $('.fa-refresh').removeClass('fa-spin');
                  },
                  error: function (data) {
                      console.log(data);
                    //  throw "Error in ajax form submission";
                  }
              });

        },
    	newFolder: function(){

    		var dirPath = this.$data.currentDirectory;
    		var folderName = $('[name="new_folder_name"]').val();

    		$.post('admin/file-manager/new-folder',
    		{
    			_token: filemanager.$data._csrfToken,
    			dir_path: dirPath,
    			new_folder_name: folderName
    		},
    		function( data ) {
                if(typeof data.success !== 'undefined'){

    			  	console.log("Dir created: "+dirPath+'/'+folderName);

                    $('#new_folder').modal('hide');
    			  	$('[name="new_folder_name"]').val("");

                    filemanager.$data.folders.push(folderName);

                }else{
                    console.log("Error:");
                    console.log(data);
                }
			}
			);

    	},
		upload: function(){

            console.log("Uploading ...");

			var dirPath = filemanager.$data.currentDirectory;

            var fileSelect = $('#input-2');
            var files = fileSelect[0].files;

            var formData = new FormData();
            formData.append('_token',filemanager.$data._csrfToken);
            formData.append('dir_path',dirPath);

            for (var i = 0; i < files.length; i++) {
              var file = files[i];
              formData.append('up_file[]', file, file.name);
            }

		      $.ajax({
		          url: 'admin/file-manager/fileupload',
		          type: 'POST',
		          enctype: 'multipart/form-data',
		          data: formData,
		          async: false,
		          cache: false,
		          contentType: false,
		          processData: false,
		          success: function (data) {
                     if(typeof data.success !== 'undefined'){
    		              console.log(data);
                          $('#upload_file_to_storage').modal('hide');
                          fileSelect.val("");
                          fileSelect.fileinput("clear");

                          for (var i = 0; i < data.uploadedFileNames.length; i++) {
                                console.log(filemanager.basename(data.uploadedFileNames[i]));
                                filemanager.$data.files.push(filemanager.basename(data.uploadedFileNames[i])+'.'+filemanager.getFileExtension(data.uploadedFileNames[i]));
                          }
                    }else{
                        console.log("Error" +data);
                    }
		          },
		          error: function () {
		              console.log("Error in ajax form submission");
		          }
		      });
		},
		basename: function (url){
		    return ((url=/(([^\/\\\.#\? ]+)(\.\w+)*)([?#].+)?$/.exec(url))!= null)? url[2]: '';
		},
        modal: function(file){
            var modal = $('#delete_sample');
            $($($(modal.find('div.modal-body')).find('div')).find('b')).html(function(event,html){ return filemanager.basename(file); });
            modal.find('a').data('file',file);
            modal.modal('toggle');
        },
    	deleteFile: function(event){

    		file = filemanager.$data.currentDirectory+'/'+$(event.target).data('file');

    		$.get('admin/file-manager/delete',
    		{
    			_token: filemanager.$data._csrfToken,
    			file: file
    		},
    		function( data ) {
    			if(typeof data.success !== 'undefined'){

                    var index = filemanager.$data.files.indexOf($(event.target).data('file'));
                    if (index > -1) {
                      filemanager.$data.files.splice(index, 1);
                    }

                    index = filemanager.$data.folders.indexOf($(event.target).data('file'));
                    if (index > -1) {
                      filemanager.$data.folders.splice(index, 1);
                    }

    				$('#delete_sample').modal('hide');
    			}else{
    				 console.log(data);
    			}
			}
			);

    	},
        getUrlVar: function (location,vary){
            var vars = [], hash;
            var hashes = location.slice(location.indexOf('?') + 1).split('&');
            for(var i = 0; i < hashes.length; i++)
            {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars[vary];
        },
    	getUrlParam: function ( paramName ) {
            var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
            var match = window.location.search.match( reParam );

            return ( match && match.length > 1 ) ? match[1] : null;
        },
        returnFileUrl: function (filepath) {
        	// Simulate user action of selecting a file to be returned to CKEditor.
            var funcNum = 1;/*getUrlParam( 'CKEditorFuncNum' );*/
            var fileUrl = filepath;
            window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
            window.close();
        },
        getFileExtension: function(fileName){
            return fileName.substr(fileName.lastIndexOf('.') + 1);
        },
        isKnownExtension: function(fileName){
            return $.inArray( this.getFileExtension(fileName) , this.$data.knownFileExtensions ) >= 0;
        }
    }

});
<commit_msg>Fix image preview in filemanager - case insensitive<commit_after>
/**
 * First we will load all of this project's JavaScript dependencies which
 * include Vue and Vue Resource. This gives a great starting point for
 * building robust, powerful web applications using Vue and Laravel.
 */

//require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the body of the page. From here, you may begin adding components to
 * the application, or feel free to tweak this setup for your needs.
 */

//Vue.component('example', require('./components/Example.vue'));

var filemanager = new Vue({
	mounted: function(){
    	console.log("VueJS: FileManager started");
        this.open($(this.$el).data('start'),false);
        console.log('Directory: '+this.$data.currentDirectory);
    },
    name: 'FileManager',
    el: '#filemanager',
    data:{
        _csrfToken: $('[name="_token"]').val(),
        previousDirectory: null,
        currentDirectory: 'storage',
        folders: [],
        files: [],
        knownFileExtensions: ['jpg','png','jpeg'],
        messages: []
    },
    watch:{

    },
    computed: {
        breadcrumb: function(){
            var here = this.$data.currentDirectory.split('/');

            var parts = [];

            for( var i = 0; i < here.length; i++ ) {
                var part = here[i];
                var text = part;
                var link = '' + here.slice( 0, i + 1 ).join('/');
                parts.push({ "text": text, "link": link });
            }

            return parts;
        }
    },
    methods:{
        open: function(folder, useCurrent = true){

           if(useCurrent){
              var folderToOpen = this.$data.currentDirectory+'/'+folder;
           }else{
              var folderToOpen = folder;
           }

           $.ajax({
                  url: 'admin/file-manager/index',
                  type: 'GET',
                  data:{
                    path: folderToOpen
                  },
                  success: function (data) {

                    filemanager.$data.previousDirectory = filemanager.$data.currentDirectory;
                    filemanager.$data.currentDirectory = data.current_dir;
                    filemanager.$data.folders = [];
                    filemanager.$data.files = [];

                     console.log(data);

                     if(typeof data.dirs !== 'undefined' && data.dirs.length > 0){

                         data.dirs.forEach(function(each){
                            filemanager.$data.folders.push(each);
                         });
                     }

                    if(typeof data.files !== 'undefined' && data.files.length > 0){

                        data.files.forEach(function(each){
                            filemanager.$data.files.push(each);
                         });

                        }

                        $('.fa-refresh').removeClass('fa-spin');
                  },
                  error: function (data) {
                      console.log(data);
                    //  throw "Error in ajax form submission";
                  }
              });

        },
    	newFolder: function(){

    		var dirPath = this.$data.currentDirectory;
    		var folderName = $('[name="new_folder_name"]').val();

    		$.post('admin/file-manager/new-folder',
    		{
    			_token: filemanager.$data._csrfToken,
    			dir_path: dirPath,
    			new_folder_name: folderName
    		},
    		function( data ) {
                if(typeof data.success !== 'undefined'){

    			  	console.log("Dir created: "+dirPath+'/'+folderName);

                    $('#new_folder').modal('hide');
    			  	$('[name="new_folder_name"]').val("");

                    filemanager.$data.folders.push(folderName);

                }else{
                    console.log("Error:");
                    console.log(data);
                }
			}
			);

    	},
		upload: function(){

            console.log("Uploading ...");

			var dirPath = filemanager.$data.currentDirectory;

            var fileSelect = $('#input-2');
            var files = fileSelect[0].files;

            var formData = new FormData();
            formData.append('_token',filemanager.$data._csrfToken);
            formData.append('dir_path',dirPath);

            for (var i = 0; i < files.length; i++) {
              var file = files[i];
              formData.append('up_file[]', file, file.name);
            }

		      $.ajax({
		          url: 'admin/file-manager/fileupload',
		          type: 'POST',
		          enctype: 'multipart/form-data',
		          data: formData,
		          async: false,
		          cache: false,
		          contentType: false,
		          processData: false,
		          success: function (data) {
                     if(typeof data.success !== 'undefined'){
    		              console.log(data);
                          $('#upload_file_to_storage').modal('hide');
                          fileSelect.val("");
                          fileSelect.fileinput("clear");

                          for (var i = 0; i < data.uploadedFileNames.length; i++) {
                                console.log(filemanager.basename(data.uploadedFileNames[i]));
                                filemanager.$data.files.push(filemanager.basename(data.uploadedFileNames[i])+'.'+filemanager.getFileExtension(data.uploadedFileNames[i]));
                          }
                    }else{
                        console.log("Error" +data);
                    }
		          },
		          error: function () {
		              console.log("Error in ajax form submission");
		          }
		      });
		},
		basename: function (url){
		    return ((url=/(([^\/\\\.#\? ]+)(\.\w+)*)([?#].+)?$/.exec(url))!= null)? url[2]: '';
		},
        modal: function(file){
            var modal = $('#delete_sample');
            $($($(modal.find('div.modal-body')).find('div')).find('b')).html(function(event,html){ return filemanager.basename(file); });
            modal.find('a').data('file',file);
            modal.modal('toggle');
        },
    	deleteFile: function(event){

    		file = filemanager.$data.currentDirectory+'/'+$(event.target).data('file');

    		$.get('admin/file-manager/delete',
    		{
    			_token: filemanager.$data._csrfToken,
    			file: file
    		},
    		function( data ) {
    			if(typeof data.success !== 'undefined'){

                    var index = filemanager.$data.files.indexOf($(event.target).data('file'));
                    if (index > -1) {
                      filemanager.$data.files.splice(index, 1);
                    }

                    index = filemanager.$data.folders.indexOf($(event.target).data('file'));
                    if (index > -1) {
                      filemanager.$data.folders.splice(index, 1);
                    }

    				$('#delete_sample').modal('hide');
    			}else{
    				 console.log(data);
    			}
			}
			);

    	},
        getUrlVar: function (location,vary){
            var vars = [], hash;
            var hashes = location.slice(location.indexOf('?') + 1).split('&');
            for(var i = 0; i < hashes.length; i++)
            {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars[vary];
        },
    	getUrlParam: function ( paramName ) {
            var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
            var match = window.location.search.match( reParam );

            return ( match && match.length > 1 ) ? match[1] : null;
        },
        returnFileUrl: function (filepath) {
        	// Simulate user action of selecting a file to be returned to CKEditor.
            var funcNum = 1;/*getUrlParam( 'CKEditorFuncNum' );*/
            var fileUrl = filepath;
            window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
            window.close();
        },
        getFileExtension: function(fileName){
            return fileName.substr(fileName.lastIndexOf('.') + 1);
        },
        isKnownExtension: function(fileName){
            return $.inArray( this.getFileExtension(fileName).toLowerCase() , this.$data.knownFileExtensions ) >= 0;
        }
    }

});
<|endoftext|>


<commit_before>const expect = require('chai').expect;
const std = require('../src/index');

describe('hourlySalary()', () => {
  it('以月薪 36,000 元計算，平均時薪為 150 元', () => {
    expect(std.hourlySalary(36000)).eq(150);
  });
});

describe('overtimePay()', () => {
  describe('休息日 (regular leave)', () => {
    it('平均時薪 150 工作一小時，薪資為 400 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 1, std.REGULAR_LEAVE)).eq(400)
    });

    it('平均時薪 150 工作兩小時，薪資為 400 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 2, std.REGULAR_LEAVE)).eq(400)
    });

    it('平均時薪 150 工作五小時，薪資為 1900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 5, std.REGULAR_LEAVE)).eq(1900)
    });

    it('平均時薪 150 工作 5.5 個小時，薪資為 1900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 5.5, std.REGULAR_LEAVE)).eq(1900)
    });

    it('平均時薪 150 工作 8 個小時，薪資為 1900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 8, std.REGULAR_LEAVE)).eq(1900)
    });

    it('平均時薪 150 工作 8.5 個小時，薪資為 2900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 8.5, std.REGULAR_LEAVE)).eq(2900)
    });

    it('平均時薪 150 工作 10 個小時，薪資為 2900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 10, std.REGULAR_LEAVE)).eq(2900)
    });

    it('平均時薪 150 工作 12 個小時，薪資為 2900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 12, std.REGULAR_LEAVE)).eq(2900)
    });

    it('平均時薪 150 工作 13 個小時，丟出 RangeError（勞基法 32 條）', () => {
      try {
        std.overtimePay(150, 13, std.REGULAR_LEAVE);
      }
      catch (err) {
        expect(err instanceof RangeError).is.true;
      }
    });
  });
});
<commit_msg>Fix overtime pay with working hour less than 4 hours for regular leave<commit_after>const expect = require('chai').expect;
const std = require('../src/index');

describe('hourlySalary()', () => {
  it('以月薪 36,000 元計算，平均時薪為 150 元', () => {
    expect(std.hourlySalary(36000)).eq(150);
  });
});

describe('overtimePay()', () => {
  describe('休息日 (regular leave)', () => {
    it('平均時薪 150 工作一小時，薪資為 900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 1, std.REGULAR_LEAVE)).eq(900)
    });

    it('平均時薪 150 工作兩小時，薪資為 900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 2, std.REGULAR_LEAVE)).eq(900)
    });

    it('平均時薪 150 工作 4 小時，薪資為 900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 4, std.REGULAR_LEAVE)).eq(900)
    });

    it('平均時薪 150 工作五小時，薪資為 1900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 5, std.REGULAR_LEAVE)).eq(1900)
    });

    it('平均時薪 150 工作 5.5 個小時，薪資為 1900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 5.5, std.REGULAR_LEAVE)).eq(1900)
    });

    it('平均時薪 150 工作 8 個小時，薪資為 1900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 8, std.REGULAR_LEAVE)).eq(1900)
    });

    it('平均時薪 150 工作 8.5 個小時，薪資為 2900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 8.5, std.REGULAR_LEAVE)).eq(2900)
    });

    it('平均時薪 150 工作 10 個小時，薪資為 2900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 10, std.REGULAR_LEAVE)).eq(2900)
    });

    it('平均時薪 150 工作 12 個小時，薪資為 2900 元（勞基法 24 條）', () => {
      expect(std.overtimePay(150, 12, std.REGULAR_LEAVE)).eq(2900)
    });

    it('平均時薪 150 工作 13 個小時，丟出 RangeError（勞基法 32 條）', () => {
      try {
        std.overtimePay(150, 13, std.REGULAR_LEAVE);
      }
      catch (err) {
        expect(err instanceof RangeError).is.true;
      }
    });
  });
});
<|endoftext|>