<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(async function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            await setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

/*
    ENABLE THIS WHEN ADAPTER RUNS IN DEAMON MODE TO CHECK THAT IT HAS STARTED SUCCESSFULLY
*/
    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });
/**/

/*
    PUT YOUR OWN TESTS HERE USING
    it('Testname', function ( done) {
        ...
    });

    You can also use "sendTo" method to send messages to the started adapter
*/

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<commit_msg>update testAdapter.js<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(async function () {
            var config = await setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            await setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

/*
    ENABLE THIS WHEN ADAPTER RUNS IN DEAMON MODE TO CHECK THAT IT HAS STARTED SUCCESSFULLY
*/
    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });
/**/

/*
    PUT YOUR OWN TESTS HERE USING
    it('Testname', function ( done) {
        ...
    });

    You can also use "sendTo" method to send messages to the started adapter
*/

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>


<commit_before>/* global describe, it, before*/
'use strict';

// Travis run this file while building.
var execSync = require('child_process').exec
  , path = require('path')
  , basename = path.basename(__filename, '.js')
  , debug = require('debug')('ezmaster:' + basename)
  , request = require('supertest');

//Build the fakeapp image
// Create the container and the manifest file
//Before all the test
before(function() {

  this.timeout(60000);

  var cmd = path.join('docker build -t fakeapp --build-arg https_proxy --build-arg http_proxy '
            , __dirname, '/datasets/fakeapp/');

  execSync(cmd);

});

request = request('http://127.0.0.1:35267');

describe('Test Fakeapp', function () {

  this.timeout(60000);

  it('Create fakeapp', function (done) {

    var data = {
      'longName' : 'fakeapp',
      'project' : 'test',
      'version' : '',
      'study': 'fakeapp',
      'technicalName' :  'test-fakeapp',
      'app' : 'fakeapp'
    };

    request
    .post('/-/v1/instances')
    .send(data)
    .expect(200, function (err) {
      done(err);
    });

  });

  it('Found fakeapp', function (done) {
    request.get('/-/v1/instances/').expect(function (res) {
      if (!res.body['test-fakeapp']) { throw new Error('fakeapp not found!'); }
    })
    .end(done);

  });

  it('Delete fakeapp', function (done) {

    request
    .delete('/-/v1/instances/test-fakeapp')
    .expect(200, function (err) {
      done(err);
    });

  });
});<commit_msg>try to fix travis<commit_after>/* global describe, it, before*/
'use strict';

// Travis run this file while building.
var exec = require('child_process').exec
  , path = require('path')
  , basename = path.basename(__filename, '.js')
  , debug = require('debug')('ezmaster:' + basename)
  , request = require('supertest');

//Build the fakeapp image
// Create the container and the manifest file
//Before all the test
before(function(done) {

  this.timeout(60000);

  var cmd = path.join('docker build -t fakeapp --build-arg https_proxy --build-arg http_proxy '
            , __dirname, '/datasets/fakeapp/');

  exec(cmd, done);

});

request = request('http://127.0.0.1:35267');

describe('Test Fakeapp', function () {

  this.timeout(60000);

  it('Create fakeapp', function (done) {

    var data = {
      'longName' : 'fakeapp',
      'project' : 'test',
      'version' : '',
      'study': 'fakeapp',
      'technicalName' :  'test-fakeapp',
      'app' : 'fakeapp'
    };

    request
    .post('/-/v1/instances')
    .send(data)
    .expect(200, function (err) {
      done(err);
    });

  });

  it('Found fakeapp', function (done) {
    request.get('/-/v1/instances/').expect(function (res) {
      if (!res.body['test-fakeapp']) { throw new Error('fakeapp not found!'); }
    })
    .end(done);

  });

  it('Delete fakeapp', function (done) {

    request
    .delete('/-/v1/instances/test-fakeapp')
    .expect(200, function (err) {
      done(err);
    });

  });
});<|endoftext|>


<commit_before>/**
 * @author simonThiele / https://github.com/simonThiele
 */

module( "Object3D" );

var RadToDeg = 180 / Math.PI;

test( "rotateX", function() {
	var obj = new THREE.Object3D();

	var angleInRad = 1.562;
	obj.rotateX(angleInRad);

	// should calculate the correct rotation on x
	checkIfFloatsAreEqual(obj.rotation.x, angleInRad);
});

test( "rotateY", function() {
	var obj = new THREE.Object3D();

	var angleInRad = -0.346;
	obj.rotateY(angleInRad);

	// should calculate the correct rotation on y
	checkIfFloatsAreEqual(obj.rotation.y, angleInRad);
});

test( "rotateZ", function() {
	var obj = new THREE.Object3D();

	var angleInRad = 1;
	obj.rotateZ(angleInRad);

	// should calculate the correct rotation on y
	checkIfFloatsAreEqual(obj.rotation.z, angleInRad);
});

test( "translateOnAxis", function() {
	var obj = new THREE.Object3D();

	// get a reference object for comparing
	var reference = {x: 1, y: 1.23, z: -4.56};
	obj.translateOnAxis(new THREE.Vector3(1, 0, 0), 1);
	obj.translateOnAxis(new THREE.Vector3(0, 1, 0), 1.23);
	obj.translateOnAxis(new THREE.Vector3(0, 0, 1), -4.56);

	checkIfPropsAreEqual(reference, obj.position);
});

test( "translateX", function() {
	var obj = new THREE.Object3D();
	obj.translateX(1.234);

	ok( obj.position.x === 1.234 , "x is equal" );
});

test( "translateY", function() {
	var obj = new THREE.Object3D();
	obj.translateY(1.234);

	ok( obj.position.y === 1.234 , "y is equal" );
});

test( "translateZ", function() {
	var obj = new THREE.Object3D();
	obj.translateZ(1.234);

	ok( obj.position.z === 1.234 , "z is equal" );
});

test( "lookAt", function() {
	var obj = new THREE.Object3D();
	obj.lookAt(new THREE.Vector3(0, -1, 1));

	ok( obj.rotation.x * RadToDeg === 45 , "x is equal" );
});

test( "getWorldQuaternion", function() {
	var obj = new THREE.Object3D();

	obj.lookAt(new THREE.Vector3(0, -1, 1));
	ok( obj.getWorldRotation().x * RadToDeg === 45 , "x is equal" );

	obj.lookAt(new THREE.Vector3(1, 0, 0));
	ok( obj.getWorldRotation().y * RadToDeg === 90 , "y is equal" );
});

function checkIfPropsAreEqual(reference, obj) {
	ok( obj.x === reference.x , "x is equal" );
	ok( obj.y === reference.y , "y is equal!" );
	ok( obj.z === reference.z , "z is equal!" );
}

// since float equal checking is a mess in js, one solution is to cut off
// decimal places
function checkIfFloatsAreEqual(f1, f2) {
	var f1Rounded = ((f1 * 1000) | 0) / 1000;
	var f2Rounded = ((f2 * 1000) | 0) / 1000;

	ok( f1Rounded === f2Rounded, "passed" );
}
<commit_msg>getWorldQuaternion -> getWorldRotation<commit_after>/**
 * @author simonThiele / https://github.com/simonThiele
 */

module( "Object3D" );

var RadToDeg = 180 / Math.PI;

test( "rotateX", function() {
	var obj = new THREE.Object3D();

	var angleInRad = 1.562;
	obj.rotateX(angleInRad);

	// should calculate the correct rotation on x
	checkIfFloatsAreEqual(obj.rotation.x, angleInRad);
});

test( "rotateY", function() {
	var obj = new THREE.Object3D();

	var angleInRad = -0.346;
	obj.rotateY(angleInRad);

	// should calculate the correct rotation on y
	checkIfFloatsAreEqual(obj.rotation.y, angleInRad);
});

test( "rotateZ", function() {
	var obj = new THREE.Object3D();

	var angleInRad = 1;
	obj.rotateZ(angleInRad);

	// should calculate the correct rotation on y
	checkIfFloatsAreEqual(obj.rotation.z, angleInRad);
});

test( "translateOnAxis", function() {
	var obj = new THREE.Object3D();

	// get a reference object for comparing
	var reference = {x: 1, y: 1.23, z: -4.56};
	obj.translateOnAxis(new THREE.Vector3(1, 0, 0), 1);
	obj.translateOnAxis(new THREE.Vector3(0, 1, 0), 1.23);
	obj.translateOnAxis(new THREE.Vector3(0, 0, 1), -4.56);

	checkIfPropsAreEqual(reference, obj.position);
});

test( "translateX", function() {
	var obj = new THREE.Object3D();
	obj.translateX(1.234);

	ok( obj.position.x === 1.234 , "x is equal" );
});

test( "translateY", function() {
	var obj = new THREE.Object3D();
	obj.translateY(1.234);

	ok( obj.position.y === 1.234 , "y is equal" );
});

test( "translateZ", function() {
	var obj = new THREE.Object3D();
	obj.translateZ(1.234);

	ok( obj.position.z === 1.234 , "z is equal" );
});

test( "lookAt", function() {
	var obj = new THREE.Object3D();
	obj.lookAt(new THREE.Vector3(0, -1, 1));

	ok( obj.rotation.x * RadToDeg === 45 , "x is equal" );
});

test( "getWorldRotation", function() {
	var obj = new THREE.Object3D();

	obj.lookAt(new THREE.Vector3(0, -1, 1));
	ok( obj.getWorldRotation().x * RadToDeg === 45 , "x is equal" );

	obj.lookAt(new THREE.Vector3(1, 0, 0));
	ok( obj.getWorldRotation().y * RadToDeg === 90 , "y is equal" );
});

function checkIfPropsAreEqual(reference, obj) {
	ok( obj.x === reference.x , "x is equal" );
	ok( obj.y === reference.y , "y is equal!" );
	ok( obj.z === reference.z , "z is equal!" );
}

// since float equal checking is a mess in js, one solution is to cut off
// decimal places
function checkIfFloatsAreEqual(f1, f2) {
	var f1Rounded = ((f1 * 1000) | 0) / 1000;
	var f2Rounded = ((f2 * 1000) | 0) / 1000;

	ok( f1Rounded === f2Rounded, "passed" );
}
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';
var async = require('async');
var scaleapi = require('../lib/scaleapi');
var chai = require('chai');
var expect = chai.expect;
var testApiKey = process.env.SCALE_API_TEST_KEY || process.env.SCALE_TEST_API_KEY;

if (!testApiKey) throw new Error('Please set the environment variable SCALE_TEST_API_KEY.');

var client = new scaleapi.ScaleClient(testApiKey);
const TIMEOUT = 4000;

describe('task creation', function() {
  this.timeout(TIMEOUT);
  it('categorize', done => {
    client.createCategorizationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Is this company public or private?',
      attachment_type: 'website',
      attachment: 'http://www.google.com/',
      categories: ['public', 'private']}, done);
  });

  it('categorize fail', done => {
    client.createCategorizationTask({
      callback_url: 'http://www.example.com/callback',
      categories: ['public', 'private']},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('transcription', done => {
    client.createTranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Transcribe the given fields. Then for each news item on the page, transcribe the information for the row.',
      attachment_type: 'website',
      attachment: 'http://www.google.com/',
      fields: {
        'title': 'Title of Webpage',
        'top_result': 'Title of the top result'
      },
      repeatable_fields: {
        'username': 'Username of submitter',
        'comment_count': 'Number of comments'
      }}, done);
  });

  it('transcription fail', done => {
    client.createTranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'website'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('comparison', done => {
    client.createComparisonTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Do the objects in these images have the same pattern?',
      attachment_type: 'image',
      attachments: [
        'http://i.ebayimg.com/00/$T2eC16dHJGwFFZKjy5ZjBRfNyMC4Ig~~_32.JPG',
        'http://images.wisegeek.com/checkered-tablecloth.jpg'
      ],
      choices: ['yes', 'no']}, done);
  });

  it('comparison fail', done => {
    client.createComparisonTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Do the objects in these images have the same pattern?',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('annotation', done => {
    client.createAnnotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a box around each **baby cow** and **big cow**',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['baby cow', 'big cow'],
      with_labels: true}, done);
  });

  it('annotation_min_width', done => {
    client.createAnnotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a box around each **baby cow** and **big cow**',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      min_width: '30',
      objects_to_annotate: ['baby cow', 'big cow'],
      with_labels: true}, done);
  });

  it('annotation fail', done => {
    client.createAnnotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a box around each **baby cow** and **big cow**',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('polygonannotation', done => {
    client.createPolygonannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a tight shape around the big cow.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['big cow'],
      with_labels: true}, done);
  });

  it('polygonannotation fail', done => {
    client.createPolygonannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a tight shape around the big cow.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('lineannotation', done => {
    client.createLineannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw lines along the legs of the big cow.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['leg'],
      splines: true,
      with_labels: true}, done);
  });

  it('lineannotation fail', done => {
    client.createLineannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw lines along the legs of the big cow.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('pointannotation', done => {
    client.createPointannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a point on the big cow.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['big cow'],
      with_labels: true}, done);
  });

  it('pointannotation fail', done => {
    client.createPointannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a tight shape around the big cow.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('segmentannotation', done => {
    client.createSegmentannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Segment the image.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      labels: ['big cow', 'background'],
      allow_unlabeled: true}, done);
  });

  it('segmentannotation fail', done => {
    client.createSegmentannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Segment the image.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('datacollection', done => {
    client.createDatacollectionTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Find the URL for the hiring page for the company with attached website.',
      attachment_type: 'website',
      attachment: 'http://www.google.com/',
      fields: { 'hiring_page': 'Hiring Page URL' }}, done);
  });

  it('datacollection fail', done => {
    client.createDatacollectionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'website'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('audiotranscription', done => {
    client.createAudiotranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'audio',
      attachment: 'https://storage.googleapis.com/deepmind-media/pixie/knowing-what-to-say/second-list/speaker-3.wav',
      verbatim: false}, done);
  });

  it('audiotranscription fail', done => {
    client.createAudiotranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'audio'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('audiotranscription fail2', done => {
    client.createAudiotranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment: 'some_non_url'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });
});

var MAKE_A_TASK = cb => client.createComparisonTask({
  callback_url: 'http://www.example.com/callback',
  instruction: 'Do the objects in these images have the same pattern?',
  attachment_type: 'image',
  attachments: [
    'http://i.ebayimg.com/00/$T2eC16dHJGwFFZKjy5ZjBRfNyMC4Ig~~_32.JPG',
    'http://images.wisegeek.com/checkered-tablecloth.jpg'
  ],
  choices: ['yes', 'no']}, cb);

describe('task methods', function() {
  this.timeout(TIMEOUT);
  it('test cancel', done => {
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => task.cancel(cb)],
      //since test tasks complete instantly, we expect cancellation to fail
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('test task retrieval', done => {
    var task1;
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => {
        task1 = task;
        client.fetchTask(task.id, cb);
      }],
      (err, task2) => {
        expect(task1.status).to.equal('pending');
        expect(task2.status).to.equal('completed');
        var fields = [
          'id', 'callback_url', 'instruction',
          'attachment_type', 'attachment', 'choices',
          'metadata', 'type', 'created_at'
        ];
        fields.forEach(field => expect(task1[field]).to.eql(task2[field]));
        done();
      });
  });

  it('test task retrieval time', done => {
    var startTime;
    var endTime;
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => setTimeout(cb, 500),
      cb => {startTime = (new Date()).toISOString(); cb();},
      cb => setTimeout(cb, 500),
      cb => {endTime = (new Date()).toISOString(); cb();},
      cb => client.tasks({start_time: startTime, end_time: endTime}, cb),
    ], (err, tasks) => {
      expect(tasks.docs).to.be.empty;
      done();
    });
  });

  it('test task retrieval fail', done => {
    client.fetchTask('fake_id_qwertyuiop', err => {
      expect(err).to.be.an.instanceof(scaleapi.ScaleException);
      done();
    });
  });

  it('test tasks', done => {
    var tasks = [];
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => { tasks.push(task); cb(); },
      MAKE_A_TASK,
      (task, cb) => { tasks.push(task); cb(); },
      MAKE_A_TASK,
      (task, cb) => { tasks.push(task); cb(); },
      cb => client.tasks({limit: 3}, cb)
    ], (err, res) => {
      var taskids = tasks.map(task => task.id);
      var retrievedTaskIds = res.docs.map(task => task.id);
      expect(taskids).to.have.members(retrievedTaskIds);
      done();
    });
  });

  it('test tasks invalid', () => {
    try {
      client.tasks({bogus: 0}, err => {});
    } catch(err) {
      expect(err).to.be.an.instanceof(scaleapi.ScaleException);
    }
  });
});
<commit_msg>Check that error was in fact thrown<commit_after>/* eslint-env mocha */
'use strict';
var async = require('async');
var scaleapi = require('../lib/scaleapi');
var chai = require('chai');
var expect = chai.expect;
var testApiKey = process.env.SCALE_API_TEST_KEY || process.env.SCALE_TEST_API_KEY;

if (!testApiKey) throw new Error('Please set the environment variable SCALE_TEST_API_KEY.');

var client = new scaleapi.ScaleClient(testApiKey);
const TIMEOUT = 4000;

describe('task creation', function() {
  this.timeout(TIMEOUT);
  it('categorize', done => {
    client.createCategorizationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Is this company public or private?',
      attachment_type: 'website',
      attachment: 'http://www.google.com/',
      categories: ['public', 'private']}, done);
  });

  it('categorize fail', done => {
    client.createCategorizationTask({
      callback_url: 'http://www.example.com/callback',
      categories: ['public', 'private']},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('transcription', done => {
    client.createTranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Transcribe the given fields. Then for each news item on the page, transcribe the information for the row.',
      attachment_type: 'website',
      attachment: 'http://www.google.com/',
      fields: {
        'title': 'Title of Webpage',
        'top_result': 'Title of the top result'
      },
      repeatable_fields: {
        'username': 'Username of submitter',
        'comment_count': 'Number of comments'
      }}, done);
  });

  it('transcription fail', done => {
    client.createTranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'website'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('comparison', done => {
    client.createComparisonTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Do the objects in these images have the same pattern?',
      attachment_type: 'image',
      attachments: [
        'http://i.ebayimg.com/00/$T2eC16dHJGwFFZKjy5ZjBRfNyMC4Ig~~_32.JPG',
        'http://images.wisegeek.com/checkered-tablecloth.jpg'
      ],
      choices: ['yes', 'no']}, done);
  });

  it('comparison fail', done => {
    client.createComparisonTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Do the objects in these images have the same pattern?',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('annotation', done => {
    client.createAnnotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a box around each **baby cow** and **big cow**',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['baby cow', 'big cow'],
      with_labels: true}, done);
  });

  it('annotation_min_width', done => {
    client.createAnnotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a box around each **baby cow** and **big cow**',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      min_width: '30',
      objects_to_annotate: ['baby cow', 'big cow'],
      with_labels: true}, done);
  });

  it('annotation fail', done => {
    client.createAnnotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a box around each **baby cow** and **big cow**',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('polygonannotation', done => {
    client.createPolygonannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a tight shape around the big cow.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['big cow'],
      with_labels: true}, done);
  });

  it('polygonannotation fail', done => {
    client.createPolygonannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a tight shape around the big cow.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('lineannotation', done => {
    client.createLineannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw lines along the legs of the big cow.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['leg'],
      splines: true,
      with_labels: true}, done);
  });

  it('lineannotation fail', done => {
    client.createLineannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw lines along the legs of the big cow.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('pointannotation', done => {
    client.createPointannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a point on the big cow.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      objects_to_annotate: ['big cow'],
      with_labels: true}, done);
  });

  it('pointannotation fail', done => {
    client.createPointannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Draw a tight shape around the big cow.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('segmentannotation', done => {
    client.createSegmentannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Segment the image.',
      attachment_type: 'image',
      attachment: 'http://i.imgur.com/v4cBreD.jpg',
      labels: ['big cow', 'background'],
      allow_unlabeled: true}, done);
  });

  it('segmentannotation fail', done => {
    client.createSegmentannotationTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Segment the image.',
      attachment_type: 'image'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('datacollection', done => {
    client.createDatacollectionTask({
      callback_url: 'http://www.example.com/callback',
      instruction: 'Find the URL for the hiring page for the company with attached website.',
      attachment_type: 'website',
      attachment: 'http://www.google.com/',
      fields: { 'hiring_page': 'Hiring Page URL' }}, done);
  });

  it('datacollection fail', done => {
    client.createDatacollectionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'website'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('audiotranscription', done => {
    client.createAudiotranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'audio',
      attachment: 'https://storage.googleapis.com/deepmind-media/pixie/knowing-what-to-say/second-list/speaker-3.wav',
      verbatim: false}, done);
  });

  it('audiotranscription fail', done => {
    client.createAudiotranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment_type: 'audio'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('audiotranscription fail2', done => {
    client.createAudiotranscriptionTask({
      callback_url: 'http://www.example.com/callback',
      attachment: 'some_non_url'},
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });
});

var MAKE_A_TASK = cb => client.createComparisonTask({
  callback_url: 'http://www.example.com/callback',
  instruction: 'Do the objects in these images have the same pattern?',
  attachment_type: 'image',
  attachments: [
    'http://i.ebayimg.com/00/$T2eC16dHJGwFFZKjy5ZjBRfNyMC4Ig~~_32.JPG',
    'http://images.wisegeek.com/checkered-tablecloth.jpg'
  ],
  choices: ['yes', 'no']}, cb);

describe('task methods', function() {
  this.timeout(TIMEOUT);
  it('test cancel', done => {
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => task.cancel(cb)],
      //since test tasks complete instantly, we expect cancellation to fail
      err => {
        expect(err).to.be.an.instanceof(scaleapi.ScaleException);
        done();
      });
  });

  it('test task retrieval', done => {
    var task1;
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => {
        task1 = task;
        client.fetchTask(task.id, cb);
      }],
      (err, task2) => {
        expect(task1.status).to.equal('pending');
        expect(task2.status).to.equal('completed');
        var fields = [
          'id', 'callback_url', 'instruction',
          'attachment_type', 'attachment', 'choices',
          'metadata', 'type', 'created_at'
        ];
        fields.forEach(field => expect(task1[field]).to.eql(task2[field]));
        done();
      });
  });

  it('test task retrieval time', done => {
    var startTime;
    var endTime;
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => setTimeout(cb, 500),
      cb => {startTime = (new Date()).toISOString(); cb();},
      cb => setTimeout(cb, 500),
      cb => {endTime = (new Date()).toISOString(); cb();},
      cb => client.tasks({start_time: startTime, end_time: endTime}, cb),
    ], (err, tasks) => {
      expect(tasks.docs).to.be.empty;
      done();
    });
  });

  it('test task retrieval fail', done => {
    client.fetchTask('fake_id_qwertyuiop', err => {
      expect(err).to.be.an.instanceof(scaleapi.ScaleException);
      done();
    });
  });

  it('test tasks', done => {
    var tasks = [];
    async.waterfall([
      MAKE_A_TASK,
      (task, cb) => { tasks.push(task); cb(); },
      MAKE_A_TASK,
      (task, cb) => { tasks.push(task); cb(); },
      MAKE_A_TASK,
      (task, cb) => { tasks.push(task); cb(); },
      cb => client.tasks({limit: 3}, cb)
    ], (err, res) => {
      var taskids = tasks.map(task => task.id);
      var retrievedTaskIds = res.docs.map(task => task.id);
      expect(taskids).to.have.members(retrievedTaskIds);
      done();
    });
  });

  it('test tasks invalid', () => {
    let errorThrown = false;
    try {
      client.tasks({bogus: 0}, err => {});
    } catch(err) {
      expect(err).to.be.an.instanceof(scaleapi.ScaleException);
      errorThrown = true;
    }
    expect(errorThrown).to.equal(true);
  });
});
<|endoftext|>


<commit_before>// Switching mocha to TDD style
window.mocha.setup({ui: 'bdd'});

// Add new assertions here<commit_msg>remove test config file from tests in pip-webui-locations<commit_after><|endoftext|>


<commit_before>import test from 'ava';
import swipe from 'vanilla-touchwipe';

import configure from '../../js/lib/configure';
import defaultOptions from '../../js/lib/default-options';
import createContext from './helper/create-context';

import Perfundo from '../../js/lib/perfundo';

const defaultContext = createContext(defaultOptions);
const defaultDependencies = {
  configure,
  context: defaultContext,
  defaultOptions,
  swipe,
};

test(`Is a function.`, (t) => {
  t.true(typeof Perfundo === `function`);
});

test(`Returns an instance of itself if a single target is given.`, (t) => {
  const context = createContext(defaultOptions, 1);
  const dependencies = Object.assign({}, defaultDependencies, { context });
  const perfundoInstance = new Perfundo(dependencies, `.perfundo`);

  t.true(typeof perfundoInstance === `object`);
  t.truthy(perfundoInstance.context);
  t.truthy(perfundoInstance.element);
  t.truthy(perfundoInstance.options);
});

test(`Returns an array of Perfundo instances if a multi target is given.`, (t) => {
  const context = createContext(defaultOptions, 2);
  const dependencies = Object.assign({}, defaultDependencies, { context });
  const perfundoInstances = new Perfundo(dependencies, `.perfundo`);

  t.true(Array.isArray(perfundoInstances));
  t.true(typeof perfundoInstances[0] === `object`);
  t.true(typeof perfundoInstances[1] === `object`);
});
<commit_msg>Add missing unit tests<commit_after>import test from 'ava';
import swipe from 'vanilla-touchwipe';

import configure from '../../js/lib/configure';
import defaultOptions from '../../js/lib/default-options';
import createContext from './helper/create-context';

import Perfundo from '../../js/lib/perfundo';

const defaultContext = createContext(defaultOptions);
const defaultDependencies = {
  configure,
  context: defaultContext,
  defaultOptions,
  swipe,
};

test(`Is a function.`, (t) => {
  t.true(typeof Perfundo === `function`);
});

test(`Returns an instance of itself if a single target is given.`, (t) => {
  const context = createContext(defaultOptions, 1);
  const dependencies = Object.assign({}, defaultDependencies, { context });
  const perfundoInstance = new Perfundo(dependencies, `.perfundo`);

  t.true(typeof perfundoInstance === `object`);
  t.truthy(perfundoInstance.context);
  t.truthy(perfundoInstance.element);
  t.truthy(perfundoInstance.options);
});

test(`Returns an array of Perfundo instances if a multi target is given.`, (t) => {
  const context = createContext(defaultOptions, 2);
  const dependencies = Object.assign({}, defaultDependencies, { context });
  const perfundoInstances = new Perfundo(dependencies, `.perfundo`);

  t.true(Array.isArray(perfundoInstances));
  t.true(typeof perfundoInstances[0] === `object`);
  t.true(typeof perfundoInstances[1] === `object`);
});

test(`Should add and remove active class on overlay element.`, (t) => {
  const context = createContext(defaultOptions, 1);
  const dependencies = Object.assign({}, defaultDependencies, { context });
  const perfundoInstance = new Perfundo(dependencies, `.perfundo`);

  perfundoInstance.open();
  let overlayElementHasActiveClass = context.querySelector(`.perfundo__overlay`).classList.contains(`is-active`);

  t.true(overlayElementHasActiveClass);

  perfundoInstance.close();
  overlayElementHasActiveClass = context.querySelector(`.perfundo__overlay`).classList.contains(`is-active`);

  t.false(overlayElementHasActiveClass);
});

test(`Should call \`close()\`, and \`click()\` on the previous overlay element.`, (t) => {
  const context = createContext(defaultOptions, 2);
  const dependencies = Object.assign({}, defaultDependencies, { context });

  let mockCloseCalled = false;
  const mockClose = () => { mockCloseCalled = true; };

  let mockClickCalled = false;
  const mockClick = () => { mockClickCalled = true; };

  const perfundoInstances = new Perfundo(dependencies, `.perfundo`);

  perfundoInstances[1].close = mockClose;
  context.querySelector(`.perfundo__link`).click = mockClick;
  perfundoInstances[1].prev();

  t.true(mockCloseCalled);
  t.true(mockClickCalled);
});

test(`Should call \`close()\`, and \`click()\` on the next overlay element.`, (t) => {
  const context = createContext(defaultOptions, 2);
  const dependencies = Object.assign({}, defaultDependencies, { context });

  let mockCloseCalled = false;
  const mockClose = () => { mockCloseCalled = true; };

  let mockClickCalled = false;
  const mockClick = () => { mockClickCalled = true; };

  const perfundoInstances = new Perfundo(dependencies, `.perfundo`);

  perfundoInstances[0].close = mockClose;
  context.querySelector(`.perfundo + .perfundo .perfundo__link`).click = mockClick;
  perfundoInstances[0].next();

  t.true(mockCloseCalled);
  t.true(mockClickCalled);
});

test(`Should return the elements root Perfundo element.`, (t) => {
  const context = createContext(defaultOptions, 1);
  const dependencies = Object.assign({}, defaultDependencies, { context });
  const perfundoInstance = new Perfundo(dependencies, `.perfundo`);

  const actual = perfundoInstance.getRootElement(context.querySelector(`.perfundo__overlay`));
  const expected = context.querySelector(`.perfundo`);

  t.deepEqual(actual, expected);
});
<|endoftext|>


<commit_before>(function () {
var testobj = new Test.TAP.Class();
testobj.plan(10)

testobj.testMultiMethod = function() {
    var t = this;
    t.diag("Sanity");
    t.ok(Joose,   "Joose is here");
    t.ok(JooseX.MultiMethod,   "We have the MultiMethod class");

    Class("MultiMethodTestClass", {
        methods: {
            test: function () { return "foo"  }
        }
    });

    var method = new JooseX.MultiMethod("multi", function () {}, {});
    var patterns = [
        {
            signature : [],
            fun       : function() {
                return "foo";
            }
        },
        {
            signature : ["quux", TYPE.Func],
            fun       : function() {
                return "fooQUUX";
            }
        },
        {
            signature : [TYPE.Str, TYPE.Func],
            fun       : function() {
                return "fooStringFunc";
            }
        }
    ];
    method.setPatterns(patterns);
    MultiMethodTestClass.meta.addMethodObject(method);

    var o = new MultiMethodTestClass();

    t.ok(o.meta.can("multi"), "Method is there");
    t.ok(typeof o.multi === "function", "There is actually a function in the spot");

    var result;
    t.lives_ok(function () {
        result = o.multi();
    }, "calling with correct argument signature lives")

    t.is(result, "foo", "result from method call is correct")

    var result2;
    t.lives_ok(function () {
        result2 = o.multi("blah", function() {});
    }, "calling with a different correct argument signature lives")

    t.ok(result != result2,
        "result from method calls with different signatures "
         + "produce different results")

    t.is(result2, "fooStringFunc", "result from second signature for method"
        + "call is correct")

    // exceptions
    t.throws_ok(function () {
        o.multi(1,2,3)
    }, /multi-method type method call with no matching signature/,
        "Calling with incorrect signature throws exception")

    t.is(o.multi("quux", function() {}), "fooQUUX",
        'dispatched on value also')
    // builder syntax
    //t.diag("Testing builder syntax for typed methods")

};

return testobj;
})()
<commit_msg>descriptive comments on the test patterns<commit_after>(function () {
var testobj = new Test.TAP.Class();
testobj.plan(10)

testobj.testMultiMethod = function() {
    var t = this;
    t.diag("Sanity");
    t.ok(Joose,   "Joose is here");
    t.ok(JooseX.MultiMethod,   "We have the MultiMethod class");

    Class("MultiMethodTestClass", {
        methods: {
            test: function () { return "foo"  }
        }
    });

    var method = new JooseX.MultiMethod("multi", function () {}, {});
    var patterns = [
        {
            signature : [],
            fun       : function() {
                return "foo";
            }
        },
        // Order matters. So this signature has to come before the other
        // Rule of thumb more specific matches go before more general matches.
        // this is considered a feature
        {
            signature : ["quux", TYPE.Func],
            fun       : function() {
                return "fooQUUX";
            }
        },
        {
            signature : [TYPE.Str, TYPE.Func],
            fun       : function() {
                return "fooStringFunc";
            }
        }
    ];
    method.setPatterns(patterns);
    MultiMethodTestClass.meta.addMethodObject(method);

    var o = new MultiMethodTestClass();

    t.ok(o.meta.can("multi"), "Method is there");
    t.ok(typeof o.multi === "function", "There is actually a function in the spot");

    var result;
    t.lives_ok(function () {
        result = o.multi();
    }, "calling with correct argument signature lives")

    t.is(result, "foo", "result from method call is correct")

    var result2;
    t.lives_ok(function () {
        result2 = o.multi("blah", function() {});
    }, "calling with a different correct argument signature lives")

    t.ok(result != result2,
        "result from method calls with different signatures "
         + "produce different results")

    t.is(result2, "fooStringFunc", "result from second signature for method"
        + "call is correct")

    // exceptions
    t.throws_ok(function () {
        o.multi(1,2,3)
    }, /multi-method type method call with no matching signature/,
        "Calling with incorrect signature throws exception")

    t.is(o.multi("quux", function() {}), "fooQUUX",
        'dispatched on value also')
    // builder syntax
    //t.diag("Testing builder syntax for typed methods")

};

return testobj;
})()
<|endoftext|>


<commit_before>'use strict';

const util = require('util');
const ttn = require('ttn');
const iothub = require('azure-iothub');
const device = require('azure-iot-device');
const amqp = require('azure-iot-device-amqp');
const common = require('azure-iot-common');
const EventEmitter = require('events');

const DEFAULT_TTN_BROKER = 'staging.thethingsnetwork.org';
const SAK_CONNECTION_STRING = 'HostName=%s.azure-devices.net;SharedAccessKeyName=%s;SharedAccessKey=%s';
const DEVICE_CONNECTION_STRING = 'HostName=%s.azure-devices.net;DeviceId=%%s;SharedAccessKey=%%s';

const Bridge = class Bridge extends EventEmitter {
  constructor(appEUI, appAccessKey, hubName, keyName, key, options) {
    super();
    options = options || {};

    this.registry = iothub.Registry.fromConnectionString(util.format(SAK_CONNECTION_STRING, hubName, keyName, key));
    this.deviceConnectionString = util.format(DEVICE_CONNECTION_STRING, hubName);
    this.devices = {};

    this.ttnClient = new ttn.Client(options.ttnBroker || DEFAULT_TTN_BROKER, appEUI, appAccessKey);
    this.ttnClient.on('connect', super.emit.bind(this, 'ttn-connect'));
    this.ttnClient.on('error', super.emit.bind(this, 'error'));
    this.ttnClient.on('uplink', this._handleUplink.bind(this));
  }

  _getDevice(devEUI) {
    if (this.devices[devEUI])
      return Promise.resolve(this.devices[devEUI]);

    return new Promise((resolve, reject) => {
      var device = new iothub.Device(null);
      device.deviceId = devEUI;
      this.registry.create(device, (err, deviceInfo) => {
        if (err) { // The device probably exists
          this.registry.get(device.deviceId, (err, deviceInfo) => {
            if (err) {
              reject(err);
            } else
              resolve(deviceInfo);
          });
        } else
          resolve(deviceInfo);
      });
    }).then(deviceInfo => {
      var key = deviceInfo.authentication.SymmetricKey.primaryKey;
      var connectionString = util.format(this.deviceConnectionString, devEUI, key);
      var client = amqp.clientFromConnectionString(connectionString);
      return new Promise((resolve, reject) => {
        client.open(err => {
          if (err)
            reject(err);
          else {
            this.devices[devEUI] = client;
            resolve(client);
          }
        });
      });
    });
  }

  _handleUplink(uplink) {
    console.log('%s: Handling uplink', uplink.devEUI);

    this._getDevice(uplink.devEUI).then(deviceInfo => {
      var data = JSON.stringify(Object.assign({}, uplink.fields, {
        deviceId: uplink.devEUI,
        time: uplink.metadata.server_time
      }));
      var message = new device.Message(data);
      var that = this;
      deviceInfo.sendEvent(message, (err, res) => {
        if (err) {
          console.warn('%s: Could not send event: %s', uplink.devEUI, err);
          that.emit('error', err);
        }
        else
          that.emit('uplink', { devEUI: uplink.devEUI, data: data });
      });
    })
    .catch(err => {
      console.log('%s: Could not get device: %s', uplink.devEUI, err);
      super.emit('error', err);
    });
  }
}

module.exports = {
  Bridge: Bridge
};<commit_msg>Close connection when send fails, code style<commit_after>'use strict';

const util = require('util');
const ttn = require('ttn');
const iothub = require('azure-iothub');
const device = require('azure-iot-device');
const amqp = require('azure-iot-device-amqp');
const common = require('azure-iot-common');
const EventEmitter = require('events');

const DEFAULT_TTN_BROKER = 'staging.thethingsnetwork.org';
const SAK_CONNECTION_STRING = 'HostName=%s.azure-devices.net;SharedAccessKeyName=%s;SharedAccessKey=%s';
const DEVICE_CONNECTION_STRING = 'HostName=%s.azure-devices.net;DeviceId=%%s;SharedAccessKey=%%s';

const Bridge = class Bridge extends EventEmitter {
  constructor(appEUI, appAccessKey, hubName, keyName, key, options) {
    super();
    options = options || {};

    this.registry = iothub.Registry.fromConnectionString(util.format(SAK_CONNECTION_STRING, hubName, keyName, key));
    this.deviceConnectionString = util.format(DEVICE_CONNECTION_STRING, hubName);
    this.devices = {};

    this.ttnClient = new ttn.Client(options.ttnBroker || DEFAULT_TTN_BROKER, appEUI, appAccessKey);
    this.ttnClient.on('connect', super.emit.bind(this, 'ttn-connect'));
    this.ttnClient.on('error', super.emit.bind(this, 'error'));
    this.ttnClient.on('uplink', this._handleUplink.bind(this));
  }

  _getDevice(devEUI) {
    if (this.devices[devEUI]) {
      return Promise.resolve(this.devices[devEUI]);
    }

    return new Promise((resolve, reject) => {
      const device = new iothub.Device(null);
      device.deviceId = devEUI;
      this.registry.create(device, (err, deviceInfo) => {
        if (!err) {
          resolve(deviceInfo);
        } else {
          // The device probably exists
          this.registry.get(device.deviceId, (err, deviceInfo) => {
            if (err) {
              reject(err);
            } else {
              resolve(deviceInfo);
            }
          });
        }
      });
    }).then(deviceInfo => {
      const key = deviceInfo.authentication.SymmetricKey.primaryKey;
      const connectionString = util.format(this.deviceConnectionString, devEUI, key);
      const client = amqp.clientFromConnectionString(connectionString);
      return new Promise((resolve, reject) => {
        client.open(err => {
          if (err) {
            reject(err);
          } else {
            this.devices[devEUI] = client;
            resolve(client);
          }
        });
      });
    });
  }

  _handleUplink(uplink) {
    console.log('%s: Handling uplink', uplink.devEUI);

    this._getDevice(uplink.devEUI).then(deviceInfo => {
      const data = JSON.stringify(Object.assign({}, uplink.fields, {
        deviceId: uplink.devEUI,
        time: uplink.metadata.server_time
      }));
      const message = new device.Message(data);

      deviceInfo.sendEvent(message, (err, res) => {
        if (err) {
          console.warn('%s: Could not send event: %s. Closing connection', uplink.devEUI, err);
          deviceInfo.close(err => {
            // Delete reference even if close failed
            delete this.devices[uplink.devEUI];
          });
          this.emit('error', err);
        } else {
          this.emit('uplink', { devEUI: uplink.devEUI, data: data });
        }
      });
    })
    .catch(err => {
      console.log('%s: Could not get device: %s', uplink.devEUI, err);
      super.emit('error', err);
    });
  }
}

module.exports = {
  Bridge: Bridge
};<|endoftext|>


<commit_before>var Twit = require('twit'),
	geocoder = require('geocoder'),
	request = require('request'),
	moment = require('moment'),
	keys = require('../api_keys/weatherbot_keys');

var Bot = new Twit({
    consumer_key:         keys.TWITTER_CONSUMER_KEY,
	consumer_secret:      keys.TWITTER_CONSUMER_SECRET,
	access_token:         keys.TWITTER_ACCESS_TOKEN,
	access_token_secret:  keys.TWITTER_ACCESS_TOKEN_SECRET
});

// Listen To Twitter Stream filtered for @HiWeatherbot
var stream = Bot.stream('statuses/filter', { track: ['@HiWeatherbot'] });

stream.on('error', function (error) {
	// Log the error
	console.log("Weatherbot error: ", error);
});

stream.on('limit', function(limitMessage){
  	console.log("Weatherbot limit problem: ",limitMessage);
});

stream.on('disconnect', function (disconnectMessage) {
  	console.log("Weatherbot disconnect issue: ",disconnectMessage);
});

stream.on('reconnect', function (request, response, connectInterval) {
	console.log("Reconnect issue. Reconnecting in:", connectInterval + "ms");
	console.log("Reconnect Request: " + request);
	console.log("Reconnect Response: " + response);
});

// If someone mentions @HiWeatherbot, jump into action
stream.on('tweet', function (tweet) {

	// First, making sure the tweet is not directed at me --
	// needs to be a directed message with @hiweatherbot, not just a mention.
    // We can know because the in_reply_to_user_id isn't me (2908555695)
 	if (tweet.in_reply_to_user_id != 2908555695) {

		// in_reply_to_user_id doesn't match
		// Tweet not directed at me, just a mention
		// Log it (might also do something like Slack it)

		var log_text = "Weatherbot note: Someone's tweeting about me. http://twitter.com/" + tweet.user.screen_name + "/status/" + tweet.id_str;
		console.log(log_text);

		} else {

		console.log("---");
		console.log("Weeatherbot tweet received:", tweet.text);

		// Tweet directed at me! Extract the location from the tweet text
		var location_text = extractLocation(tweet.text);

		// TODO: Detect other fun things, like "thank you" and "hello"

		// TODO: Detect a blank tweet, which messes up the geocoder code

		// Go forth and geocode that location
		geocoder.geocode(location_text, function(err, data) {

			var replyto = tweet.user.screen_name;
			var tweet_text;

			if (err) {

				// @reply about the geocode fail
				tweet_text = "@" + replyto + " Hi! Something went wrong with my geocoding system, so I can't get you a forecast. Sorry! cc @jkeefe";
				tweetThis(tweet_text, tweet.id_str);

				// log the error
				console.log("Geocode error: ", err);

			} else if (data.status == "ZERO_RESULTS") {

				// @reply that we couldn't find any results
				tweet_text = "@" + replyto + " Hi! I couldn't find a location based on your tweet to me. For a forecast, try again with a city name.";
				tweetThis(tweet_text, tweet.id_str);
				console.log("Geocode Zero Results");

			} else {

				console.log("Successful geocode.");

				// found a location! Pull out the lat/lon
				var lat = data.results[0].geometry.location.lat;
				var lon = data.results[0].geometry.location.lng;

				// grab the name of the locality for the tweet
				var locality = getLocality(data.results[0].address_components);

				// should we use celsius instead?
				var country = getCountry(data.results[0].address_components);
				var farenheit_countries = ["US", "BS", "BZ", "KY", "PW", "AS", "VI"];
				var included = farenheit_countries.indexOf(country);
				var use_celsius = false;

				if (included == -1 ) {
					// our country is not in the list
					use_celsius = true;
				}

				// configure the request to forecast.io
				var options = {
					url: 'https://api.forecast.io/forecast/'+ keys.FORECAST_IO_API_KEY +'/' + lat + ',' + lon,
					method: 'GET'
				};

				// Start the request to forecast.io
				request(options, function (error, response, body) {

					if (error || response.statusCode != 200) {

						// Something went wrong getting forecast
						// @reply about that
						tweet_text = "@" + replyto + " Hi! Something went wrong getting your forcast. I'm sorry! cc @jkeefe";
						tweetThis(tweet_text, tweet.id_str);

						// log the error
						console.log("Forecast fetching error: ", error);

					} else {

						console.log("Successful forecast fetch.");

						// all good getting forecast
						var weather = JSON.parse(body);

						// What time is it!?!
						// Here current_local_time will be set to the time at the forecast location
						var current_local_time = moment.unix(weather.currently.time);

							// adjust the offset based on the one provided by forecast,
							// so we are using times local to the forecast point.
							// ... need to take the inverse since moment assumes negative offset
							current_local_time = current_local_time.zone(-1 * weather.offset);

						// use today's forecast data[0] if it's before noon local time
						// use tomorrow's forecast data[1] if it's after noonlocal time
						var forecast;

						if (current_local_time.hour() < 12) {
							forecast = weather.daily.data[0];
						} else {
							forecast = weather.daily.data[1];
						}

						// grab the forecast time, turn it into an unix moment object
						var forecast_time = moment.unix(forecast.time);

							// adjust the offset based on the one provided by forecast,
							// again, using times local to the forecast point.
							// ... need to take the inverse since moment assumes negative offset
							forecast_time = forecast_time.zone(-1 * weather.offset);

						// build the components of the tweet ...

						// if the forecast day of the week and the current day of the week are the same,
						// call the forecast "today." Otherwise use the day of the week for the forecast.
						var forecast_day;
						if (forecast_time.day() == current_local_time.day()) {
							forecast_day = "today";
						} else {
							// take the day of the week out of the forecast time (Sunday, Monday, Tuesday)
							forecast_day = forecast_time.format("dddd");
						}

						var summary = forecast.summary;
						var high = "";

							if (use_celsius === true) {

								var temp = (forecast.temperatureMax - 32) * 5 / 9;
								high = Math.round(temp).toString(10) + "°C";

							} else {

								high = Math.round(forecast.temperatureMax).toString(10) + "°F";

							}

						var chance = Math.round(forecast.precipProbability * 100);
						var precip = forecast.precipType;
						var more = "http://forecast.io/#/f/" + lat.toPrecision(6) + "," + lon.toPrecision(6);
						var precip_text = "";

						// show precipitation repsonse if the chance is greater than 0%
						if (chance > 0) {

							precip_text = "chance of " + precip + " " + chance + "%.";

						} else {

							precip_text = "with no precipitation likely.";

						}

						tweet_text = "@" + replyto + " Hi! " + locality + " " + forecast_day + ": " + summary + " High of " + high + ", " + precip_text;

						// make sure it's not more than 140 characters
						tweet_text = tweet_text.substring(0,140);

						// if there's room, add on the forecast.io url
						// this is based on the current t.co length (22) from 140 (118) and a space (117)
						// more info here: https://dev.twitter.com/overview/t.co
						if (tweet_text.length <= 117) {
							tweet_text = tweet_text + " " + more;
						}

						console.log("Tweet sent:", tweet_text);

						//Turn off tweets here if testing locally
						tweetThis(tweet_text, tweet.id_str);

					}

				});

			}

		});

	}

});

function extractLocation(text) {

	// This function cleans up the tweet's text to distill it into a location, if it can

	// Take any @mentions out of the text
	var location = text.replace(/@\S+/g, '');

	// Now take any #hashtags out, too
	location = location.replace(/#\S+/g, '');

	// Eventually also remove links

	return location;
}

// extract country short name (e.g. GB for Great Britain) from google geocode API result
function getCountry(addrComponents) {
    for (var i = 0; i < addrComponents.length; i++) {
        if (addrComponents[i].types[0] == "country") {
            return addrComponents[i].short_name;
        }
    }
    return false;
}

// extract locality (e.g. Minneapolis) from google geocode API result
function getLocality(addrComponents) {
    for (var i = 0; i < addrComponents.length; i++) {
        if (addrComponents[i].types[1] == "sublocality") {
            return addrComponents[i].long_name;
        } else if (addrComponents[i].types[0] == "locality") {
			return addrComponents[i].short_name;
		}
    }
    // This replaces a blank locality in the tweet. So instead of "Minneapolis Friday"
	// tweet will say "For Friday"
    return "For";
}

// the tweeting function
function tweetThis(text, id) {

	Bot.post('statuses/update', {
		status: text,
		in_reply_to_status_id: id
		}, function(err, data, response) {
			/// console.log(data);
	});

}<commit_msg>updated forecast.io -> darksky.net<commit_after>var Twit = require('twit'),
	geocoder = require('geocoder'),
	request = require('request'),
	moment = require('moment'),
	keys = require('../api_keys/weatherbot_keys');

var Bot = new Twit({
    consumer_key:         keys.TWITTER_CONSUMER_KEY,
	consumer_secret:      keys.TWITTER_CONSUMER_SECRET,
	access_token:         keys.TWITTER_ACCESS_TOKEN,
	access_token_secret:  keys.TWITTER_ACCESS_TOKEN_SECRET
});

// Listen To Twitter Stream filtered for @HiWeatherbot
var stream = Bot.stream('statuses/filter', { track: ['@HiWeatherbot'] });

stream.on('error', function (error) {
	// Log the error
	console.log("Weatherbot error: ", error);
});

stream.on('limit', function(limitMessage){
  	console.log("Weatherbot limit problem: ",limitMessage);
});

stream.on('disconnect', function (disconnectMessage) {
  	console.log("Weatherbot disconnect issue: ",disconnectMessage);
});

stream.on('reconnect', function (request, response, connectInterval) {
	console.log("Reconnect issue. Reconnecting in:", connectInterval + "ms");
	console.log("Reconnect Request: " + request);
	console.log("Reconnect Response: " + response);
});

// If someone mentions @HiWeatherbot, jump into action
stream.on('tweet', function (tweet) {

	// First, making sure the tweet is not directed at me --
	// needs to be a directed message with @hiweatherbot, not just a mention.
    // We can know because the in_reply_to_user_id isn't me (2908555695)
 	if (tweet.in_reply_to_user_id != 2908555695) {

		// in_reply_to_user_id doesn't match
		// Tweet not directed at me, just a mention
		// Log it (might also do something like Slack it)

		var log_text = "Weatherbot note: Someone's tweeting about me. http://twitter.com/" + tweet.user.screen_name + "/status/" + tweet.id_str;
		console.log(log_text);

		} else {

		console.log("---");
		console.log("Weeatherbot tweet received:", tweet.text);

		// Tweet directed at me! Extract the location from the tweet text
		var location_text = extractLocation(tweet.text);

		// TODO: Detect other fun things, like "thank you" and "hello"

		// TODO: Detect a blank tweet, which messes up the geocoder code

		// Go forth and geocode that location
		geocoder.geocode(location_text, function(err, data) {

			var replyto = tweet.user.screen_name;
			var tweet_text;

			if (err) {

				// @reply about the geocode fail
				tweet_text = "@" + replyto + " Hi! Something went wrong with my geocoding system, so I can't get you a forecast. Sorry! cc @jkeefe";
				tweetThis(tweet_text, tweet.id_str);

				// log the error
				console.log("Geocode error: ", err);

			} else if (data.status == "ZERO_RESULTS") {

				// @reply that we couldn't find any results
				tweet_text = "@" + replyto + " Hi! I couldn't find a location based on your tweet to me. For a forecast, try again with a city name.";
				tweetThis(tweet_text, tweet.id_str);
				console.log("Geocode Zero Results");

			} else {

				console.log("Successful geocode.");

				// found a location! Pull out the lat/lon
				var lat = data.results[0].geometry.location.lat;
				var lon = data.results[0].geometry.location.lng;

				// grab the name of the locality for the tweet
				var locality = getLocality(data.results[0].address_components);

				// should we use celsius instead?
				var country = getCountry(data.results[0].address_components);
				var farenheit_countries = ["US", "BS", "BZ", "KY", "PW", "AS", "VI"];
				var included = farenheit_countries.indexOf(country);
				var use_celsius = false;

				if (included == -1 ) {
					// our country is not in the list
					use_celsius = true;
				}

				// configure the request to darksky.net
				var options = {
					url: 'https://api.darksky.net/forecast/'+ keys.FORECAST_IO_API_KEY +'/' + lat + ',' + lon,
					method: 'GET'
				};

				// Start the request to api.darksky.net
				request(options, function (error, response, body) {

					if (error || response.statusCode != 200) {

						// Something went wrong getting forecast
						// @reply about that
						tweet_text = "@" + replyto + " Hi! Something went wrong getting your forcast. I'm sorry! cc @jkeefe";
						tweetThis(tweet_text, tweet.id_str);

						// log the error
						console.log("Forecast fetching error: ", error);

					} else {

						console.log("Successful forecast fetch.");

						// all good getting forecast
						var weather = JSON.parse(body);

						// What time is it!?!
						// Here current_local_time will be set to the time at the forecast location
						var current_local_time = moment.unix(weather.currently.time);

							// adjust the offset based on the one provided by forecast,
							// so we are using times local to the forecast point.
							// ... need to take the inverse since moment assumes negative offset
							current_local_time = current_local_time.zone(-1 * weather.offset);

						// use today's forecast data[0] if it's before noon local time
						// use tomorrow's forecast data[1] if it's after noonlocal time
						var forecast;

						if (current_local_time.hour() < 12) {
							forecast = weather.daily.data[0];
						} else {
							forecast = weather.daily.data[1];
						}

						// grab the forecast time, turn it into an unix moment object
						var forecast_time = moment.unix(forecast.time);

							// adjust the offset based on the one provided by forecast,
							// again, using times local to the forecast point.
							// ... need to take the inverse since moment assumes negative offset
							forecast_time = forecast_time.zone(-1 * weather.offset);

						// build the components of the tweet ...

						// if the forecast day of the week and the current day of the week are the same,
						// call the forecast "today." Otherwise use the day of the week for the forecast.
						var forecast_day;
						if (forecast_time.day() == current_local_time.day()) {
							forecast_day = "today";
						} else {
							// take the day of the week out of the forecast time (Sunday, Monday, Tuesday)
							forecast_day = forecast_time.format("dddd");
						}

						var summary = forecast.summary;
						var high = "";

							if (use_celsius === true) {

								var temp = (forecast.temperatureMax - 32) * 5 / 9;
								high = Math.round(temp).toString(10) + "°C";

							} else {

								high = Math.round(forecast.temperatureMax).toString(10) + "°F";

							}

						var chance = Math.round(forecast.precipProbability * 100);
						var precip = forecast.precipType;
						var more = "http://darksky.net/#/f/" + lat.toPrecision(6) + "," + lon.toPrecision(6);
						var precip_text = "";

						// show precipitation repsonse if the chance is greater than 0%
						if (chance > 0) {

							precip_text = "chance of " + precip + " " + chance + "%.";

						} else {

							precip_text = "with no precipitation likely.";

						}

						tweet_text = "@" + replyto + " Hi! " + locality + " " + forecast_day + ": " + summary + " High of " + high + ", " + precip_text;

						// make sure it's not more than 140 characters
						tweet_text = tweet_text.substring(0,140);

						// if there's room, add on the api.darksky.net url
						// this is based on the current t.co length (22) from 140 (118) and a space (117)
						// more info here: https://dev.twitter.com/overview/t.co
						if (tweet_text.length <= 117) {
							tweet_text = tweet_text + " " + more;
						}

						console.log("Tweet sent:", tweet_text);

						//Turn off tweets here if testing locally
						tweetThis(tweet_text, tweet.id_str);

					}

				});

			}

		});

	}

});

function extractLocation(text) {

	// This function cleans up the tweet's text to distill it into a location, if it can

	// Take any @mentions out of the text
	var location = text.replace(/@\S+/g, '');

	// Now take any #hashtags out, too
	location = location.replace(/#\S+/g, '');

	// Eventually also remove links

	return location;
}

// extract country short name (e.g. GB for Great Britain) from google geocode API result
function getCountry(addrComponents) {
    for (var i = 0; i < addrComponents.length; i++) {
        if (addrComponents[i].types[0] == "country") {
            return addrComponents[i].short_name;
        }
    }
    return false;
}

// extract locality (e.g. Minneapolis) from google geocode API result
function getLocality(addrComponents) {
    for (var i = 0; i < addrComponents.length; i++) {
        if (addrComponents[i].types[1] == "sublocality") {
            return addrComponents[i].long_name;
        } else if (addrComponents[i].types[0] == "locality") {
			return addrComponents[i].short_name;
		}
    }
    // This replaces a blank locality in the tweet. So instead of "Minneapolis Friday"
	// tweet will say "For Friday"
    return "For";
}

// the tweeting function
function tweetThis(text, id) {

	Bot.post('statuses/update', {
		status: text,
		in_reply_to_status_id: id
		}, function(err, data, response) {
			/// console.log(data);
	});

}<|endoftext|>


<commit_before>var path = require("path");
var assert = require("assert");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var local = path.join.bind(path, __dirname);

describe("Clone", function() {
  var Repository = require(local("../../lib/repository"));
  var Clone = require(local("../../lib/clone"));
  var NodeGit = require(local("../../"));

  var clonePath = local("../repos/clone");

  var sshPublicKey = local("../id_rsa.pub");
  var sshPrivateKey = local("../id_rsa");

  // Set a reasonable timeout here now that our repository has grown.
  this.timeout(30000);

  beforeEach(function() {
    return fse.remove(clonePath).catch(function(err) {
      console.log(err);

      throw err;
    });
  });

  afterEach(function(done) {
    if (this.repository) {
      this.repository.stateCleanup();
      this.repository.free();
      delete this.repository;
    }

    process.nextTick(function() {
      global.gc();
      done();
    });
  });

  it.skip("can clone with http", function() {
    var test = this;
    var url = "http://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    return Clone.clone(url, clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with https", function() {
    var test = this;
    var url = "https://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    return Clone.clone(url, clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with ssh", function() {
    var test = this;
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        },
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    return Clone.clone(url, clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with ssh while manually loading a key", function() {
    var test = this;
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        },
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyNew(
            userName,
            sshPublicKey,
            sshPrivateKey,
            "");
        }
      }
    };

    return Clone.clone(url, clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    return Clone.clone(url, clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
    });
  });

  it("can clone with filesystem", function() {
    var test = this;
    var prefix = process.platform === "win32" ? "" : "file://";
    var url = prefix + local("../repos/empty");

    return Clone.clone(url, clonePath).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("will not segfault when accessing a url without username", function() {
    var url = "https://github.com/nodegit/private";

    return Clone.clone(url, clonePath, {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        },
        credentials: function() {
          return NodeGit.Cred.userpassPlaintextNew("fake-token",
            "x-oauth-basic");
        }
      }
    }).catch(function unhandledError() { });
  });
});
<commit_msg>Add unique directories to each clone test<commit_after>var path = require("path");
var assert = require("assert");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var local = path.join.bind(path, __dirname);

describe("Clone", function() {
  var Repository = require(local("../../lib/repository"));
  var Clone = require(local("../../lib/clone"));
  var NodeGit = require(local("../../"));

  var clonePath = local("../repos/clone");

  var sshPublicKey = local("../id_rsa.pub");
  var sshPrivateKey = local("../id_rsa");

  // Set a reasonable timeout here now that our repository has grown.
  this.timeout(30000);

  beforeEach(function() {
    return fse.remove(this.clonePath).catch(function(err) {
      console.log(err);

      throw err;
    });
  });

  afterEach(function(done) {
    if (this.repository) {
      this.repository.stateCleanup();
      this.repository.free();
      delete this.repository;
    }

    process.nextTick(function() {
      global.gc();
      done();
    });
  });

  it.skip("can clone with http", function() {
    var test = this;
    var url = "http://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    test.clonePath = local("../repos/http");

    return Clone.clone(url, test.clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with https", function() {
    var test = this;
    var url = "https://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    test.clonePath = local("../repos/https");

    return Clone.clone(url, test.clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with ssh", function() {
    var test = this;
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        },
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    test.clonePath = local("../repos/ssh");

    return Clone.clone(url, test.clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with ssh while manually loading a key", function() {
    var test = this;
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        },
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyNew(
            userName,
            sshPublicKey,
            sshPrivateKey,
            "");
        }
      }
    };

    test.clonePath = local("../repos/sshManual");

    return Clone.clone(url, test.clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    test.clonePath = local("../repos/git");

    return Clone.clone(url, test.clonePath, opts).then(function(repo) {
      assert.ok(repo instanceof Repository);
    });
  });

  it("can clone with filesystem", function() {
    var test = this;
    var prefix = process.platform === "win32" ? "" : "file://";
    var url = prefix + local("../repos/empty");

    test.clonePath = local("../repos/filesystem");

    return Clone.clone(url, test.clonePath).then(function(repo) {
      assert.ok(repo instanceof Repository);
      test.repository = repo;
    });
  });

  it("will not segfault when accessing a url without username", function() {
    var url = "https://github.com/nodegit/private";

    return Clone.clone(url, clonePath, {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        },
        credentials: function() {
          return NodeGit.Cred.userpassPlaintextNew("fake-token",
            "x-oauth-basic");
        }
      }
    }).catch(function unhandledError() { });
  });
});
<|endoftext|>


<commit_before>var path = require("path");
var assert = require("assert");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var local = path.join.bind(path, __dirname);

describe("Clone", function() {
  var Repository = require(local("../../lib/repository"));
  var Clone = require(local("../../lib/clone"));
  var NodeGit = require(local("../../"));

  var http = local("../repos/http");
  var https = local("../repos/https");
  var ssh = local("../repos/ssh");
  var sshManual = local("../repos/sshmanual");
  var git = local("../repos/git");
  var file = local("../repos/file");

  var sshPublicKey = local("../id_rsa.pub");
  var sshPrivateKey = local("../id_rsa");

  // Set a reasonable timeout here now that our repository has grown.
  this.timeout(15000);

  function prepTestAndClean(url, location, opts) {
    return fse.remove(location)
      .then(function() {
        return Clone.clone(url, location, opts);
      })
      .then(function(repo) {
        assert.ok(repo instanceof Repository);
      });
  }

  it("can clone with http", function() {
    var url = "http://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return prepTestAndClean(url, http, opts);
  });

  it("can clone with https", function() {
    var url = "https://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return prepTestAndClean(url, https, opts);
  });

  it("can clone with ssh", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    return prepTestAndClean(url, ssh, opts);
  });

  it("can clone with ssh while manually loading a key", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyNew(
            userName,
            sshPublicKey,
            sshPrivateKey,
            "");
        }
      }
    };

    return prepTestAndClean(url, sshManual, opts);
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return prepTestAndClean(url, git, opts);
  });

  it("can clone with filesystem", function() {
    var prefix = process.platform === "win32" ? "" : "file://";
    var url = prefix + local("../repos/empty");

    return prepTestAndClean(url, file);
  });
});
<commit_msg>Updated clone tests<commit_after>var path = require("path");
var assert = require("assert");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var local = path.join.bind(path, __dirname);

describe("Clone", function() {
  var Repository = require(local("../../lib/repository"));
  var Clone = require(local("../../lib/clone"));
  var NodeGit = require(local("../../"));

  var http = local("../repos/http");
  var https = local("../repos/https");
  var ssh = local("../repos/ssh");
  var sshManual = local("../repos/sshmanual");
  var git = local("../repos/git");
  var file = local("../repos/file");

  var sshPublicKey = local("../id_rsa.pub");
  var sshPrivateKey = local("../id_rsa");

  // Set a reasonable timeout here now that our repository has grown.
  this.timeout(15000);

  function prepTestAndClean(url, location, opts) {
    return fse.remove(location)
      .then(function() {
        return Clone.clone(url, location, opts);
      })
      .then(function(repo) {
        assert.ok(repo instanceof Repository);
      });
  }

  it.skip("can clone with http", function() {
    var url = "http://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    return prepTestAndClean(url, http, opts);
  });

  it.only("can clone with https", function() {
    var url = "https://github.com/nodegit/test.git";
    var opts = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    return prepTestAndClean(url, https, opts);
  });

  it("can clone with ssh", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    return prepTestAndClean(url, ssh, opts);
  });

  it("can clone with ssh while manually loading a key", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyNew(
            userName,
            sshPublicKey,
            sshPrivateKey,
            "");
        }
      }
    };

    return prepTestAndClean(url, sshManual, opts);
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return prepTestAndClean(url, git, opts);
  });

  it("can clone with filesystem", function() {
    var prefix = process.platform === "win32" ? "" : "file://";
    var url = prefix + local("../repos/empty");

    return prepTestAndClean(url, file);
  });
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function() {
  'use strict';

  Polymer({
    is: 'gr-external-style',
    _legacyUndefinedCheck: true,

    properties: {
      name: String,
      _urlsImported: {
        type: Array,
        value() { return []; },
      },
      _stylesApplied: {
        type: Array,
        value() { return []; },
      },
    },

    /**
     * @suppress {checkTypes}
     */
    _import(url) {
      if (this._urlsImported.includes(url)) { return Promise.resolve(); }
      this._urlsImported.push(url);
      return new Promise((resolve, reject) => {
        (this.importHref || Polymer.importHref)(url, resolve, reject);
      });
    },

    _applyStyle(name) {
      if (this._stylesApplied.includes(name)) { return; }
      this._stylesApplied.push(name);
      // Hybrid custom-style syntax:
      // https://polymer-library.polymer-project.org/2.0/docs/devguide/style-shadow-dom
      const s = document.createElement('style', 'custom-style');
      s.setAttribute('include', name);
      const cs = document.createElement('custom-style');
      cs.appendChild(s);
      // When using Shadow DOM <custom-style> must be added to the <body>.
      // Within <gr-external-style> itself the styles would have no effect.
      const topEl = document.getElementsByTagName('body')[0];
      topEl.insertBefore(cs, topEl.firstChild);
    },

    _importAndApply() {
      Promise.all(Gerrit._endpoints.getPlugins(this.name).map(
          pluginUrl => this._import(pluginUrl))
      ).then(() => {
        const moduleNames = Gerrit._endpoints.getModules(this.name);
        for (const name of moduleNames) {
          this._applyStyle(name);
        }
      });
    },

    attached() {
      this._importAndApply();
    },

    ready() {
      Gerrit.awaitPluginsLoaded().then(() => this._importAndApply());
    },
  });
})();
<commit_msg>Fix for external styles in Polymer 2<commit_after>/**
 * @license
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function() {
  'use strict';

  Polymer({
    is: 'gr-external-style',
    _legacyUndefinedCheck: true,

    properties: {
      name: String,
      _urlsImported: {
        type: Array,
        value() { return []; },
      },
      _stylesApplied: {
        type: Array,
        value() { return []; },
      },
    },

    /**
     * @suppress {checkTypes}
     */
    _import(url) {
      if (this._urlsImported.includes(url)) { return Promise.resolve(); }
      this._urlsImported.push(url);
      return new Promise((resolve, reject) => {
        (this.importHref || Polymer.importHref)(url, resolve, reject);
      });
    },

    _applyStyle(name) {
      if (this._stylesApplied.includes(name)) { return; }
      this._stylesApplied.push(name);
      // Hybrid custom-style syntax:
      // https://polymer-library.polymer-project.org/2.0/docs/devguide/style-shadow-dom
      const s = document.createElement('style', 'custom-style');
      s.setAttribute('include', name);
      const cs = document.createElement('custom-style');
      cs.appendChild(s);
      // When using Shadow DOM <custom-style> must be added to the <body>.
      // Within <gr-external-style> itself the styles would have no effect.
      const topEl = document.getElementsByTagName('body')[0];
      topEl.insertBefore(cs, topEl.firstChild);
      Polymer.updateStyles();
    },

    _importAndApply() {
      Promise.all(Gerrit._endpoints.getPlugins(this.name).map(
          pluginUrl => this._import(pluginUrl))
      ).then(() => {
        const moduleNames = Gerrit._endpoints.getModules(this.name);
        for (const name of moduleNames) {
          this._applyStyle(name);
        }
      });
    },

    attached() {
      this._importAndApply();
    },

    ready() {
      Gerrit.awaitPluginsLoaded().then(() => this._importAndApply());
    },
  });
})();
<|endoftext|>


<commit_before>define(
		[
				'angular',
				'/camunda/api/tasklist/plugin/process-tree-plugin/static/lib/jstree.js',
				'/camunda/api/tasklist/plugin/process-tree-plugin/static/lib/ngJsTree.js',
				'/camunda/api/tasklist/plugin/process-tree-plugin/static/app/treeService.js' ],

		function(angular, jstree, ngJsTree, treeService) {

			var ngModule = angular.module(
					'tasklist.plugin.process-tree-plugin', [ 'ngJsTree',
							'treeService' ]);

			var Controller = [
					'$scope',
					'$modal',
					'$http',
					'camAPI',
					'dataDepend',
					'treeService',
					function($scope, $modal, $http, camAPI, dataDepend,
							treeService) {

						// TODO passing correct id here:
						$scope.treeData = treeService.treeDataById('xxx');

						var ProcessDefinition = camAPI
								.resource('process-definition');

						var diagramData = $scope.taskData.newChild($scope);

						diagramData.observe('processDefinition', function(
								processDefinition) {
							$scope.processDefinition = processDefinition;

							ProcessDefinition.xml(processDefinition, function(
									err, res) {
								if (err) {
									throw err;
								} else {
									$scope.processXml = res.bpmn20Xml;
								}
							});
						});

						$scope.readyCB = function() {
					        console.log('ready called');
					    };

					    $scope.selectNodeCB = function(node, selected, event) {
					    	console.log('selectNodeCB called');
					    	console.log(node);
					    	console.log(selected);
					    };

					} ];

			var Configuration = function PluginConfiguration(ViewsProvider) {

				ViewsProvider
						.registerDefaultView(
								'tasklist.task.detail',
								{
									id : 'tasklist-plugin',
									label : 'Process Tree',
									// url :
									// 'plugin://process-tree-plugin/static/app/test.html',
									url : 'tasklistbase://../../api/tasklist/plugin/process-tree-plugin/static/app/test.html',
									controller : Controller,
									priority : 200
								});
			};

			Configuration.$inject = [ 'ViewsProvider' ];

			ngModule.config(Configuration);
			ngModule.controller(Controller);

			return ngModule;
		});
<commit_msg>cosmetic change in loading of url. 	<commit_after>define(
		[
				'angular',
				'/camunda/api/tasklist/plugin/process-tree-plugin/static/lib/jstree.js',
				'/camunda/api/tasklist/plugin/process-tree-plugin/static/lib/ngJsTree.js',
				'/camunda/api/tasklist/plugin/process-tree-plugin/static/app/treeService.js' ],

		function(angular, jstree, ngJsTree, treeService) {

			var ngModule = angular.module(
					'tasklist.plugin.process-tree-plugin', [ 'ngJsTree',
							'treeService' ]);

			var Controller = [
					'$scope',
					'$modal',
					'$http',
					'camAPI',
					'dataDepend',
					'treeService',
					function($scope, $modal, $http, camAPI, dataDepend,
							treeService) {

						// TODO passing correct id here:
						$scope.treeData = treeService.treeDataById('xxx');

						var ProcessDefinition = camAPI
								.resource('process-definition');

						var diagramData = $scope.taskData.newChild($scope);

						diagramData.observe('processDefinition', function(
								processDefinition) {
							$scope.processDefinition = processDefinition;

							ProcessDefinition.xml(processDefinition, function(
									err, res) {
								if (err) {
									throw err;
								} else {
									$scope.processXml = res.bpmn20Xml;
								}
							});
						});

						$scope.readyCB = function() {
					        console.log('ready called');
					    };

					    $scope.selectNodeCB = function(node, selected, event) {
					    	console.log('selectNodeCB called');
					    	console.log(node);
					    	console.log(selected);
					    };

					} ];

			var Configuration = function PluginConfiguration(ViewsProvider) {

				ViewsProvider
						.registerDefaultView(
								'tasklist.task.detail',
								{
									id : 'tasklist-plugin',
									label : 'Process Tree',
									url: '/camunda/api/tasklist/plugin/process-tree-plugin/static/app/test.html',
									controller : Controller,
									priority : 200
								});
			};

			Configuration.$inject = [ 'ViewsProvider' ];

			ngModule.config(Configuration);
			ngModule.controller(Controller);

			return ngModule;
		});
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const fs = require('mz/fs');
const path = require('path');
const Koa = require('koa');
const _ = require('koa-route');
const serve = require('koa-static');
const mount = require('koa-mount');

const app = new Koa();
const root = path.dirname(path.dirname(__dirname));

async function getTree(fsPath, level) {
	const element = path.basename(fsPath);
	const stat = await fs.stat(fsPath);

	if (!stat.isDirectory() || element === '.git' || element === '.build' || level >= 4) {
		return { element };
	}

	const childNames = await fs.readdir(fsPath);
	const children = await Promise.all(childNames.map(async childName => await getTree(path.join(fsPath, childName), level + 1)));
	return { element, collapsible: true, collapsed: false, children };
}

app.use(serve('public'));
app.use(mount('/static', serve('../../out')));
app.use(_.get('/api/ls', async ctx => {
	const relativePath = ctx.query.path;
	const absolutePath = path.join(root, relativePath);

	ctx.body = await getTree(absolutePath, 0);
}))

app.listen(3000);
console.log('http://localhost:3000');<commit_msg>tree test<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const fs = require('mz/fs');
const path = require('path');
const Koa = require('koa');
const _ = require('koa-route');
const serve = require('koa-static');
const mount = require('koa-mount');

const app = new Koa();
const root = path.dirname(path.dirname(__dirname));

async function getTree(fsPath, level) {
	const element = path.basename(fsPath);
	const stat = await fs.stat(fsPath);

	if (!stat.isDirectory() || element === '.git' || element === '.build' || level >= 5) {
		return { element };
	}

	const childNames = await fs.readdir(fsPath);
	const children = await Promise.all(childNames.map(async childName => await getTree(path.join(fsPath, childName), level + 1)));
	return { element, collapsible: true, collapsed: false, children };
}

app.use(serve('public'));
app.use(mount('/static', serve('../../out')));
app.use(_.get('/api/ls', async ctx => {
	const relativePath = ctx.query.path;
	const absolutePath = path.join(root, relativePath);

	ctx.body = await getTree(absolutePath, 0);
}))

app.listen(3000);
console.log('http://localhost:3000');<|endoftext|>