<commit_before>/* jshint node:true */

// Basic tests

var _ = require('underscore');

var suite = Object.create(require('./lib/superSuite.js'));

module.exports = _.extend(suite, {

  // Test basic messaging, to and from client
  messageBasics: function(test) {

    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      messages: {
        dog: function(arg, user) {
          test.equals(arg.foo, 123);
          user.message('cat', {bar: 456});
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.message('dog', {foo: 123});
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test that the server can handle two clients
  // and send messages to the right one
  twoClients: function(test) {

    test.expect(4);

    var server = this.server;
    var client1 = suite.createClient();
    var client2 = suite.createClient();

    var doneCount = 0;

    server.configure({
      port: this.port,
      messages: {
        dog1: function(arg, user) {
          test.ok(true, 'received message from client 1');
          user.message('cat', {bar: 456});
        },
        dog2: function(arg, user) {
          test.ok(true, 'received message from client 2');
          user.message('cat', {bar: 789});
        }
      }
    });

    client1.configure({
      serverEvents: {
        begin: function() {
          client1.message('dog1');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    client2.configure({
      serverEvents: {
        begin: function() {
          client2.message('dog2');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 789);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  // Test the autoCreateRooms server option with
  // minRoomMembers set to 2
  autoCreateRooms: function(test) {

    var server = this.server;
    var client1 = suite.createClient();
    var client2 = suite.createClient();

    var steps = [
      'joined Lobby',
      'joined Lobby',
      'joined Room 1',
      'joined Room 1',
      'leave room',
      'joined Lobby',
      'joined Lobby',
    ];

    test.expect(steps.length);

    function step(actual) {
      var expected = steps.shift();
      test.equals(actual, expected);
      if (steps.length === 0) {
        test.done();
      }
    }

    function joinRoomHandler(room) {
      step('joined '+ room.name);
      if (steps[0] === 'leave room') {
        step('leave room');
        client1.leaveRoom();
      }
    }

    server.configure({
      port: this.port,
      autoCreateRooms: true,
      minRoomMembers: 2
    });

    client1.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    client2.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  // Test the ability of a client to automatically
  // reconnect and resume after disconnection
  resume: function(test) {

    test.expect(1);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test as many server events as possible; right now
  // a few still need to be added because it's trickier
  // to test those ones.
  serverEvents: function(test) {

    test.expect(6);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        connecting: function() {
          test.ok(true, 'connecting event happened');
        },
        connect: function() {
          test.ok(true, 'connect event happened');
        },
        begin: function() {
          test.ok(true, 'begin event happened');
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test that users are pruned if reconnectWait is set
  reconnectWait: function(test) {

    test.expect(4);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      gameLoopSpeed: 100,
      reconnectWait: 200
    });

    client.configure({
      serverEvents: {
        begin: function() {
          setTimeout(function() {
            test.equals(server.userCount(), 1);
            client.end();
            test.equals(server.userCount(), 1);
          }, 200);

          setTimeout(function() {
            test.equals(server.userCount(), 1);
          }, 300);

          setTimeout(function() {
            test.equals(server.userCount(), 0);
            test.done();
          }, 500);
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test that users are pruned if reconnectWaitRoomless is set
  reconnectWaitRoomless: function(test) {

    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      autoJoinLobby: false,
      minRoomMembers: null,
      gameLoopSpeed: 10,
      reconnectWait: null,
      reconnectWaitRoomless: 50
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var user = server.getUsers()[0];
          var room = server.createRoom();

          user.enterRoom(room);
          client.end();

          setTimeout(function() {
            test.equals(server.userCount(), 1);
            user.leaveRoom();
          }, 100);

          setTimeout(function() {
            test.equals(server.userCount(), 0);
            test.done();
          }, 120);

        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test create and delete room functions.
  createAndDeleteRooms: function(test) {
    test.expect(3);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var user = server.getUsers()[0];
          var room = server.createRoom('123');
          test.ok(server.getRoom(room.id), 'room exists');
          test.ok(room.name === '123', 'room name is correct');
          server.deleteRoom(room);
          test.equals(server.getRoom(room.id), false);
          test.done();
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test the client-side listRooms function
  listRooms: function(test) {
    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.listRooms(function(rooms) {
            test.equals(rooms.length, 0);
            server.createRoom('123');
            server.createRoom('456');
            server.createRoom('789');
            client.listRooms(function(rooms) {
              test.equals(rooms.length, 3);
              test.done();
            });
          });

        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test server exception handling
  serverError: function(test) {
    test.expect(1);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      messages: {
        error: function() {
          this.foo.bar = true; // throw a dang error
        },
        afterError: function() {
          // if we got here, the server didn't crash! yay!
          test.ok(true);
          test.done();
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.message('error');
          client.message('afterError');
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  shouldAllowUser: function(test) {
    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      messages: {},
      room: {
        shouldAllowUser: function(user) {
          return this.name === 'Let me in!';
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var user = server.getUsers()[0];
          var room1 = server.createRoom('Not allowed!');
          var room2 = server.createRoom('Let me in!');
          test.equals(room1.addMember(user), false);
          test.equals(room2.addMember(user), true);
          test.done();
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test Room module emitEvent does emit event.
  _emitEvent: function(test) {
    test.expect(1);

    var server = this.server;
    var client = suite.createClient();
    var eventCount = 0;
    var incrementCount = function() {
      eventCount += 1;
    };
    server.configure({
      port: this.port,
      room: {
        init: function() {
          incrementCount();
        },
        pulse: function() {
          incrementCount();
        },
        newMember: function() {
          incrementCount();
        },
        memberLeaves: function() {
          incrementCount();
        },
        close: function() {
          incrementCount();
        },
        shouldAllowUser: function() {
          incrementCount();
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var room = server.createRoom('123');
          room._emitEvent('pulse', this);
          room._emitEvent('newMember', this);
          room._emitEvent('memberLeaves', this);
          room._emitEvent('close', this);
          room._emitEvent('shouldAllowUser', this);
          test.equals(eventCount, 6);
          test.done();
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test Rooms module emitEvent passes correct context and args.
  _emitEventContext: function(test) {
    test.expect(3);

    var server = this.server;
    var client = suite.createClient();
    var stubContext = {
      cloakIsCool: true
    };
    server.configure({
      port: this.port,
      room: {
        pulse: function(arg1, arg2) {
          test.equals(this, stubContext);
          test.equals(arg1, 123);
          test.equals(arg2, 321);
          test.done();
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var room = server.createRoom('123');
          room._emitEvent('pulse', stubContext, [123, 321]);
        }
      }
    });
    server.run();
    client.run(this.host);
  }

});<commit_msg>Adds passing test for deleteUser server method and connected client method.<commit_after>/* jshint node:true */

// Basic tests

var _ = require('underscore');

var suite = Object.create(require('./lib/superSuite.js'));

module.exports = _.extend(suite, {

  // Test basic messaging, to and from client
  messageBasics: function(test) {

    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      messages: {
        dog: function(arg, user) {
          test.equals(arg.foo, 123);
          user.message('cat', {bar: 456});
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.message('dog', {foo: 123});
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test that the server can handle two clients
  // and send messages to the right one
  twoClients: function(test) {

    test.expect(4);

    var server = this.server;
    var client1 = suite.createClient();
    var client2 = suite.createClient();

    var doneCount = 0;

    server.configure({
      port: this.port,
      messages: {
        dog1: function(arg, user) {
          test.ok(true, 'received message from client 1');
          user.message('cat', {bar: 456});
        },
        dog2: function(arg, user) {
          test.ok(true, 'received message from client 2');
          user.message('cat', {bar: 789});
        }
      }
    });

    client1.configure({
      serverEvents: {
        begin: function() {
          client1.message('dog1');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    client2.configure({
      serverEvents: {
        begin: function() {
          client2.message('dog2');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 789);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  // Test the autoCreateRooms server option with
  // minRoomMembers set to 2
  autoCreateRooms: function(test) {

    var server = this.server;
    var client1 = suite.createClient();
    var client2 = suite.createClient();

    var steps = [
      'joined Lobby',
      'joined Lobby',
      'joined Room 1',
      'joined Room 1',
      'leave room',
      'joined Lobby',
      'joined Lobby',
    ];

    test.expect(steps.length);

    function step(actual) {
      var expected = steps.shift();
      test.equals(actual, expected);
      if (steps.length === 0) {
        test.done();
      }
    }

    function joinRoomHandler(room) {
      step('joined '+ room.name);
      if (steps[0] === 'leave room') {
        step('leave room');
        client1.leaveRoom();
      }
    }

    server.configure({
      port: this.port,
      autoCreateRooms: true,
      minRoomMembers: 2
    });

    client1.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    client2.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  // Test the ability of a client to automatically
  // reconnect and resume after disconnection
  resume: function(test) {

    test.expect(1);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test as many server events as possible; right now
  // a few still need to be added because it's trickier
  // to test those ones.
  serverEvents: function(test) {

    test.expect(6);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        connecting: function() {
          test.ok(true, 'connecting event happened');
        },
        connect: function() {
          test.ok(true, 'connect event happened');
        },
        begin: function() {
          test.ok(true, 'begin event happened');
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test that users are pruned if reconnectWait is set
  reconnectWait: function(test) {

    test.expect(4);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      gameLoopSpeed: 100,
      reconnectWait: 200
    });

    client.configure({
      serverEvents: {
        begin: function() {
          setTimeout(function() {
            test.equals(server.userCount(), 1);
            client.end();
            test.equals(server.userCount(), 1);
          }, 200);

          setTimeout(function() {
            test.equals(server.userCount(), 1);
          }, 300);

          setTimeout(function() {
            test.equals(server.userCount(), 0);
            test.done();
          }, 500);
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test that users are pruned if reconnectWaitRoomless is set
  reconnectWaitRoomless: function(test) {

    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      autoJoinLobby: false,
      minRoomMembers: null,
      gameLoopSpeed: 10,
      reconnectWait: null,
      reconnectWaitRoomless: 50
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var user = server.getUsers()[0];
          var room = server.createRoom();

          user.enterRoom(room);
          client.end();

          setTimeout(function() {
            test.equals(server.userCount(), 1);
            user.leaveRoom();
          }, 100);

          setTimeout(function() {
            test.equals(server.userCount(), 0);
            test.done();
          }, 120);

        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test create and delete room functions.
  createAndDeleteRooms: function(test) {
    test.expect(3);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var user = server.getUsers()[0];
          var room = server.createRoom('123');
          test.ok(server.getRoom(room.id), 'room exists');
          test.ok(room.name === '123', 'room name is correct');
          server.deleteRoom(room);
          test.equals(server.getRoom(room.id), false);
          test.done();
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test the client-side listRooms function
  listRooms: function(test) {
    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.listRooms(function(rooms) {
            test.equals(rooms.length, 0);
            server.createRoom('123');
            server.createRoom('456');
            server.createRoom('789');
            client.listRooms(function(rooms) {
              test.equals(rooms.length, 3);
              test.done();
            });
          });

        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test server exception handling
  serverError: function(test) {
    test.expect(1);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      messages: {
        error: function() {
          this.foo.bar = true; // throw a dang error
        },
        afterError: function() {
          // if we got here, the server didn't crash! yay!
          test.ok(true);
          test.done();
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.message('error');
          client.message('afterError');
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  shouldAllowUser: function(test) {
    test.expect(2);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port,
      messages: {},
      room: {
        shouldAllowUser: function(user) {
          return this.name === 'Let me in!';
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var user = server.getUsers()[0];
          var room1 = server.createRoom('Not allowed!');
          var room2 = server.createRoom('Let me in!');
          test.equals(room1.addMember(user), false);
          test.equals(room2.addMember(user), true);
          test.done();
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test deleteUser in conjunction with connected client method.
  deleteUser: function(test) {
    test.expect(4);

    var server = this.server;
    var client = suite.createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          test.equals(server.getUsers().length, 1);
          test.equals(client.connected(), true);
          server.deleteUser(server.getUsers()[0]);
          test.equals(server.getUsers().length, 0);
          setTimeout(function() {
            test.equals(client.connected(), false);
            test.done();
          }, 50)
        }
      }
    });

    server.run();
    client.run(this.host);
  },

  // Test Room module emitEvent does emit event.
  _emitEvent: function(test) {
    test.expect(1);

    var server = this.server;
    var client = suite.createClient();
    var eventCount = 0;
    var incrementCount = function() {
      eventCount += 1;
    };
    server.configure({
      port: this.port,
      room: {
        init: function() {
          incrementCount();
        },
        pulse: function() {
          incrementCount();
        },
        newMember: function() {
          incrementCount();
        },
        memberLeaves: function() {
          incrementCount();
        },
        close: function() {
          incrementCount();
        },
        shouldAllowUser: function() {
          incrementCount();
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var room = server.createRoom('123');
          room._emitEvent('pulse', this);
          room._emitEvent('newMember', this);
          room._emitEvent('memberLeaves', this);
          room._emitEvent('close', this);
          room._emitEvent('shouldAllowUser', this);
          test.equals(eventCount, 6);
          test.done();
        }
      }
    });
    server.run();
    client.run(this.host);
  },

  // Test Rooms module emitEvent passes correct context and args.
  _emitEventContext: function(test) {
    test.expect(3);

    var server = this.server;
    var client = suite.createClient();
    var stubContext = {
      cloakIsCool: true
    };
    server.configure({
      port: this.port,
      room: {
        pulse: function(arg1, arg2) {
          test.equals(this, stubContext);
          test.equals(arg1, 123);
          test.equals(arg2, 321);
          test.done();
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          var room = server.createRoom('123');
          room._emitEvent('pulse', stubContext, [123, 321]);
        }
      }
    });
    server.run();
    client.run(this.host);
  }

});<|endoftext|>


<commit_before>var fs = require('fs');
var Coinigy = require('../dist/index');
var config = JSON.parse(fs.readFileSync('./test-config.json', 'utf8'));
var coinigy = new Coinigy(config.apiKey, config.apiSecret);
var chai = require('chai');
chai.should();

describe('Coinigy API', function () {
  //userInfo
  describe('userInfo', function () {
    it('should return many keys', function () {
      return coinigy.userInfo()
      .then(function (b) {
        b.should.have.all.keys('data', 'notifications');
      })
      .catch(function (err) {
        should.not.exist(err);
      });
    });
  });

  //activity log
  describe('activity', function () {
    it('should return many keys', function () {
      return coinigy.activity()
      .then(function (b) {
        b.should.have.all.keys('data', 'notifications');
      })
      .catch(function (err) {
        should.not.exist(err);
      });
    });
  });

});
<commit_msg>added a few tests<commit_after>var fs = require('fs');
var Coinigy = require('../dist/index');
var config = JSON.parse(fs.readFileSync('./test-config.json', 'utf8'));
var coinigy = new Coinigy(config.apiKey, config.apiSecret);
var chai = require('chai');
chai.should();

describe('Coinigy API', function () {
  //userInfo
  describe('userInfo', function () {
    it('should return many keys', function () {
      return coinigy.userInfo()
      .then(function (b) {
        b.should.have.all.keys('data', 'notifications');
      })
      .catch(function (err) {
        should.not.exist(err);
      });
    });
  });

  //activity log
  describe('activity', function () {
    it('should return many keys', function () {
      return coinigy.activity()
      .then(function (b) {
        b.should.have.all.keys('data', 'notifications');
        b.open_order.should.have.all.keys('exch_name');
      })
      .catch(function (err) {
        should.not.exist(err);
      });
    });
  });
  describe('accounts', function () {
    it('lists all accounts', function () {
      return coinigy.accounts()
      .then(function (b) {
        b.should.have.all.keys('data', 'notifications');
        should.not.exist(b.notifications);
        //b.open_order.should.have.all.keys('exch_name');
      })
      .catch(function (err) {
        should.not.exist(err);
      });
    });
  });
  describe('balances', function () {
    it('lists all account balance', function () {
      return coinigy.balances()
      .then(function (b) {
        b.should.have.all.keys('data', 'notifications');
        should.not.exist(b.notifications);
        //b.open_order.should.have.all.keys('exch_name');
      })
      .catch(function (err) {
        should.not.exist(err);
      });
    });
  });
  describe('orders', function () {
    it('lists all orders', function () {
      return coinigy.orders()
      .then(function (b) {
        b.should.have.all.keys('data', 'notifications');
        should.not.exist(b.notifications);
        //b.open_order.should.have.all.keys('exch_name');
      })
      .catch(function (err) {
        should.not.exist(err);
      });
    });
  });
  //How do I test post with a specific body? IE: auth_ids = 1234 in post for Refresh Balance
  //http://docs.coinigy.apiary.io/#reference/account-functions/refresh-balance/refreshbalance
});
<|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';
import numeral from 'numeral';
import moment from 'moment';

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/**
 * @class CurrencyPairs
 * @extends {React.Component}
 */
class CurrencyPairs extends React.Component {

  /**
   * Renders an individual trade in blotter
   * @param {Object} trade
   * @returns {HTMLElement.TR}
   */
  renderRow(trade){
    const notional           = numeral(trade.amount).format('0,000,000[.]00') + ' ' + trade.pair.substr(0, 3),
          dateTime           = moment(trade.dateTime).format('MMM Do, HH:mm:ss'),
          valueDay           = new Date(trade.valueDate),
          formattedValueDate = ['SP.', valueDay.getDate(), MONTHS[valueDay.getMonth()]].join(' ');

    return (

        {trade.id}

{dateTime}

        {trade.direction}
        {trade.pair}
        {notional}
        {trade.rate}
        {trade.status}
        {formattedValueDate}
        {trade.trader}

    );
  }

  render(){
    return

          Id
          Date
          Dir.
          CCY
          Notional
          Rate
          Status
          Value date
          Trader

        {this.props.trades.map(this.renderRow)}

;
  }
}

export default CurrencyPairs;
<commit_msg>fixed NaN value date bug on ios<commit_after>import React from 'react';
import _ from 'lodash';
import numeral from 'numeral';
import moment from 'moment';

/**
 * @class CurrencyPairs
 * @extends {React.Component}
 */
class CurrencyPairs extends React.Component {

  /**
   * Renders an individual trade in blotter
   * @param {Object} trade
   * @returns {HTMLElement.TR}
   */
  renderRow(trade){
    const notional           = numeral(trade.amount).format('0,000,000[.]00') + ' ' + trade.pair.substr(0, 3),
          dateTime           = moment(trade.dateTime).format('MMM Do, HH:mm:ss'),
          valueDay           = moment(trade.valueDate),
          formattedValueDate = ['SP.', valueDay.format('DD MMM')].join(' ');

    console.log(trade.valueDate);

    return (

        {trade.id}

{dateTime}

        {trade.direction}
        {trade.pair}
        {notional}
        {trade.rate}
        {trade.status}
        {formattedValueDate}
        {trade.trader}

    );
  }

  render(){
    return

          Id
          Date
          Dir.
          CCY
          Notional
          Rate
          Status
          Value date
          Trader

        {this.props.trades.map(this.renderRow)}

;
  }
}

export default CurrencyPairs;
<|endoftext|>


<commit_before>if (typeof module === 'object') require('./setup');

testSuite('NProgress', function() {

  afterEach(function() {
    $("#nprogress").remove();
    $('html').attr('class', '');
    NProgress.status = null;
  });

  describe('.set()', function() {
    it('.set(0) must render', function(done) {
      NProgress.set(0);
      assert.equal($("#nprogress").length, 1);
      assert.equal($("#nprogress .bar").length, 1);
      assert.equal($("#nprogress .peg").length, 1);
      assert.equal($("#nprogress .spinner").length, 1);
      done();
    });

    it('.set(1) should appear and disappear', function(done) {
      NProgress.configure({ speed: 10 });
      NProgress.set(0).set(1);
      assert.equal($("#nprogress").length, 1);

      setTimeout(function() {
        assert.equal($("#nprogress").length, 0);
        done();
      }, 70);
    });

    it('must respect minimum', function() {
      NProgress.set(0);
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });

    it('must clamp to minimum', function() {
      NProgress.set(-100);
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });

    it('must clamp to maximum', function() {
      NProgress.set(456);
      assert.equal(NProgress.status, null);
    });
  });

  // ----

  describe('.start()', function() {
    it('must render', function(done) {
      NProgress.start();
      assert.equal($("#nprogress").length, 1);
      done();
    });

    it('must respect minimum', function() {
      NProgress.start();
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });
  });

  // ----

  describe('.done()', function() {
    it('must not render without start', function(done) {
      NProgress.done();
      assert.equal($("#nprogress").length, 0);
      done();
    });

    it('.done(true) must render', function(done) {
      NProgress.done(true);
      assert.equal($("#nprogress").length, 1);
      done();
    });
  });

  // ----

  describe('.inc()', function() {
    it('should render', function() {
      NProgress.inc();
      assert.equal($("#nprogress").length, 1);
    });

    it('should start with minimum', function() {
      NProgress.inc();
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });

    it('should increment', function() {
      NProgress.start();
      var start = NProgress.status;

      NProgress.inc();
      assert.operator(NProgress.status, '>', start);
    });

    it('should never reach 1.0', function() {
      for (var i=0; i<100; ++i) { NProgress.inc(); }
      assert.operator(NProgress.status, '<', 1.0);
    });
  });

  // -----

  describe('.configure()', function() {
    it('should work', function() {
      NProgress.configure({ minimum: 0.5 });
      assert.equal(NProgress.settings.minimum, 0.5);
    });
  });
});
<commit_msg>Add tests for showSpinner. (See #9)<commit_after>if (typeof module === 'object') require('./setup');

testSuite('NProgress', function() {

  beforeEach(function() {
    this.settings = $.extend({}, NProgress.settings);
  });

  afterEach(function() {
    $("#nprogress").remove();
    $('html').attr('class', '');
    NProgress.status = null;

    // Restore settings
    $.extend(NProgress.settings, this.settings);
  });

  describe('.set()', function() {
    it('.set(0) must render', function(done) {
      NProgress.set(0);
      assert.equal($("#nprogress").length, 1);
      assert.equal($("#nprogress .bar").length, 1);
      assert.equal($("#nprogress .peg").length, 1);
      assert.equal($("#nprogress .spinner").length, 1);
      done();
    });

    it('.set(1) should appear and disappear', function(done) {
      NProgress.configure({ speed: 10 });
      NProgress.set(0).set(1);
      assert.equal($("#nprogress").length, 1);

      setTimeout(function() {
        assert.equal($("#nprogress").length, 0);
        done();
      }, 70);
    });

    it('must respect minimum', function() {
      NProgress.set(0);
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });

    it('must clamp to minimum', function() {
      NProgress.set(-100);
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });

    it('must clamp to maximum', function() {
      NProgress.set(456);
      assert.equal(NProgress.status, null);
    });
  });

  // ----

  describe('.start()', function() {
    it('must render', function(done) {
      NProgress.start();
      assert.equal($("#nprogress").length, 1);
      done();
    });

    it('must respect minimum', function() {
      NProgress.start();
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });
  });

  // ----

  describe('.done()', function() {
    it('must not render without start', function(done) {
      NProgress.done();
      assert.equal($("#nprogress").length, 0);
      done();
    });

    it('.done(true) must render', function(done) {
      NProgress.done(true);
      assert.equal($("#nprogress").length, 1);
      done();
    });
  });

  // ----

  describe('.inc()', function() {
    it('should render', function() {
      NProgress.inc();
      assert.equal($("#nprogress").length, 1);
    });

    it('should start with minimum', function() {
      NProgress.inc();
      assert.equal(NProgress.status, NProgress.settings.minimum);
    });

    it('should increment', function() {
      NProgress.start();
      var start = NProgress.status;

      NProgress.inc();
      assert.operator(NProgress.status, '>', start);
    });

    it('should never reach 1.0', function() {
      for (var i=0; i<100; ++i) { NProgress.inc(); }
      assert.operator(NProgress.status, '<', 1.0);
    });
  });

  // -----

  describe('.configure()', function() {
    it('should work', function() {
      NProgress.configure({ minimum: 0.5 });
      assert.equal(NProgress.settings.minimum, 0.5);
    });
  });

  // ----

  describe('.configure(showSpinner)', function() {
    it('should render spinner by default', function() {
      NProgress.start();

      assert.equal($("#nprogress .spinner").length, 1);
    });

    it('should be true by default', function() {
      assert.equal(NProgress.settings.showSpinner, true);
    });

    it('should hide (on false)', function() {
      NProgress.configure({ showSpinner: false });
      NProgress.start();

      assert.equal($("#nprogress .spinner").length, 0);
    });
  });
});
<|endoftext|>


<commit_before>//Import dependencies
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var utily = require('../index.js');

//Test the fs methods
describe('utily -> fs', function()
{
  //Test checksum method
  describe('-> checksum method', function()
  {
    var file = path.join(__dirname, './fs-checksum-test.txt');
    fs.writeFileSync(file, 'Hello\nThis is the content\n', 'utf8');
    it('should generate the correct checksum of the file', function(done)
    {
      return utily.fs.checksum(file, 'md5', function(error, sum)
      {
        assert.equal(null, error);
        assert.equal('2c1b03ff58b808e5bd56196131cc8505', sum);
        done();
      });
    });
  });

  //Test copy method
  describe('-> copy method', function()
  {
    //Copy files
    it('shgould copy a file that exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      fs.writeFileSync(file_source, 'This is the content of the file 1', 'utf8');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.equal(null, error);
        var content1 = fs.readFileSync(file_source, 'utf8');
        var content2 = fs.readFileSync(file_destination, 'utf8');
        assert.equal(content1, content2);
        done();
      });
    });

    //Display an error
    it('should return an error if source file does not exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source-unexistent.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.notEqual(null, error);
        done();
      });
    });
  });

  //Test exists method
  describe('-> exists method', function()
  {
    //Folder that does not exists
    it('should return false if path does not exists', function(done)
    {
      return utily.fs.exists(path.join(__dirname, './inexistent'), function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });
    //Folder that exists
    it('should return true if path exists', function(done)
    {
      return utily.fs.exists(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });
  });

  //Test mkdir method
  describe('-> mkdir method', function()
  {
    //Create a folder
    it('should create the folders', function(done)
    {
      var folders = path.join(__dirname, './new/folders/yeah');
      return utily.fs.mkdir(folders, function(error)
      {
        assert.equal(null, error);
        assert.equal(true, fs.existsSync(folders));
        done();
      });
    });
  });

  //Test size method
  describe('-> size method', function()
  {
    //Check the file size
    it('should get the real file size', function(done)
    {
      var file = path.join(__dirname, './fs-size-test.txt');
      fs.writeFileSync(file, 'This is the content of the \nfile\n', 'utf8');
      return utily.fs.size(file, function(error, size)
      {
        assert.equal(null, error);
        assert.equal(33, size);
        done();
      });
    });
  });

  //Test unlink method
  describe('-> unlink method', function()
  {
    //Delete a list of file
    it('should delete a list of files', function(done)
    {
      var file1 = path.join(__dirname, './fs-unlink-test1.txt');
      var file2 = path.join(__dirname, './fs-unlink-test2.txt');
      fs.writeFileSync(file1, 'Test 1', 'utf8');
      fs.writeFileSync(file2, 'Test 2', 'utf8');
      return utily.fs.unlink([ file1, file2 ], function(error)
      {
        assert.equal(null, error);
        assert.equal(false, fs.existsSync(file1));
        assert.equal(false, fs.existsSync(file2));
        done();
      });
    });
  });
});

<commit_msg>test/test.js: added fs.isDir tests<commit_after>//Import dependencies
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var utily = require('../index.js');

//Test the fs methods
describe('utily -> fs', function()
{
  //Test checksum method
  describe('-> checksum method', function()
  {
    var file = path.join(__dirname, './fs-checksum-test.txt');
    fs.writeFileSync(file, 'Hello\nThis is the content\n', 'utf8');
    it('should generate the correct checksum of the file', function(done)
    {
      return utily.fs.checksum(file, 'md5', function(error, sum)
      {
        assert.equal(null, error);
        assert.equal('2c1b03ff58b808e5bd56196131cc8505', sum);
        done();
      });
    });
  });

  //Test copy method
  describe('-> copy method', function()
  {
    //Copy files
    it('shgould copy a file that exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      fs.writeFileSync(file_source, 'This is the content of the file 1', 'utf8');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.equal(null, error);
        var content1 = fs.readFileSync(file_source, 'utf8');
        var content2 = fs.readFileSync(file_destination, 'utf8');
        assert.equal(content1, content2);
        done();
      });
    });

    //Display an error
    it('should return an error if source file does not exists', function(done)
    {
      var file_source = path.join(__dirname, 'fs-copy-source-unexistent.txt');
      var file_destination = path.join(__dirname, 'fs-copy-destination.txt');
      return utily.fs.copy(file_source, file_destination, function(error)
      {
        assert.notEqual(null, error);
        done();
      });
    });
  });

  //Test exists method
  describe('-> exists method', function()
  {
    //Folder that does not exists
    it('should return false if path does not exists', function(done)
    {
      return utily.fs.exists(path.join(__dirname, './inexistent'), function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });
    //Folder that exists
    it('should return true if path exists', function(done)
    {
      return utily.fs.exists(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });
  });

  //Test isDir method
  describe('-> isDir method', function()
  {
    //Folder that exists
    it('should return that the folder path is a directory', function(done)
    {
      return utily.fs.isDir(__dirname, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(true, exists);
        done();
      });
    });

    //Path is a file
    it('should return that the file path is not a directory', function(done)
    {
      var file = path.join(__dirname, 'test.js');
      return utily.fs.isDir(file, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    });

    //Path does not exists
    it('should return that the fake path is not a directory', function(done)
    {
      var fake = path.join(__dirname, './fake/path');
      return utily.fs.isDir(fake, function(error, exists)
      {
        assert.equal(null, error);
        assert.equal(false, exists);
        done();
      });
    })
  });

  //Test mkdir method
  describe('-> mkdir method', function()
  {
    //Create a folder
    it('should create the folders', function(done)
    {
      var folders = path.join(__dirname, './new/folders/yeah');
      return utily.fs.mkdir(folders, function(error)
      {
        assert.equal(null, error);
        assert.equal(true, fs.existsSync(folders));
        done();
      });
    });
  });

  //Test size method
  describe('-> size method', function()
  {
    //Check the file size
    it('should get the real file size', function(done)
    {
      var file = path.join(__dirname, './fs-size-test.txt');
      fs.writeFileSync(file, 'This is the content of the \nfile\n', 'utf8');
      return utily.fs.size(file, function(error, size)
      {
        assert.equal(null, error);
        assert.equal(33, size);
        done();
      });
    });
  });

  //Test unlink method
  describe('-> unlink method', function()
  {
    //Delete a list of file
    it('should delete a list of files', function(done)
    {
      var file1 = path.join(__dirname, './fs-unlink-test1.txt');
      var file2 = path.join(__dirname, './fs-unlink-test2.txt');
      fs.writeFileSync(file1, 'Test 1', 'utf8');
      fs.writeFileSync(file2, 'Test 2', 'utf8');
      return utily.fs.unlink([ file1, file2 ], function(error)
      {
        assert.equal(null, error);
        assert.equal(false, fs.existsSync(file1));
        assert.equal(false, fs.existsSync(file2));
        done();
      });
    });
  });
});

<|endoftext|>


<commit_before>var assert = require('assert')
  , fs = require('fs')
  , path = require('path')
  , glob = require('glob')
  , redis = require('redis')
  , validator = require('../lib/pupa-validate')();

var messages = [
  'GET http://www.popoloproject.com/schemas/organization.json#',
  'GET http://www.popoloproject.com/schemas/other_name.json#',
  'GET http://www.popoloproject.com/schemas/identifier.json#',
  'GET http://www.popoloproject.com/schemas/area.json#',
  'GET http://www.popoloproject.com/schemas/contact_detail.json#',
  'GET http://www.popoloproject.com/schemas/link.json#',
  'GET http://www.popoloproject.com/schemas/membership.json#',
  'GET http://www.popoloproject.com/schemas/post.json#',
  'GET http://www.popoloproject.com/schemas/motion.json#',
  'GET http://www.popoloproject.com/schemas/vote_event.json#',
  'GET http://www.popoloproject.com/schemas/vote.json#',
  'GET http://www.popoloproject.com/schemas/person.json#',
  'GET http://www.popoloproject.com/schemas/group_result.json#',
  'GET http://www.popoloproject.com/schemas/count.json#',
  'GET http://www.popoloproject.com/schemas/speech.json#',

  // Filesystem
  /No _type for \{/,
  function (message) {
    var json = JSON.parse(message);
    assert.ok('uri' in json[0]);
    delete json[0].uri;
    assert.deepEqual(json, [{
      'schemaUri': 'http://www.popoloproject.com/schemas/organization.json#/properties/id'
    , 'attribute': 'type'
    , 'message': 'Instance is not a required type'
    , 'details': ['string', 'null']
    }]);
  },
  /^No _type for \{/,
  'No URL for invalid',

  // Redis
  /No _type for \{/,
  function (message) {
    var json = JSON.parse(message);
    assert.ok('uri' in json[0]);
    delete json[0].uri;
    assert.deepEqual(json, [{
      'schemaUri': 'http://www.popoloproject.com/schemas/organization.json#/properties/id'
    , 'attribute': 'type'
    , 'message': 'Instance is not a required type'
    , 'details': ['string', 'null']
    }]);
  },
  /No _type for \{/,
  'No URL for invalid',
];

function log(message) {
  // process.stdout.write('"' + message + '"\n');
  var expected = messages.shift();
  if (!expected || typeof expected === 'string') {
    assert.equal(message, expected);
  }
  else if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    assert.ok(expected.test(message));
  }
  else {
    expected(message);
  }
}

var args = ['organization', 'http://www.popoloproject.com/schemas/organization.json#']
  , directory = 'test/fixtures'
  , logger = {info: log, error: log};

validator(args, {output_dir: directory}, logger, function () {
  var client = redis.createClient(6379, '127.0.0.1');

  client.select(15, function (err, res) {
    client.flushall(function (err, res) {
      glob('*.json', {cwd: directory}, function ($, files) {
        var array = [];
        files.forEach(function (file) {
          array.push(file, fs.readFileSync(path.join(directory, file)));
        });

        client.mset(array, function (err, res) {
          client.quit();
          validator(args, {output_dir: 'redis://127.0.0.1:6379/15'}, logger, function () {
            assert.equal(messages.length, 0);
          });
        });
      });
    });
  });
});
<commit_msg>fix test<commit_after>var assert = require('assert')
  , fs = require('fs')
  , path = require('path')
  , glob = require('glob')
  , redis = require('redis')
  , validator = require('../lib/pupa-validate')();

var messages = [
  'GET http://www.popoloproject.com/schemas/organization.json#',
  'GET http://www.popoloproject.com/schemas/other_name.json#',
  'GET http://www.popoloproject.com/schemas/identifier.json#',
  'GET http://www.popoloproject.com/schemas/area.json#',
  'GET http://www.popoloproject.com/schemas/contact_detail.json#',
  'GET http://www.popoloproject.com/schemas/link.json#',
  'GET http://www.popoloproject.com/schemas/membership.json#',
  'GET http://www.popoloproject.com/schemas/post.json#',
  'GET http://www.popoloproject.com/schemas/motion.json#',
  'GET http://www.popoloproject.com/schemas/vote_event.json#',
  'GET http://www.popoloproject.com/schemas/vote.json#',
  'GET http://www.popoloproject.com/schemas/person.json#',
  'GET http://www.popoloproject.com/schemas/event.json#',
  'GET http://www.popoloproject.com/schemas/group_result.json#',
  'GET http://www.popoloproject.com/schemas/count.json#',
  'GET http://www.popoloproject.com/schemas/speech.json#',

  // Filesystem
  /No _type for \{/,
  function (message) {
    var json = JSON.parse(message);
    assert.ok('uri' in json[0]);
    delete json[0].uri;
    assert.deepEqual(json, [{
      'schemaUri': 'http://www.popoloproject.com/schemas/organization.json#/properties/id'
    , 'attribute': 'type'
    , 'message': 'Instance is not a required type'
    , 'details': ['string', 'null']
    }]);
  },
  /^No _type for \{/,
  'No URL for invalid',

  // Redis
  /No _type for \{/,
  function (message) {
    var json = JSON.parse(message);
    assert.ok('uri' in json[0]);
    delete json[0].uri;
    assert.deepEqual(json, [{
      'schemaUri': 'http://www.popoloproject.com/schemas/organization.json#/properties/id'
    , 'attribute': 'type'
    , 'message': 'Instance is not a required type'
    , 'details': ['string', 'null']
    }]);
  },
  /No _type for \{/,
  'No URL for invalid',
];

function log(message) {
  // process.stdout.write('"' + message + '"\n');
  var expected = messages.shift();
  if (!expected || typeof expected === 'string') {
    assert.equal(message, expected);
  }
  else if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    assert.ok(expected.test(message));
  }
  else {
    expected(message);
  }
}

var args = ['organization', 'http://www.popoloproject.com/schemas/organization.json#']
  , directory = 'test/fixtures'
  , logger = {info: log, error: log};

validator(args, {output_dir: directory}, logger, function () {
  var client = redis.createClient(6379, '127.0.0.1');

  client.select(15, function (err, res) {
    client.flushall(function (err, res) {
      glob('*.json', {cwd: directory}, function ($, files) {
        var array = [];
        files.forEach(function (file) {
          array.push(file, fs.readFileSync(path.join(directory, file)));
        });

        client.mset(array, function (err, res) {
          client.quit();
          validator(args, {output_dir: 'redis://127.0.0.1:6379/15'}, logger, function () {
            assert.equal(messages.length, 0);
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
//var jQuery = require('../serve/jquery-1.11.3.js');
var $ = require('jquery');
//var couch = require('../serve/jquery.couch-1.5.js');
var couch = require('couchjs');
var mica = require('../serve/mica.js');
//eval(fs.readFileSync('../serve/mica.js')+'');

var Docker = require('dockerode');
var docker = new Docker({socketPath: '/var/run/docker.sock'});

function remove(container, next) {
	container.remove(function (err, data) {
	  if (err) {
	      console.log(err);
	  } else {
	      console.log("Container removed.");
		if(next)
		      next(container, null);
	  }
	});
}
function cleanup(name, next) {
	console.log("Looking up: " + name);
        var container = docker.getContainer(name);
	if (container) {
		container.inspect(function (err, data) {
			if (err) {
			    console.log("No container to cleanup: " + name);
				if(next)
				    next(container, null);
			} else {
				console.log("Container inspected: " + data);
				if (data.State.Running) {
					container.stop(function (err, data) {
						if (err)
						      console.log(err);
						else {
							console.log("Container stopped.");
							remove(container, next);
						}
					});
				} else {
				     remove(container, next);
				}
			  }
		});
	} else {
		console.log("No such container: " + name);
	}
}

// query API for container info
//docker run -i -t -d -p 5984:5984 -p 2222:22 -p 6984:6984 -p 7984:7984 --name couchdev micadev7
options = {
	Image: 'micadev7',
	Cmd: ['/home/mrhines/mica/restart.sh'],
	name: 'couchdev',
	Tty : true,
	ExposedPorts: {
            "22/tcp": {},
            "5984/tcp": {},
            "6984/tcp": {},
            "7984/tcp": {}
        }
}

function start(result, next) {
	docker.createContainer(options, function (err, container) {
	  if (err)
	      console.log(err);
	  else {
		console.log("Container created.");
		container.start(function (err, data) {
			if (err)
			      console.log(err);
			else {
				console.log("Container started.");
				cleanup(options.name, null);
			}
		  });
	  }
	});

}

cleanup(options.name, start);
<commit_msg>done all I can here without internet.<commit_after>var fs = require('fs');
var http = require('http');
//var jQuery = require('../serve/jquery-1.11.3.js');
var $ = require('jquery');
//var couch = require('../serve/jquery.couch-1.5.js');
var couch = require('couchjs');
//var mica = require('../serve/mica.js');
//eval(fs.readFileSync('../serve/mica.js')+'');

var Docker = require('dockerode');
var docker = new Docker({socketPath: '/var/run/docker.sock'});

function remove(container, next) {
	container.remove(function (err, data) {
	  if (err) {
	      console.log(err);
	  } else {
	      console.log("Container removed.");
		if(next)
		      next(container, null);
	  }
	});
}
function cleanup(name, next) {
	console.log("Looking up: " + name);
        var container = docker.getContainer(name);
	if (container) {
		container.inspect(function (err, data) {
			if (err) {
			    console.log("No container to cleanup: " + name);
				if(next)
				    next(container, null);
			} else {
				console.log("Container inspected: " + data);
				if (data.State.Running) {
					container.stop(function (err, data) {
						if (err)
						      console.log(err);
						else {
							console.log("Container stopped.");
							remove(container, next);
						}
					});
				} else {
				     remove(container, next);
				}
			  }
		});
	} else {
		console.log("No such container: " + name);
	}
}

var options = {
	Image: 'micadev7',
	Cmd: ['/home/mrhines/mica/restart.sh'],
	name: 'couchdev',
	Tty : true,
	PortBindings: {
            "22/tcp": [{
	            "HostIp": "0.0.0.0",
                    "HostPort": "2222"
	     }],
            "5984/tcp": [{
	            "HostIp": "0.0.0.0",
                    "HostPort": "5984"
	    }],
            "6984/tcp": [{
	            "HostIp": "0.0.0.0",
                    "HostPort": "6984"
	    }],
            "7984/tcp": [{
	            "HostIp": "0.0.0.0",
                    "HostPort": "7984"
	    }]
        }
}

var loc = {
    host: 'localhost',
    port: 80,
    path: '/'
};

function start(result, next) {
	docker.createContainer(options, function (err, container) {
	  if (err)
	      console.log(err);
	  else {
		console.log("Container created.");
		container.start(function (err, data) {
			if (err)
			      console.log(err);
			else {
				console.log("Container started.");
				//cleanup(options.name, null);

				var html = '';
				http.get(options, function(res) {
				    res.on('data', function(data) {
					// collect the data chunks to the variable named "html"
					html += data;
				    }).on('end', function() {
					var title = $(html).find('title').text();
					console.log("HTML title:" + title);
				     });
				});
			}
		  });
	  }
	});

}
cleanup(options.name, start);
<|endoftext|>


<commit_before>var next_menu_node_id = 1;

var configuration_updated = false;

function _menu_create_node( n, n_id, current_state ) {
/*
  Function to create a hide/show link on a node...
*/
  var q = Builder.node('span',
    { id: n_id, className: 'menu_help' },
    [ current_state ? 'Hide info' : 'Show info' ]
  );
  n.appendChild(q);
  Event.observe(q,'click',function(e){
    remove_grey_box();
    var me = Event.findElement(e,'SPAN');
    var n  = me.parentNode;
    var t = me.id;
    var x = t+'_dd';
    me.remove();
    if( $(x) ) {
      $(x).toggle();
      _menu_create_node( n, t, $(x).visible() );
    }

  });
}

var current_menu_id = '';
var current_link_id = '';
var current_selected_node = '';
var initial_configuration = false;

function __init_config_menu() {
/*
  Section 1)
  Loop through all the track configuration links on the left hand side of the
  configuration box, remove the link (so the href doesn't get fired (yuk!)
  add an onclick event to show the appropriate menu and hide the menu
*/
  if( ! initial_configuration ) {
    initial_configuration = $('configuration') ? $('configuration').serialize(true) : false;
  }

  var has_configuration = $$('.track_configuration').length > 0;
  $$('.track_configuration dd').each(function(n) {
    var link_id = n.id;
    var menu_id = 'menu_'+link_id.substr(5);
    if( n.hasClassName('active') ) {
      current_menu_id = menu_id;
      current_link_id = link_id;
    } else {
      $(menu_id).hide();
    }
    var an = n.select('a')[0];
    if( an ) {
      var txt =an.innerHTML;
      an.remove();
      n.appendChild(Builder.node('span', { className: 'fake_link' }, [ txt ] ));
    }
    Event.observe( n, 'click', function(e) {
      remove_grey_box();
      var dd_n = Event.findElement(e,'DD');
      var link_id = dd_n.id;
      var menu_id = 'menu_'+link_id.substr(5);
      if( current_menu_id ) {
        $(current_menu_id).hide();
        $(current_link_id).removeClassName('active');
      }
      $(menu_id).show();
      dd_n.addClassName('active');
      current_menu_id=menu_id;
      current_link_id=link_id;
    });
  });
/*
  Section 2)
  Add a hide/show link to each of the menu items on the right handside...
*/
  $$('dl.config_menu').each(function(menu_n){
    var col          = 1;
    var current_node = 0;
    var div_n = menu_n.up('div');
    menu_n.childElements().each(function(n){
      if(n.nodeName == 'DT') {
        col = 3-col;
        n.addClassName('col'+col);
	if( !n.hasClassName('munged') ) {
	  n.addClassName( 'munged' ); // Stop a double rendering of the links!
          _menu_create_node( n, 'mn_'+next_menu_node_id, 0 );
	}
        current_node = next_menu_node_id;
        next_menu_node_id++;
        n.select('select').each(function(sn){
	  if(sn.visible()) {
            var current_selected = 'off';
            sn.hide();
            sn.select('option').each(function(on){
              if(on.selected) {
                var x = on.value;
                var i = Builder.node('img',{
                  src:'/i/render/'+x+'.gif', title:on.text,
                  cursor: 'hand',
                  id:'gif_'+sn.id
                });
                n.insertBefore(i,sn.nextSibling);
                Event.observe(i,'click',change_img_value);
             }
            });
	  }
        });
      } else if(n.nodeName == 'DD' && current_node) {
        n.setAttribute('id','mn_'+current_node+'_dd');
        n.addClassName('col'+col);
        n.hide();
      }
    });
  });
/* deprecated!!
  if( $('config') ) {
    Event.observe( $('config'), 'submit', function(f){
      alert($('config').serialize());
    });
  } */
}

var configurator_action_url = '';
var configurator_action_title = '';

function configurator_submit_form( url, title ) {
  remove_grey_box(); // Remove our "pseudo" graphical dropdowns....
  // Grab the final configuration ...
  var final_configuration = $H( $('configuration') ? $('configuration').serialize(true) :{} );
  // ... and compare it with the initial configuration
  var diff_configuration = {};
  var config_name = '';
  final_configuration.each(function(pair){
    if( pair.key == 'config' ) {
      config_name = pair.value;
    } else if( pair.value != initial_configuration[pair.key] ) {
      diff_configuration[ pair.key ] = pair.value;
    }
    delete initial_configuration[pair.key];
  });
  $H(initial_configuration).each(function(pair){ diff_configuration[ pair.key ] = 'no'; }); // CheckBox 0 value!
  initial_configuration = false;
  if( $H(diff_configuration).keys().size() == 0 ) {
    __modal_dialog_link_open_2( url, title );
    return;
  }
  if( config_name ) {
    diff_configuration[ 'config' ] = config_name;
  }
  diff_configuration[ 'submit' ] = 1;
  // ... create a query string from this...
  if( ENSEMBL_AJAX == 'enabled' ) { // We have Ajax so submit it using AJAX
    $('modal_disable').show();
    configurator_action_url   = url;
    configurator_action_title = title;
    new Ajax.Request( $('configuration').action,{
      method : $('configuration').method,
      parameters: $H(diff_configuration),
      onSuccess: function( transport ) { configurator_success(transport) },
      onFailure: function( transport ) {
        $('modal_disable').hide();
	$('modal_content').innerHTML = '
Failure: unable to update configuration
';
      }
    });
  }
}

function configurator_success( transport ) {
  var x = transport.responseText;
  $('modal_disable').hide();
  if( x == 'SUCCESS' ) { // Form submitted OK!... we need to flag this case!
    configuration_updated = true;
    $('modal_content').update(Builder.node('div', 'Content updated'));
    __modal_dialog_link_open_2( configurator_action_url, configurator_action_title );
  } else { // We've got the form back....
    modal_success( transport ); // Act like we just loaded it!!!
  }
}

function remove_grey_box() {
  if( $('s_menu') ) $('s_menu').remove();
  current_selected_index = 0;
}

function change_img_value(e) {
  var i_node = Event.element(e);
  var select_id = i_node.id.substr(4);
      current_selected_index = select_id;
  var value     = i_node.src;
  if($('s_menu')) $('s_menu').remove();
//  i_node.absolutize();
  var x = Position.cumulativeOffset(i_node);
  var select_menu = Builder.node('dl',{
    id:       's_menu',
    className:'popup_menu',
    style:    'position:absolute;top:'+(x[1]+15)+'px;left:'+(x[0]+10)+'px;z-index: 1000000;'
  });
  $$('body')[0].appendChild(select_menu);

  $(select_id).select('option').each(function(on){
    dt_node = Builder.node('dt',
      [ Builder.node('img',  {title: on.text,src:'/i/render/'+on.value+'.gif'}),on.text ]
    )
    select_menu.appendChild(dt_node);
    Event.observe(dt_node,'click',function(e){
      var value = Event.findElement(e,'DT').select('img')[0].title;
      dt_node.parentNode.remove();
      $(current_selected_index).select('option').each(function(on){
        if(on.text == value) {
          on.selected = "selected";
          $('gif_'+current_selected_index).src = '/i/render/'+on.value+'.gif';
          current_selected_index = 0; return;
        }
      });
    });
  });
//  i_node.relativize();
}

addLoadEvent(__init_config_menu);
<commit_msg>hide submit button<commit_after>var next_menu_node_id = 1;

var configuration_updated = false;

function _menu_create_node( n, n_id, current_state ) {
/*
  Function to create a hide/show link on a node...
*/
  var q = Builder.node('span',
    { id: n_id, className: 'menu_help' },
    [ current_state ? 'Hide info' : 'Show info' ]
  );
  n.appendChild(q);
  Event.observe(q,'click',function(e){
    remove_grey_box();
    var me = Event.findElement(e,'SPAN');
    var n  = me.parentNode;
    var t = me.id;
    var x = t+'_dd';
    me.remove();
    if( $(x) ) {
      $(x).toggle();
      _menu_create_node( n, t, $(x).visible() );
    }

  });
}

var current_menu_id = '';
var current_link_id = '';
var current_selected_node = '';
var initial_configuration = false;

function __init_config_menu() {
/*
  Section 1)
  Loop through all the track configuration links on the left hand side of the
  configuration box, remove the link (so the href doesn't get fired (yuk!)
  add an onclick event to show the appropriate menu and hide the menu
*/
  if( ! initial_configuration ) {
    initial_configuration = $('configuration') ? $('configuration').serialize(true) : false;
  }

  var has_configuration = $$('.track_configuration').length > 0;
  $$('.track_configuration dd').each(function(n) {
    var link_id = n.id;
    var menu_id = 'menu_'+link_id.substr(5);
    if( n.hasClassName('active') ) {
      current_menu_id = menu_id;
      current_link_id = link_id;
    } else {
      $(menu_id).hide();
    }
    var an = n.select('a')[0];
    if( an ) {
      var txt =an.innerHTML;
      an.remove();
      n.appendChild(Builder.node('span', { className: 'fake_link' }, [ txt ] ));
    }
    Event.observe( n, 'click', function(e) {
      remove_grey_box();
      var dd_n = Event.findElement(e,'DD');
      var link_id = dd_n.id;
      var menu_id = 'menu_'+link_id.substr(5);
      if( current_menu_id ) {
        $(current_menu_id).hide();
        $(current_link_id).removeClassName('active');
      }
      $(menu_id).show();
      dd_n.addClassName('active');
      current_menu_id=menu_id;
      current_link_id=link_id;
    });
  });
/*
  Section 2)
  Add a hide/show link to each of the menu items on the right handside...
*/
  $$('dl.config_menu').each(function(menu_n){
    var col          = 1;
    var current_node = 0;
    var div_n = menu_n.up('div');
    menu_n.childElements().each(function(n){
      if(n.nodeName == 'DT') {
        col = 3-col;
        n.addClassName('col'+col);
	if( !n.hasClassName('munged') ) {
	  n.addClassName( 'munged' ); // Stop a double rendering of the links!
          _menu_create_node( n, 'mn_'+next_menu_node_id, 0 );
	}
        current_node = next_menu_node_id;
        next_menu_node_id++;
        n.select('select').each(function(sn){
	  if(sn.visible()) {
            var current_selected = 'off';
            sn.hide();
            sn.select('option').each(function(on){
              if(on.selected) {
                var x = on.value;
                var i = Builder.node('img',{
                  src:'/i/render/'+x+'.gif', title:on.text,
                  cursor: 'pointer',
                  id:'gif_'+sn.id
                });
                n.insertBefore(i,sn.nextSibling);
                Event.observe(i,'click',change_img_value);
             }
            });
	  }
        });
      } else if(n.nodeName == 'DD' && current_node) {
        n.setAttribute('id','mn_'+current_node+'_dd');
        n.addClassName('col'+col);
        n.hide();
      }
    });
  });
  $$('dt.submit').each(function(n){ n.hide(); });
/* deprecated!!
  if( $('config') ) {
    Event.observe( $('config'), 'submit', function(f){
      alert($('config').serialize());
    });
  } */
}

var configurator_action_url = '';
var configurator_action_title = '';

function configurator_submit_form( url, title ) {
  remove_grey_box(); // Remove our "pseudo" graphical dropdowns....
  // Grab the final configuration ...
  var final_configuration = $H( $('configuration') ? $('configuration').serialize(true) :{} );
  // ... and compare it with the initial configuration
  var diff_configuration = {};
  var config_name = '';
  final_configuration.each(function(pair){
    if( pair.key == 'config' ) {
      config_name = pair.value;
    } else if( pair.value != initial_configuration[pair.key] ) {
      diff_configuration[ pair.key ] = pair.value;
    }
    delete initial_configuration[pair.key];
  });
  $H(initial_configuration).each(function(pair){ diff_configuration[ pair.key ] = 'no'; }); // CheckBox 0 value!
  initial_configuration = false;
  if( $H(diff_configuration).keys().size() == 0 ) {
    __modal_dialog_link_open_2( url, title );
    return;
  }
  if( config_name ) {
    diff_configuration[ 'config' ] = config_name;
  }
  diff_configuration[ 'submit' ] = 1;
  // ... create a query string from this...
  if( ENSEMBL_AJAX == 'enabled' ) { // We have Ajax so submit it using AJAX
    $('modal_disable').show();
    configurator_action_url   = url;
    configurator_action_title = title;
    new Ajax.Request( $('configuration').action,{
      method : $('configuration').method,
      parameters: $H(diff_configuration),
      onSuccess: function( transport ) { configurator_success(transport) },
      onFailure: function( transport ) {
        $('modal_disable').hide();
	$('modal_content').innerHTML = '
Failure: unable to update configuration
';
      }
    });
  }
}

function configurator_success( transport ) {
  var x = transport.responseText;
  $('modal_disable').hide();
  if( x == 'SUCCESS' ) { // Form submitted OK!... we need to flag this case!
    configuration_updated = true;
    $('modal_content').update(Builder.node('div', 'Content updated'));
    __modal_dialog_link_open_2( configurator_action_url, configurator_action_title );
  } else { // We've got the form back....
    modal_success( transport ); // Act like we just loaded it!!!
  }
}

function remove_grey_box() {
  if( $('s_menu') ) $('s_menu').remove();
  current_selected_index = 0;
}

function change_img_value(e) {
  var i_node = Event.element(e);
  var select_id = i_node.id.substr(4);
      current_selected_index = select_id;
  var value     = i_node.src;
  if($('s_menu')) $('s_menu').remove();
//  i_node.absolutize();
  var x = Position.cumulativeOffset(i_node);
  var select_menu = Builder.node('dl',{
    id:       's_menu',
    className:'popup_menu',
    style:    'position:absolute;top:'+(x[1]+15)+'px;left:'+(x[0]+10)+'px;z-index: 1000000;'
  });
  $$('body')[0].appendChild(select_menu);

  $(select_id).select('option').each(function(on){
    dt_node = Builder.node('dt',
      [ Builder.node('img',  {title: on.text,src:'/i/render/'+on.value+'.gif'}),on.text ]
    )
    select_menu.appendChild(dt_node);
    Event.observe(dt_node,'click',function(e){
      var value = Event.findElement(e,'DT').select('img')[0].title;
      dt_node.parentNode.remove();
      $(current_selected_index).select('option').each(function(on){
        if(on.text == value) {
          on.selected = "selected";
          $('gif_'+current_selected_index).src = '/i/render/'+on.value+'.gif';
          current_selected_index = 0; return;
        }
      });
    });
  });
//  i_node.relativize();
}

addLoadEvent(__init_config_menu);
<|endoftext|>


<commit_before>//global variables
var stage;
var text;
var pixelMatrix; // 3D array of the row and columns with an area of rectSize^2
var rawPixelData; // array of pixel objects
var blackRects;
//setting variables
var canBackground, fps;
var rectSize, thresholdAlpha, resolution;
var innerText, outerText;
//variables vor animated drawing
var animatedK = 0;
var animatedO = 0;

//call init to start
$(document).ready(function() {
    init();
});
//initialize the project
function init() {
    /*
     * SETTINGS
     */
    canBackground = "RGB(255,255,255)";
    fps = 500;
    rectSize = 10;
    thresholdAlpha = 250;
    $("#innerText").val("1");
    $("#outterText").val("0");
    /*
     * SETTINGS END
     */
    //create stage
    stage = new createjs.Stage("demoCanvas");
    stage.canvas.style.background = canBackground;
    resolution = Math.floor((rectSize * rectSize) / 2);
    rectResolution = {
        x: Math.floor(stage.canvas.width / rectSize),
        y: Math.floor(stage.canvas.height / rectSize)
    };
    //calculate array size by rectSize
    rawPixelData = [];
    pixelMatrix = createEmpty3DArray(rectResolution.x, rectResolution.y);
    blackRects = createFilled2DArray(rectResolution.x, rectResolution.y);
    // register events
    $("#start").click(startVisualisation);
    $("#export").click(exportJPEG);
}
//ticker, which controls the drawing
function tick() {
        drawAnimated();
}

function startVisualisation() {
    createjs.Ticker.paused = false;
    stage.removeAllChildren();
    showText($("#textToShow").val(), stage.canvas.width / 2, stage.canvas.height / 2, 20, true);
    rawPixelData = getPixels();
    stage.removeChild(text);
    for (i = 0; i < rawPixelData.length; i++) {
        var x = Math.floor((i / rectSize) % rectResolution.x);
        var y = Math.floor(i / (rectResolution.x * rectSize * rectSize));
        pixelMatrix[x][y].push(i);
    }
    blackRects = calcFilledAreas(rawPixelData, pixelMatrix, resolution);

    if($("#animatedActiv").val() == "on"){
        createjs.Ticker.addEventListener("tick", tick);
        createjs.Ticker.setFPS(fps);
    }else{
        draw();
    }
}

function getPixels() {
    var imageData = stage.canvas.getContext('2d').getImageData(0, 0, stage.canvas.width, stage.canvas.height).data;
    var arr = []
    for (i = 0; i < imageData.length; i = i + 4) {
        arr.push({
            r: imageData[i],
            g: imageData[i + 1],
            b: imageData[i + 2],
            a: imageData[i + 3]
        });
    }
    return arr;
}

function showText(msg, x, y, scale, update) {
    text = new createjs.Text();
    text.set({
        text: msg,
        textAlign: 'center',
        textBaseline: 'middle'
    });
    //scale text
    text.scaleX = scale;
    text.scaleY = scale;
    //move text to mid of canvas
    b = text.getBounds();
    text.x = x;
    text.y = y;
    stage.addChild(text);
    if (update)
        stage.update(); //update stage to show text
}

function createEmpty3DArray(xSize, ySize) {
    var array3D = new Array(xSize);
    for (i = 0; i < array3D.length; i++) {
        array3D[i] = new Array(ySize);
        for (j = 0; j < array3D[i].length; j++) {
            array3D[i][j] = [];
        }
    }
    return array3D;
}

function createFilled2DArray(xSize, ySize) {
    var array2D = new Array(xSize);
    for (i = 0; i < array2D.length; i++) {
        array2D[i] = new Array(ySize);
    }
    return array2D;
}

function calcFilledAreas(rawData, array3D, res) {
    var blackPixelCounter;
    var matrixWithBlackAreas = createFilled2DArray(array3D.length, array3D[0].length);
    for (i = 0; i < array3D.length; i++) {
        for (j = 0; j < array3D[i].length; j++) {
            blackPixelCounter = 0;
            for (k = 0; k < array3D[i][j].length; k++) {
                if (rawData[array3D[i][j][k]].a >= thresholdAlpha) {
                    blackPixelCounter++;
                }
            }
            if (blackPixelCounter >= res) {
                matrixWithBlackAreas[i][j] = true;
            } else {
                matrixWithBlackAreas[i][j] = false;
            }
        }
    }
    return matrixWithBlackAreas;
}

function draw() {
    innerText = $("#innerText").val();
    outterText = $("#outterText").val();
    for (k = 0; k < blackRects.length; k++) {
        for (o = 0; o < blackRects[k].length; o++) {
            if (blackRects[k][o] == true) {
                showText(innerText, k * rectSize, o * rectSize, 1, false);
            } else {
                showText(outterText, k * rectSize, o * rectSize, 1, false);
            }
        }
    }
    stage.update();
    createjs.Ticker.paused = true;
}

function drawAnimated() {
    innerText = $("#innerText").val();
    outterText = $("#outterText").val();
    if(animatedK < blackRects.length) {
        if(animatedO < blackRects[animatedK].length) {
            if(blackRects[animatedK][animatedO] == true) {
                showText(innerText, animatedK * rectSize, animatedO * rectSize, 1, false);
            }else{
                showText(outterText, animatedK * rectSize, animatedO * rectSize, 1, false);
            }
            stage.update();
            animatedO ++;
        }else{
            animatedK ++;
            animatedO = 0;
        }
    }else{
        createjs.Ticker.paused = true;
        animatedK = 0;
        animatedO = 0;
    }
}

function exportJPEG() {
    //generate the url using toDataURL
    canvas = document.getElementById("demoCanvas");
    var img = canvas.toDataURL("image/png;base64;");
    //img = img.replace("image/png","image/octet-stream"); // force download, user would have to give the file name.
    // you can also use anchor tag with download attribute to force download the canvas with file name.
    window.open(img, "", "width=500,height=500");
}
<commit_msg>animated drawing now works, need to get cached<commit_after>//global variables
var stage;
var text;
var pixelMatrix; // 3D array of the row and columns with an area of rectSize^2
var rawPixelData; // array of pixel objects
var blackRects;
//setting variables
var canBackground, fps;
var rectSize, thresholdAlpha, resolution;
var innerText, outerText;
//variables vor animated drawing
var animatedK = 0;
var animatedO = 0;

//call init to start
$(document).ready(function() {
    init();
});
//initialize the project
function init() {
    /*
     * SETTINGS
     */
    canBackground = "RGB(255,255,255)";
    fps = 500;
    rectSize = 10;
    thresholdAlpha = 250;
    $("#innerText").val("1");
    $("#outterText").val("0");
    /*
     * SETTINGS END
     */
    //create stage
    stage = new createjs.Stage("demoCanvas");
    stage.canvas.style.background = canBackground;
    resolution = Math.floor((rectSize * rectSize) / 2);
    rectResolution = {
        x: Math.floor(stage.canvas.width / rectSize),
        y: Math.floor(stage.canvas.height / rectSize)
    };
    //calculate array size by rectSize
    rawPixelData = [];
    pixelMatrix = createEmpty3DArray(rectResolution.x, rectResolution.y);
    blackRects = createFilled2DArray(rectResolution.x, rectResolution.y);
    // register events
    $("#start").click(startVisualisation);
    $("#export").click(exportJPEG);
}
//ticker, which controls the drawing
function tick() {
        drawAnimated();
}

function startVisualisation() {
    createjs.Ticker.paused = false;
    stage.removeAllChildren();
    showText($("#textToShow").val(), stage.canvas.width / 2, stage.canvas.height / 2, 20, true);
    rawPixelData = getPixels();
    stage.removeChild(text);
    for (i = 0; i < rawPixelData.length; i++) {
        var x = Math.floor((i / rectSize) % rectResolution.x);
        var y = Math.floor(i / (rectResolution.x * rectSize * rectSize));
        pixelMatrix[x][y].push(i);
    }
    blackRects = calcFilledAreas(rawPixelData, pixelMatrix, resolution);

    if(document.getElementById('animatedActiv').checked == true){
        createjs.Ticker.addEventListener("tick", tick);
        createjs.Ticker.setFPS(fps);
    }else{
        draw();
    }
}

function getPixels() {
    var imageData = stage.canvas.getContext('2d').getImageData(0, 0, stage.canvas.width, stage.canvas.height).data;
    var arr = []
    for (i = 0; i < imageData.length; i = i + 4) {
        arr.push({
            r: imageData[i],
            g: imageData[i + 1],
            b: imageData[i + 2],
            a: imageData[i + 3]
        });
    }
    return arr;
}

function showText(msg, x, y, scale, update) {
    text = new createjs.Text();
    text.set({
        text: msg,
        textAlign: 'center',
        textBaseline: 'middle'
    });
    //scale text
    text.scaleX = scale;
    text.scaleY = scale;
    //move text to mid of canvas
    b = text.getBounds();
    text.x = x;
    text.y = y;
    text.snapToPixel = true;
    stage.addChild(text);
    if (update)
        stage.update(); //update stage to show text
}

function createEmpty3DArray(xSize, ySize) {
    var array3D = new Array(xSize);
    for (i = 0; i < array3D.length; i++) {
        array3D[i] = new Array(ySize);
        for (j = 0; j < array3D[i].length; j++) {
            array3D[i][j] = [];
        }
    }
    return array3D;
}

function createFilled2DArray(xSize, ySize) {
    var array2D = new Array(xSize);
    for (i = 0; i < array2D.length; i++) {
        array2D[i] = new Array(ySize);
    }
    return array2D;
}

function calcFilledAreas(rawData, array3D, res) {
    var blackPixelCounter;
    var matrixWithBlackAreas = createFilled2DArray(array3D.length, array3D[0].length);
    for (i = 0; i < array3D.length; i++) {
        for (j = 0; j < array3D[i].length; j++) {
            blackPixelCounter = 0;
            for (k = 0; k < array3D[i][j].length; k++) {
                if (rawData[array3D[i][j][k]].a >= thresholdAlpha) {
                    blackPixelCounter++;
                }
            }
            if (blackPixelCounter >= res) {
                matrixWithBlackAreas[i][j] = true;
            } else {
                matrixWithBlackAreas[i][j] = false;
            }
        }
    }
    return matrixWithBlackAreas;
}

function draw() {
    innerText = $("#innerText").val();
    outterText = $("#outterText").val();
    for (k = 0; k < blackRects.length; k++) {
        for (o = 0; o < blackRects[k].length; o++) {
            if (blackRects[k][o] == true) {
                showText(innerText, k * rectSize, o * rectSize, 1, false);
            } else {
                showText(outterText, k * rectSize, o * rectSize, 1, false);
            }
        }
    }
    stage.update();
    createjs.Ticker.paused = true;
}

function drawAnimated() {
    innerText = $("#innerText").val();
    outterText = $("#outterText").val();
    if(animatedK < blackRects.length) {
        if(animatedO < blackRects[animatedK].length) {
            if(blackRects[animatedK][animatedO] == true) {
                showText(innerText, animatedK * rectSize, animatedO * rectSize, 1, false);
            }else{
                showText(outterText, animatedK * rectSize, animatedO * rectSize, 1, false);
            }
            stage.update();
            animatedO ++;
        }else{
            animatedK ++;
            animatedO = 0;
        }
    }else{
        createjs.Ticker.paused = true;
        animatedK = 0;
        animatedO = 0;
    }
}

function exportJPEG() {
    //generate the url using toDataURL
    canvas = document.getElementById("demoCanvas");
    var img = canvas.toDataURL("image/png;base64;");
    //img = img.replace("image/png","image/octet-stream"); // force download, user would have to give the file name.
    // you can also use anchor tag with download attribute to force download the canvas with file name.
    window.open(img, "", "width=500,height=500");
}
<|endoftext|>


<commit_before>/*jshint node:true */

// Requires
var gutil = require('gulp-util');
var ts = require('../index');
var assert = require('assert');
var exec = require('child_process').exec;
var should = require('should');
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');

describe('gulp-ts', function () {
	var seconds=8;
	this.timeout(seconds*1000);

	gulp = function(task, done) {
		exec('gulp ' + task, function(error, stdout, stderr) {
			if (stderr) {
				console.log('gulp.stderr:' + stderr);
			}
			if (error) {
				throw error;
			}
			done();
		});
	};

	filesShouldExist = function(expectedFiles, done) {
		expectedFiles.forEach(function (theFile) {
			var doesExist = fs.existsSync(path.join('out', theFile));
			//console.log(theFile, doesExist ? 'does exist' : 'does NOT exist');
			doesExist.should.be.true;
		});
		if (done) {
			done();
		}
	}

	it ('should compile files in multiple folders', function(done) {
		//['hello.ts', 'subfolder/hello3.ts']
		gulp('default', function() {
			var expectedFiles = [
				'hello.js',
				'hello3.js'
			];
			filesShouldExist(expectedFiles, done);
		});
	})

	it ('should export declaration', function(done) {
		gulp('declaration', function() {
			var expectedFiles = [
				'log.d.ts'
			];
			filesShouldExist(expectedFiles, done);
		});
	});

	it ('should export declaration with singlefile', function(done) {
		gulp('declaration-singlefile', function() {
			var expectedFiles = [
				'myindex.d.ts'
			];
			filesShouldExist(expectedFiles, done);
		});
	})
//this is failing but no easy solution
	it.skip ('should work with a file in subfolder only', function (done) {
		gulp('subfolder-only', function() {
			expectedFiles =	[
				'hello3.js'
			];
			filesShouldExist(expectedFiles, done);
		});
	});
});

<commit_msg>Style issues<commit_after>/*jshint node:true */

// Requires
var fs = require('fs');
var path = require('path');

var gutil = require('gulp-util');
var ts = require('../index');
var assert = require('assert');
var exec = require('child_process').exec;
var should = require('should');
var shell = require('shelljs');

describe('gulp-ts', function () {
	var seconds=8;
	this.timeout(seconds*1000);

	gulp = function(task, done) {
		exec('gulp ' + task, function(error, stdout, stderr) {
			if (stderr) {
				console.log('gulp.stderr:' + stderr);
			}
			if (error) {
				throw error;
			}
			done();
		});
	};

	filesShouldExist = function(expectedFiles, done) {
		expectedFiles.forEach(function (theFile) {
			var doesExist = fs.existsSync(path.join('out', theFile));
			//console.log(theFile, doesExist ? 'does exist' : 'does NOT exist');
			doesExist.should.be.true;
		});
		if (done) {
			done();
		}
	}

	it ('should compile files in multiple folders', function(done) {
		//['hello.ts', 'subfolder/hello3.ts']
		gulp('default', function() {
			var expectedFiles = [
				'hello.js',
				'hello3.js'
			];
			filesShouldExist(expectedFiles, done);
		});
	})

	it ('should export declaration', function(done) {
		gulp('declaration', function() {
			var expectedFiles = [
				'log.d.ts'
			];
			filesShouldExist(expectedFiles, done);
		});
	});

	it ('should export declaration with singlefile', function(done) {
		gulp('declaration-singlefile', function() {
			var expectedFiles = [
				'myindex.d.ts'
			];
			filesShouldExist(expectedFiles, done);
		});
	})
	// This is failing but no easy solution
	it.skip ('should work with a file in subfolder only', function (done) {
		gulp('subfolder-only', function() {
			expectedFiles =	[
				'hello3.js'
			];
			filesShouldExist(expectedFiles, done);
		});
	});
});

<|endoftext|>


<commit_before>var assert = require('assert'),
    Tik = require('../').Tik,
    tik = new Tik({ db: __dirname + '/testdb' }),
    stream = require('stream'),
    rs = stream.Readable(),
    ws = stream.Writable(),
    tws = tik.writeStream(),
    trs = tik.readStream(),
    tds = tik.deleteStream();

tws.write({ key: 'a', value: 1 });
tws.write({ key: 'b', value: 2 });
tws.write({ key: 'c', value: 3 });

var bad = setTimeout(function () { assert.ok(false); }, 1000),
    entry = 1;

rs._read = function () {
  rs.push('a');
  rs.push('b');
  rs.push('c');
  rs.push(null);
};

ws._write = function (data, enc, next) {
  if (entry == 3) clearTimeout(bad);
  data = data.toString();
  assert.ok(data == 1 || data == 2 || data == 3);
  entry++;
  if (entry == 4) console.log('test');//testKeyStream();
  next();
};

rs.pipe(trs).pipe(ws);
function testKeyStream() {
  var ws2 = stream.Writable();
  bad = setTimeout(function () { assert.ok(false); }, 1000);

  ws2._write = function (data, enc, next) {
    data = data.toString();
    if (entry == 2) {
      clearTimeout(bad);
      testDeleteStream();
    }
    assert.ok(data == 'a' || data == 'b' || data == 'c');
    entry--;
    next();
  }

  tik.keyStream().pipe(ws2);
}
function testDeleteStream() {
  var ws3 = stream.Writable();
  tds.write({ key: 'a' });
  tds.write({ key: 'b' });
  tds.write({ key: 'c' });
  ws3._write = function (data, enc, next) {
    assert.ok(data == null);
    next();
  };

  tds.pipe(ws3);
}
<commit_msg>i hate you, travis. what the hell is wrong with you?<commit_after>var assert = require('assert'),
    Tik = require('../').Tik,
    tik = new Tik({ db: __dirname + '/testdb' }),
    stream = require('stream'),
    rs = stream.Readable(),
    ws = stream.Writable(),
    tws = tik.writeStream(),
    trs = tik.readStream(),
    tds = tik.deleteStream();

tws.write({ key: 'a', value: 1 });
tws.write({ key: 'b', value: 2 });
tws.write({ key: 'c', value: 3 });

var bad = setTimeout(function () { assert.ok(false); }, 1000),
    entry = 1;

rs._read = function () {
  rs.push('a');
  rs.push('b');
  rs.push('c');
  rs.push(null);
};

ws._write = function (data, enc, next) {
  if (entry == 3) clearTimeout(bad);
  data = data.toString();
  assert.ok(data == 1 || data == 2 || data == 3);
  entry++;
  if (entry == 4) testKeyStream();
  next();
};

rs.pipe(trs).pipe(ws);
function testKeyStream() {
  var ws2 = stream.Writable();
  bad = setTimeout(function () { assert.ok(false); }, 1000);

  ws2._write = function (data, enc, next) {
    data = data.toString();
    if (entry == 2) {
      clearTimeout(bad);
      testDeleteStream();
    }
    assert.ok(data == 'a' || data == 'b' || data == 'c');
    entry--;
    next();
  }

  tik.keyStream().pipe(ws2);
}
function testDeleteStream() {
  var ws3 = stream.Writable();
  tds.write({ key: 'a' });
  tds.write({ key: 'b' });
  tds.write({ key: 'c' });
  ws3._write = function (data, enc, next) {
    assert.ok(data == null);
    next();
  };

  tds.pipe(ws3);
}
<|endoftext|>


<commit_before>/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "(config|EXPORTED_SYMBOLS)" }]*/
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
XPCOMUtils.defineLazyModuleGetter(this, "AttributionCode",
                                  "resource:///modules/AttributionCode.jsm");

const EXPORTED_SYMBOLS = ["config"];

const config = {
  study: {
    studyName: "tracking-protection-study", // no spaces, for all the reasons

    async getCampaignId() {
      if (this.variation) {
        return this.variation.campaign_id;
      }

      let data = await AttributionCode.getAttrDataAsync();
      return data.campaign;
    },

    // optional, use to override/decide
    // Disable this for production!

    variation: {
      name: "opentab",
      campaign_id: "download-2",
    },

    weightedVariations: [
      { name: "control", weight: 1 },
      { name: "doorhanger", weight: 1 },
      { name: "opentab", weight: 1 },
    ],

    campaigns: {
      "doorhanger": {
        "campaign_ids": [
          "download-1",
          "download-2",
          "download-3",
        ],
        "messages": [
          "Tracking protection is enabled, making Firefox super fast.",
          "Tracking protection is enabled, blocking annoying ads.",
          "Tracking protection is enabled, protecting your privacy.",
        ],
        "newtab_messages": [
          "Firefox blocked ${blockedRequests} trackers today
 from ${blockedEntities} companies that track your browsing",
          "Firefox blocked ${blockedRequests} trackers today
 and saved you ${minutes} minutes",
          "Firefox blocked ${blockedRequests} ads today
 from ${blockedSites} different websites"
        ],
        "urls": [
          "https://mozilla.org/learn-more-about-tp-study#doorhanger-1",
          "https://mozilla.org/learn-more-about-tp-study#doorhanger-2",
          "https://mozilla.org/learn-more-about-tp-study#doorhanger-3",
        ],
      },
      "opentab": {
        "campaign_ids": [
          "download-1",
          "download-2",
          "download-3",
        ],
        "messages": [],
        "newtab_messages": [
          "Firefox blocked ${blockedRequests} trackers today
 from ${blockedEntities} companies that track your browsing",
          "Firefox blocked ${blockedRequests} trackers today
 and saved you ${minutes} minutes",
          "Firefox blocked ${blockedRequests} ads today
 from ${blockedSites} different websites"
        ],
        "urls": [
          "https://mozilla.org/learn-more-about-tp-study#opentab-1",
          "https://mozilla.org/learn-more-about-tp-study#opentab-2",
          "https://mozilla.org/learn-more-about-tp-study#opentab-3",
        ],
      }
    },
    /** **endings**
      * - keys indicate the 'endStudy' even   that opens these.
      * - urls should be static (data) or external, because they have to
      *   survive uninstall
      * - If there is no key for an endStudy reason, no url will open.
      * - usually surveys, orientations, explanations
      */
    endings: {},
    telemetry: {
      send: true, // assumed false. Actually send pings?
      removeTestingFlag: false,  // Marks pings as testing, set true for actual release
      // TODO "onInvalid": "throw"  // invalid packet for schema?  throw||log
    },
    studyUtilsPath: `./StudyUtils.jsm`,
  },
  async isEligible() {
    // get whatever prefs, addons, telemetry, anything!
    // Cu.import can see 'firefox things', but not package things.
    // In order to import addon libraries, use chrome.manifest and "resource://" in order
    // to get the correct file location. Then it is necessary to use
    // XPCOMUtils.defineLazyModuleGetter() to import the library.

    if (this.study.variation) {
      return true;
    }

    let data = await AttributionCode.getAttrDataAsync();

    if (data && data.campaign) {
      return true;
    }

    return false;
  },
  // addon-specific modules to load/unload during `startup`, `shutdown`
  modules: [
    // can use ${slug} here for example
  ],
  // sets the logging for BOTH the bootstrap file AND shield-study-utils
  log: {
    // Fatal: 70, Error: 60, Warn: 50, Info: 40, Config: 30, Debug: 20, Trace: 10, All: -1,
    bootstrap:  {
      level: "Debug",
    },
    studyUtils:  {
      level: "Trace",
    },
  },
};
<commit_msg>add line breaks<commit_after>/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "(config|EXPORTED_SYMBOLS)" }]*/
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
XPCOMUtils.defineLazyModuleGetter(this, "AttributionCode",
                                  "resource:///modules/AttributionCode.jsm");

const EXPORTED_SYMBOLS = ["config"];

const config = {
  study: {
    studyName: "tracking-protection-study", // no spaces, for all the reasons

    async getCampaignId() {
      if (this.variation) {
        return this.variation.campaign_id;
      }

      let data = await AttributionCode.getAttrDataAsync();
      return data.campaign;
    },

    // optional, use to override/decide
    // Disable this for production!

    variation: {
      name: "opentab",
      campaign_id: "download-2",
    },

    weightedVariations: [
      { name: "control", weight: 1 },
      { name: "doorhanger", weight: 1 },
      { name: "opentab", weight: 1 },
    ],

    campaigns: {
      "doorhanger": {
        "campaign_ids": [
          "download-1",
          "download-2",
          "download-3",
        ],
        "messages": [
          "Tracking protection is enabled, making Firefox super fast.",
          "Tracking protection is enabled, blocking annoying ads.",
          "Tracking protection is enabled, protecting your privacy.",
        ],
        "newtab_messages": [
          "Firefox blocked ${blockedRequests} trackers today
 from ${blockedEntities} companies that track your browsing",
          "Firefox blocked ${blockedRequests} trackers today
 and saved you ${minutes} minutes",
          "Firefox blocked ${blockedRequests} ads today from
 ${blockedSites} different websites"
        ],
        "urls": [
          "https://mozilla.org/learn-more-about-tp-study#doorhanger-1",
          "https://mozilla.org/learn-more-about-tp-study#doorhanger-2",
          "https://mozilla.org/learn-more-about-tp-study#doorhanger-3",
        ],
      },
      "opentab": {
        "campaign_ids": [
          "download-1",
          "download-2",
          "download-3",
        ],
        "messages": [],
        "newtab_messages": [
          "Firefox blocked ${blockedRequests} trackers today
 from ${blockedEntities} companies that track your browsing",
          "Firefox blocked ${blockedRequests} trackers today
 and saved you ${minutes} minutes",
          "Firefox blocked ${blockedRequests} ads today from
 ${blockedSites} different websites"
        ],
        "urls": [
          "https://mozilla.org/learn-more-about-tp-study#opentab-1",
          "https://mozilla.org/learn-more-about-tp-study#opentab-2",
          "https://mozilla.org/learn-more-about-tp-study#opentab-3",
        ],
      }
    },
    /** **endings**
      * - keys indicate the 'endStudy' even   that opens these.
      * - urls should be static (data) or external, because they have to
      *   survive uninstall
      * - If there is no key for an endStudy reason, no url will open.
      * - usually surveys, orientations, explanations
      */
    endings: {},
    telemetry: {
      send: true, // assumed false. Actually send pings?
      removeTestingFlag: false,  // Marks pings as testing, set true for actual release
      // TODO "onInvalid": "throw"  // invalid packet for schema?  throw||log
    },
    studyUtilsPath: `./StudyUtils.jsm`,
  },
  async isEligible() {
    // get whatever prefs, addons, telemetry, anything!
    // Cu.import can see 'firefox things', but not package things.
    // In order to import addon libraries, use chrome.manifest and "resource://" in order
    // to get the correct file location. Then it is necessary to use
    // XPCOMUtils.defineLazyModuleGetter() to import the library.

    if (this.study.variation) {
      return true;
    }

    let data = await AttributionCode.getAttrDataAsync();

    if (data && data.campaign) {
      return true;
    }

    return false;
  },
  // addon-specific modules to load/unload during `startup`, `shutdown`
  modules: [
    // can use ${slug} here for example
  ],
  // sets the logging for BOTH the bootstrap file AND shield-study-utils
  log: {
    // Fatal: 70, Error: 60, Warn: 50, Info: 40, Config: 30, Debug: 20, Trace: 10, All: -1,
    bootstrap:  {
      level: "Debug",
    },
    studyUtils:  {
      level: "Trace",
    },
  },
};
<|endoftext|>