<commit_before>'use strict';

const request = require('request');
const core = require('./../core/core.js');
const TelegramBot = require('node-telegram-bot-api');

/**
 * CREDENTIALS
 **/
const TELEGRAM_ACCESS_TOKEN = process.env.TELEGRAM_ACCESS_TOKEN;

var telegram = new TelegramBot(TELEGRAM_ACCESS_TOKEN, { polling: true });

telegram.on("text", (message) => {
    receivedMessage(message);
    //telegram.sendMessage(message.chat.id, "Hello world");
});

/*
* Fonction appelé par quand on recoit un message
*/
function receivedMessage(message) {
    console.log(JSON.stringify(message));
    var senderID = message.chat.id;
    var message = {
        channel: "Telegram",
        senderID: senderID,
        timestamp: message.date,
        text: message.text,
        first_name: message.from.first_name,
        last_name: message.from.last_name
    };
    core.receivedMessage(message);
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Facebook
*/
function sendMessage(message) {
    switch(message.type) {
        case "text":
            sendTextMessage(message);
        break;
        case "quickreply":
            sendQuickReplyMessage(message);
        break;
        case "location":
            sendLocationMessage(message);
        break;
        case "template":
            sendTemplateMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Facebook
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        telegram.sendMessage(message.senderID, message.text);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var replykeyboard = {keyboard:[]};
        for(var i=0;i<message.choices.length;i++) {
            var button = [{
                text: message.choices[i]
            }];
            replykeyboard.keyboard.push(button);
        }
        //console.log(JSON.stringify({reply_markup: {keyboard:[[{text:"coucou"}]]}}));
        telegram.sendMessage(message.senderID, message.text, {reply_markup: replykeyboard});
    }
}

/*
* Fonction qui envoie un message de type location
*/
function sendLocationMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var replykeyboard = {keyboard:[], one_time_keyboard:true};
        var button = [{
            text: message.text,
            request_location : true
        }];
        replykeyboard.keyboard.push(button);
        telegram.sendMessage(message.senderID, message.text, {reply_markup: replykeyboard});
    }
}

/*
* Fonction qui envoie un message de type location
*/
function sendTemplateMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.attachment != undefined) {
        var elements = [];
        /*
        *   Envoie du message avant le template
        */
        telegram.sendMessage(message.senderID, message.text);
        for(var i=0;i<message.attachment.length;i++) {
            telegram.sendVenue(message.senderID, message.attachment[i].lat, message.attachment[i].long, message.attachment[i].title, message.attachment[i].subtitle)
            if(i==3)break;
        }
    }
}

function sendTemplateMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var replykeyboard = {keyboard:[], one_time_keyboard:true};
        var button = [{
            text: message.text,
            request_location : true
        }];
        replykeyboard.keyboard.push(button);
        telegram.sendMessage(message.senderID, message.text, {reply_markup: replykeyboard});
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {
    /*console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                attachment:{
                    type: message.type,
                    payload: {
                        url: message.text
                    }
                }
            }
        };
        callSendAPI(messageData);
    }*/
}

exports.sendMessage = sendMessage
exports.sendMessages = sendMessages<commit_msg>add Debug<commit_after>'use strict';

const request = require('request');
const core = require('./../core/core.js');
const TelegramBot = require('node-telegram-bot-api');

/**
 * CREDENTIALS
 **/
const TELEGRAM_ACCESS_TOKEN = process.env.TELEGRAM_ACCESS_TOKEN;

var telegram = new TelegramBot(TELEGRAM_ACCESS_TOKEN, { polling: true });

telegram.on("text", (message) => {
    receivedMessage(message);
    //telegram.sendMessage(message.chat.id, "Hello world");
});

telegram.on("location", (message) => {
    console.log("YEAH");
    receivedMessage(message);
    //telegram.sendMessage(message.chat.id, "Hello world");
});

/*
* Fonction appelé par quand on recoit un message
*/
function receivedMessage(message) {
    console.log(JSON.stringify(message));
    var senderID = message.chat.id;
    var message = {
        channel: "Telegram",
        senderID: senderID,
        timestamp: message.date,
        text: message.text,
        first_name: message.from.first_name,
        last_name: message.from.last_name
    };
    core.receivedMessage(message);
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Facebook
*/
function sendMessage(message) {
    switch(message.type) {
        case "text":
            sendTextMessage(message);
        break;
        case "quickreply":
            sendQuickReplyMessage(message);
        break;
        case "location":
            sendLocationMessage(message);
        break;
        case "template":
            sendTemplateMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Facebook
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        telegram.sendMessage(message.senderID, message.text);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var replykeyboard = {keyboard:[]};
        for(var i=0;i<message.choices.length;i++) {
            var button = [{
                text: message.choices[i]
            }];
            replykeyboard.keyboard.push(button);
        }
        //console.log(JSON.stringify({reply_markup: {keyboard:[[{text:"coucou"}]]}}));
        telegram.sendMessage(message.senderID, message.text, {reply_markup: replykeyboard});
    }
}

/*
* Fonction qui envoie un message de type location
*/
function sendLocationMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var replykeyboard = {keyboard:[], one_time_keyboard:true};
        var button = [{
            text: message.text,
            request_location : true
        }];
        replykeyboard.keyboard.push(button);
        telegram.sendMessage(message.senderID, message.text, {reply_markup: replykeyboard});
    }
}

/*
* Fonction qui envoie un message de type location
*/
function sendTemplateMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.attachment != undefined) {
        var elements = [];
        /*
        *   Envoie du message avant le template
        */
        telegram.sendMessage(message.senderID, message.text);
        for(var i=0;i<message.attachment.length;i++) {
            telegram.sendVenue(message.senderID, message.attachment[i].lat, message.attachment[i].long, message.attachment[i].title, message.attachment[i].subtitle)
            if(i==3)break;
        }
    }
}

function sendTemplateMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var replykeyboard = {keyboard:[], one_time_keyboard:true};
        var button = [{
            text: message.text,
            request_location : true
        }];
        replykeyboard.keyboard.push(button);
        telegram.sendMessage(message.senderID, message.text, {reply_markup: replykeyboard});
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {
    /*console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                attachment:{
                    type: message.type,
                    payload: {
                        url: message.text
                    }
                }
            }
        };
        callSendAPI(messageData);
    }*/
}

exports.sendMessage = sendMessage
exports.sendMessages = sendMessages<|endoftext|>


<commit_before>// basic test
// show that it does the same thing by default as the shell.
var tap = require("tap")
, child_process = require("child_process")

// put more patterns here.
, globs =
  ["test/a/*/+(c|g)/./d"
  ,"test/a/**/[cg]/../[cg]"
  ,"test/a/{b,c,d,e,f}/**/g"
  ,"test/a/b/**"
  ,"test/**/g"
  ,"test/a/abc{fed,def}/g/h"
  ,"test/a/abc{fed/g,def}/**/"
  ,"test/a/abc{fed/g,def}/**///**/"
  ,"test/**/a/**/"
  ,"test/+(a|b|c)/a{/,bc*}/**"
  ,"test/*/*/*/f"
  ,"test/**/f"
  ,"test/a/symlink/a/b/c/a/b/c/a/b/c//a/b/c////a/b/c/**/b/c/**"
  ,"{./*/*,/usr/local/*}"
  ,"{/*,*}" // evil owl face!  how you taunt me!
  ]
, glob = require("../")
, path = require("path")

// run from the root of the project
// this is usually where you're at anyway, but be sure.
process.chdir(path.resolve(__dirname, ".."))

function alphasort (a, b) {
  a = a.toLowerCase()
  b = b.toLowerCase()
  return a > b ? 1 : a < b ? -1 : 0
}

globs.forEach(function (pattern) {
  var echoOutput
  tap.test(pattern, function (t) {
    var bashPattern = pattern //.replace(/(\(|\||\))/g, "\\$1")
    , cmd = "shopt -s globstar && " +
            "shopt -s extglob && " +
            "shopt -s nullglob && " +
            // "shopt >&2; " +
            "eval \'for i in " + bashPattern + "; do echo $i; done\'"
    , cp = child_process.spawn("bash", ["-c",cmd])
    , out = []
    , globResult
    cp.stdout.on("data", function (c) {
      out.push(c)
    })
    cp.stderr.on("data", function (c) {
      process.stderr.write(c)
    })
    cp.on("exit", function () {
      echoOutput = flatten(out)
      if (!echoOutput) echoOutput = []
      else {
        echoOutput = echoOutput.split(/\r*\n/).map(function (m) {
          // Bash is a oddly inconsistent with slashes in the
          // the results.  This implementation is a bit more
          // normalized.  Account for this in the test results.
          return m.replace(/\/+/g, "/").replace(/\/$/, "")
        }).sort(alphasort).reduce(function (set, f) {
          if (f !== set[set.length - 1]) set.push(f)
          return set
        }, [])
      }
      next()
    })

    glob(pattern, function (er, matches) {
      t.ifError(er, pattern + " should not error")
      globResult = matches
      next()
    })

    function next () {
      if (!echoOutput || !globResult) return

      t.deepEqual(globResult, echoOutput, "should match shell")
      t.end()
    }
  })

  tap.test(pattern + " sync", function (t) {
    t.deepEqual(glob.sync(pattern), echoOutput, "should match shell")
    t.end()
  })
})

function flatten (chunks) {
  var s = 0
  chunks.forEach(function (c) { s += c.length })
  var out = new Buffer(s)
  s = 0
  chunks.forEach(function (c) {
    c.copy(out, s)
    s += c.length
  })

  return out.toString().trim()
}
<commit_msg>All sorts of filtering and sorting<commit_after>// basic test
// show that it does the same thing by default as the shell.
var tap = require("tap")
, child_process = require("child_process")

// put more patterns here.
, globs =
  [
  "test/a/*/+(c|g)/./d"
  ,"test/a/**/[cg]/../[cg]"
  ,"test/a/{b,c,d,e,f}/**/g"
  ,"test/a/b/**"
  ,"test/**/g"
  ,"test/a/abc{fed,def}/g/h"
  ,"test/a/abc{fed/g,def}/**/"
  ,"test/a/abc{fed/g,def}/**///**/"
  ,"test/**/a/**/"
  ,"test/+(a|b|c)/a{/,bc*}/**"
  ,"test/*/*/*/f"
  ,"test/**/f"
  ,"test/a/symlink/a/b/c/a/b/c/a/b/c//a/b/c////a/b/c/**/b/c/**"
  ,"{./*/*,/usr/local/*}"
  ,"{/*,*}" // evil owl face!  how you taunt me!
  ]
, glob = require("../")
, path = require("path")

// run from the root of the project
// this is usually where you're at anyway, but be sure.
process.chdir(path.resolve(__dirname, ".."))

function alphasort (a, b) {
  a = a.toLowerCase()
  b = b.toLowerCase()
  return a > b ? 1 : a < b ? -1 : 0
}

globs.forEach(function (pattern) {
  var echoOutput
  tap.test(pattern, function (t) {
    var bashPattern = pattern //.replace(/(\(|\||\))/g, "\\$1")
    , cmd = "shopt -s globstar && " +
            "shopt -s extglob && " +
            "shopt -s nullglob && " +
            // "shopt >&2; " +
            "eval \'for i in " + bashPattern + "; do echo $i; done\'"
    , cp = child_process.spawn("bash", ["-c",cmd])
    , out = []
    , globResult
    cp.stdout.on("data", function (c) {
      out.push(c)
    })
    cp.stderr.on("data", function (c) {
      process.stderr.write(c)
    })
    cp.on("exit", function () {
      echoOutput = flatten(out)
      if (!echoOutput) echoOutput = []
      else {
        echoOutput = echoOutput.split(/\r*\n/).map(function (m) {
          // Bash is a oddly inconsistent with slashes in the
          // the results.  This implementation is a bit more
          // normalized.  Account for this in the test results.
          return m.replace(/\/+/g, "/").replace(/\/$/, "")
        }).sort(alphasort).reduce(function (set, f) {
          if (f !== set[set.length - 1]) set.push(f)
          return set
        }, []).sort(alphasort)
      }
      next()
    })

    glob(pattern, function (er, matches) {
      // sort and unpark, just to match the shell results
      matches = matches.map(function (m) {
        return m.replace(/\/+/g, "/").replace(/\/$/, "")
      }).sort(alphasort).reduce(function (set, f) {
        if (f !== set[set.length - 1]) set.push(f)
        return set
      }, []).sort(alphasort)

      t.ifError(er, pattern + " should not error")
      globResult = matches
      next()
    })

    function next () {
      if (!echoOutput || !globResult) return

      t.deepEqual(globResult, echoOutput, "should match shell")
      t.end()
    }
  })

  tap.test(pattern + " sync", function (t) {
    var matches = glob.sync(pattern).map(function (m) {
        return m.replace(/\/+/g, "/").replace(/\/$/, "")
      }).sort(alphasort).reduce(function (set, f) {
        if (f !== set[set.length - 1]) set.push(f)
        return set
      }, []).sort(alphasort)

    t.deepEqual(matches, echoOutput, "should match shell")
    t.end()
  })
})

function flatten (chunks) {
  var s = 0
  chunks.forEach(function (c) { s += c.length })
  var out = new Buffer(s)
  s = 0
  chunks.forEach(function (c) {
    c.copy(out, s)
    s += c.length
  })

  return out.toString().trim()
}
<|endoftext|>


<commit_before>let Networking = {
  L4LB_ADDRESS: '.marathon.l4lb.thisdcos.directory'
};

module.exports = Networking;
<commit_msg>Add network type constants<commit_after>let Networking = {
  type: {
    BRIDGE: 'BRIDGE',
    HOST: 'HOST',
    USER: 'USER'
  },
  L4LB_ADDRESS: '.marathon.l4lb.thisdcos.directory'
};

module.exports = Networking;
<|endoftext|>


<commit_before>AUI.add('tooltip', function(A) {

var L = A.Lang,
	isString = L.isString,
	isUndefined = L.isUndefined,
	isBoolean = L.isBoolean,

	BL = 'bl',
	TR = 'tr',
	FOCUSED = 'focused',
	CANCEL_HIDE_ON_INTERACTION = 'cancelHideOnInteraction',
	BOUNDING_BOX = 'boundingBox',
	HIDE_DELAY = 'hideDelay',
	BLANK = '',
	ATTR = 'attr',
	TITLE = 'title',
	CURRENT_NODE = 'currentNode',
	SECTION = 'section',
	TRIGGER = 'trigger',
	BODY_CONTENT = 'bodyContent',
	TOOLTIP = 'tooltip';

function Tooltip(config) {
 	Tooltip.superclass.constructor.apply(this, arguments);
}

A.mix(Tooltip, {
	NAME: TOOLTIP,

	ATTRS: {
		align: {
            value: { node: null, points: [ BL, TR ] }
        },

		cancelHideOnInteraction: {
			value: true,
			validador: isBoolean
		},

		showOn: {
			value: 'mouseover'
		},

		hideOn: {
			value: 'mouseout'
		},

		hideDelay: {
			value: 1500
		},

		title: {
			value: false,
			validador: isBoolean
		}
	}
});

A.extend(Tooltip, A.ContextPanel, {
	/*
	* Lifecycle
	*/
	bindUI: function() {
		var instance = this;
		var boudingBox = instance.get(BOUNDING_BOX);

		boudingBox.on('click', A.bind(instance._cancelHideOnInteraction, instance));
		boudingBox.on('mouseenter', A.bind(instance._cancelHideOnInteraction, instance));
		boudingBox.on('mouseleave', A.bind(instance._invokeHideTask, instance));
		instance.after('focusedChange', A.bind(instance._invokeHideTask, instance));
	},

	/*
	* Methods
	*/
	_show: function(event) {
		var instance = this;
		var bodyContent = instance.get(BODY_CONTENT);

		Tooltip.superclass._show.apply(this, arguments);

		if (instance.get(TITLE)) {
			instance._loadBodyContentFromTitle( instance.get(CURRENT_NODE) );
		}
	},

	_loadBodyContentFromTitle: function(currentNode) {
		var instance = this;
		var trigger = instance.get(TRIGGER);

		if (!instance._titles) {
			instance._titles = trigger.attr(TITLE);

			// prevent default browser tooltip for title
			trigger.attr(TITLE, BLANK);
		}

		if (currentNode) {
			var index = trigger.indexOf(currentNode);
			var title = instance._titles[index];

			instance.set(BODY_CONTENT, title);
		}
	},

	_invokeHideTask: function() {
		var instance = this;

		if (!instance.get(FOCUSED)) {
			instance._hideTask.delay( instance.get(HIDE_DELAY) );
		}
	},

	/*
	* Listeners
	*/
	_afterBodyChange: function(e) {
		var instance = this;

		Tooltip.superclass._afterBodyChange.apply(this, arguments);

		instance.refreshAlign();
	},

	// cancel hide if the user does some interaction with the tooltip
	// interaction = focus, mouseover
	_cancelHideOnInteraction: function(event) {
		var instance = this;

		if (instance.get(CANCEL_HIDE_ON_INTERACTION)) {
			instance.clearIntervals();
		}

		event.halt();
	}
});

A.Tooltip = Tooltip;

}, '@VERSION', { requires: [ 'context-panel' ] });<commit_msg>Tooltip overloading .show() method instead _show()<commit_after>AUI.add('tooltip', function(A) {

var L = A.Lang,
	isString = L.isString,
	isUndefined = L.isUndefined,
	isBoolean = L.isBoolean,

	BL = 'bl',
	TR = 'tr',
	FOCUSED = 'focused',
	CANCEL_HIDE_ON_INTERACTION = 'cancelHideOnInteraction',
	BOUNDING_BOX = 'boundingBox',
	HIDE_DELAY = 'hideDelay',
	BLANK = '',
	ATTR = 'attr',
	TITLE = 'title',
	CURRENT_NODE = 'currentNode',
	SECTION = 'section',
	TRIGGER = 'trigger',
	BODY_CONTENT = 'bodyContent',
	TOOLTIP = 'tooltip';

function Tooltip(config) {
 	Tooltip.superclass.constructor.apply(this, arguments);
}

A.mix(Tooltip, {
	NAME: TOOLTIP,

	ATTRS: {
		align: {
            value: { node: null, points: [ BL, TR ] }
        },

		cancelHideOnInteraction: {
			value: true,
			validador: isBoolean
		},

		showOn: {
			value: 'mouseover'
		},

		hideOn: {
			value: 'mouseout'
		},

		hideDelay: {
			value: 1500
		},

		title: {
			value: false,
			validador: isBoolean
		}
	}
});

A.extend(Tooltip, A.ContextPanel, {
	/*
	* Lifecycle
	*/
	bindUI: function() {
		var instance = this;
		var boudingBox = instance.get(BOUNDING_BOX);

		boudingBox.on('click', A.bind(instance._cancelHideOnInteraction, instance));
		boudingBox.on('mouseenter', A.bind(instance._cancelHideOnInteraction, instance));
		boudingBox.on('mouseleave', A.bind(instance._invokeHideTask, instance));
		instance.after('focusedChange', A.bind(instance._invokeHideTask, instance));
	},

	/*
	* Methods
	*/
	show: function() {
		var instance = this;
		var bodyContent = instance.get(BODY_CONTENT);

		Tooltip.superclass.show.apply(instance, arguments);

		if (instance.get(TITLE)) {
			instance._loadBodyContentFromTitle( instance.get(CURRENT_NODE) );
		}
	},

	_loadBodyContentFromTitle: function(currentNode) {
		var instance = this;
		var trigger = instance.get(TRIGGER);

		if (!instance._titles) {
			instance._titles = trigger.attr(TITLE);

			// prevent default browser tooltip for title
			trigger.attr(TITLE, BLANK);
		}

		if (currentNode) {
			var index = trigger.indexOf(currentNode);
			var title = instance._titles[index];

			instance.set(BODY_CONTENT, title);
		}
	},

	_invokeHideTask: function() {
		var instance = this;

		if (!instance.get(FOCUSED)) {
			instance._hideTask.delay( instance.get(HIDE_DELAY) );
		}
	},

	/*
	* Listeners
	*/
	_afterBodyChange: function(e) {
		var instance = this;

		Tooltip.superclass._afterBodyChange.apply(this, arguments);

		instance.refreshAlign();
	},

	// cancel hide if the user does some interaction with the tooltip
	// interaction = focus, mouseover
	_cancelHideOnInteraction: function(event) {
		var instance = this;

		if (instance.get(CANCEL_HIDE_ON_INTERACTION)) {
			instance.clearIntervals();
		}

		event.halt();
	}
});

A.Tooltip = Tooltip;

}, '@VERSION', { requires: [ 'context-panel' ] });<|endoftext|>


<commit_before>// FIXME debug.
var log  = console.log;

(function(){'use strict';

// Iterators.
function each(arr, func){
    for(var idx = 0, len = arr.length; idx < len; idx++){
        if(func(arr[idx], idx) === false) break;
    }
}
function map(arr, func){
    var results = [];
    each(arr, function(item){
        var result = func(item);
        if(typeof result !== 'undefined') results.push(result);
    });
    return results;
}
function eachval(dictionary, func){
    each(Object.keys(dictionary), function(key){
        return func(dictionary[key], key);
    });
}

// A dictionary that holds a sorted array of values.
function SortDict(){
    this.keys = [];
    this.dict = {};
    this.get = function(id){return this.dict[id];};
    this.getbypos = function(pos){return this.dict[this.keys[pos]];};

    function binsearch(arr, val){
        var minidx = 0, maxidx = arr.length - 1, idx;
        while(minidx <= maxidx){
            idx = (minidx + maxidx) / 2 | 0;
            if(arr[idx] < val) minidx = idx + 1;
            else maxidx = idx - 1;
        }
        return minidx;
    }

    this.add = function(id, item){
        if(!this.dict[id]) this.keys.splice(binsearch(this.keys, id), 0, id);
        return this.dict[id] = item;
    };

    this.getor = function(id){return this.get(id) || this.add(id, {});};

    this.each = function(callback){
        each(this.keys, function(key){
            return callback(this.get(key), key);
        }.bind(this));
    };

    this.toarray = function(){
        var arr = [];
        this.each(function(member){
            arr.push(member);
        });
        return arr;
    };
}

// Get that angular magick flowing.
angular.module('otp', []).

// A filter for rendering markdown.
// FIXME Sanitize!
filter('markdown', ['$sce', '$window', function($sce, $window){
    return function(markdown){
        return $sce.trustAsHtml($window.marked(markdown));
    };

// A filter for ordering dictionaries.
}]).filter('dictorderBy', function(){
    return function(dict, key, reverse){
        var sorted = new SortDict();
        eachval(dict, function(value, id){
            sorted.add(value[key], value);
        });
        sorted = sorted.toarray();
        if(reverse) return sorted = sorted.reverse();
        return sorted;
    };

// A secrets service to serve us the server injected secrets.
}).service('secrets', ['$window', '$http', function(
    $window, $http
){
    this.index = new SortDict();
    this.get = function(id){return this.index.get(id);};
    this.keys = function(id){return this.index.keys.slice();};
    this.viewers = {};

    // Add a secret, linking it to its relatives.
    this.add = function(rawsecret){
        var secret = this.index.getor(rawsecret.id);

        secret.service = this;
        secret.id = rawsecret.id;
        secret.time = rawsecret.time;

        secret.author = this.viewers[rawsecret.authorid];
        if(typeof rawsecret.parentid === 'number')
            secret.parent = this.index.getor(rawsecret.parentid);

        secret.children = map(rawsecret.childids, function(childid){
            return this.index.getor(childid);
        }.bind(this));

        secret.viewers = {};
        each(Object.keys(rawsecret.viewers), function(key){
            secret.viewers[key] = map(rawsecret.viewers[key], function(id){
                return this.viewers[id];
            }.bind(this));
        }.bind(this));

        if(typeof rawsecret.body === 'string'){
            secret.body = rawsecret.body;
            secret.view = true;
        // Prepare a function to fetch the unviewed secret from the server.
        }else secret.view = function(callback){
            $http({
                url: '/secrets/' + secret.id,
                method: 'GET',
            }).success(function(data){
                callback(this.service.add(data));
            }.bind(this)).error(function(data){
                console.log('server error:', arguments);
            });
        };
        return secret;
    };

    // Load a bunch of secrets and viewers and such.
    this.load = function(data){
        each(data.rawviewers, function(rawviewer){
            this[rawviewer.id] = rawviewer;
            this[rawviewer.id].lastseen = new Date(rawviewer.lastseen);
        }.bind(this.viewers));
        each(data.rawsecrets, function(rawsecret){
            this.add(rawsecret);
        }.bind(this));
        this.latestsecretid = data.latestsecretid;
    };

    // Update from the server.
    this.update = function(callback){
        $http({
            url: '/secrets',
            method: 'GET',
            params: {afterid: (this.latestsecretid || 0)}
        }).success(function(data){
            this.load(data);
            callback(data);
        }.bind(this)).error(function(data){
            console.log('server error:', arguments);
        });
    };

    // Load the secrets the server injected into the page.
    this.load({
        rawsecrets: $window.rawsecrets,
        rawviewers: $window.rawviewers,
        latestsecretid: $window.latestsecretid
    });

// A controller for displaying threads.
}]).controller('threads', ['$scope', '$interval', 'secrets', function(
    $scope, $interval, secrets
){
    $scope.viewed = [];
    $scope.ripe = [];
    $scope.hidden = [];
    $scope.subs = [];
    $scope.data = {};
    $scope.viewers = secrets.viewers;

    // Create a thread object from a root secret.
    function Thread(rootsecret){
        this.rootsecret = rootsecret;
        this.latestsecretid = this.rootsecret.id;

        // FIXME Replace with something more specific than SortDict?
        this.members = new SortDict();
        this.add = function(members){
            each(members, function(member){
                member.thread = this;
                this.members.add(member.id, member);
                if(member.id > this.latestsecretid){
                    this.latestsecretid = member.id;
                }
            }.bind(this));
        };

        // Get a thread's name.
        this.getname = function(){
            try{
                return this.rootsecret.body.match(/^[^\n]{0,20}($|[\n\s])/)[0];
            }catch(e){
                if(e instanceof TypeError){
                    return this.rootsecret.body.slice(0,19) + '…';
                }else throw e;
            }
        };

        // Get a thread's parent thread, if it exists.
        this.getparent = function(){
            var parent;
            try{
                return this.rootsecret.parent.thread;
            }catch(e){
                if(!e instanceof TypeError) throw e;
                return false;
            }
        }

        // Sort a thread as viewed, ripe, hidden or subthread.
        this.sort = function(){
            var type = 'hidden', parent = null;
            if(this.rootsecret.view === true){
                parent = this.getparent();
                if(parent){
                    type = 'subs';
                    parent.add(this.members.toarray());
                }else{
                    type = 'viewed';
                    this.name = this.getname();
                }
            }else if(this.rootsecret.parent){
                if(this.rootsecret.parent.view === true) type = 'ripe';
                else type = 'hidden';
            }else eachval(
                this.rootsecret.viewers,
                function(viewerslist, secretid){
                    if(secretid <= this.rootsecret.id){
                        if(viewerslist.indexOf(secrets.viewers[uid]) > -1){
                            return (type = 'ripe') && false;
                        }
                    }else{
                        if(secrets.get(secretid).view === true){
                            return (type = 'ripe') && false;
                        }
                    }
                }.bind(this)
            );

            // Move the thread if its type has changed.
            var pos;
            if(!this.type || this.type !== type){
                if(this.type){
                    pos = $scope[this.type].indexOf(this);
                    if(pos > -1) $scope[this.type].splice(pos, 1);
                }
                this.type = type;
                $scope[type].unshift(this);
            }
        };

        // Recursively gather a thread of secrets from a root secret.
        function threadsecrets(secret, isunviewed){
            if(typeof isunviewed === 'undefined'){
                isunviewed = (typeof secret.body === 'undefined');
            }else if((typeof secret.body === 'undefined') !== isunviewed){
                return [];
            }
            var members = [secret];
            each(secret.children, function(child){
                members = members.concat(threadsecrets(child, isunviewed));
            });
            return members;
        }

        // Add all threaded descendants of rootsecret.
        this.add(threadsecrets(this.rootsecret));
        this.sort();

        // Make a flat viewers list.
        // TODO aggregate viewers from all members?
        var viewers = [];
        eachval(this.rootsecret.viewers, function(viewerids){
            each(viewerids, function(viewerid){
                if(viewers.indexOf(viewerid) < 0) viewers.push(viewerid);
            });
        });
        this.viewers = viewers;
    }

    // Request all members of a thread and refresh threads when they arrive.
    $scope.viewthread = function(thread){
        var counter = 0;
        thread.members.each(function(member){
            counter++;
            member.view(function(newmember){
                var target, pos;
                counter--;
                if(counter === 0){
                    thread.sort();
                    each($scope.hidden, function(thread){thread.sort();});
                    $scope.data.activethread = thread.rootsecret.thread;
                }
            });
        });
    };

    // Pull threads out of a checklist of IDs.
    function threadchecklist(checklist){
        while(checklist.length > 0){
            new Thread(secrets.get(checklist.shift())).members.each(
                function(member){
                    var pos = checklist.indexOf(member.id);
                    if(pos > -1) checklist.splice(pos, 1);
                }
            );
        }
    }
    threadchecklist(secrets.keys());
    if($scope.viewed.length > 0) $scope.data.activethread = $scope.viewed[0];
    else $scope.data.activethread = null;

    $scope.getnew = function(callback){
        secrets.update(function(data){
            threadchecklist(map(data.rawsecrets, function(rawsecret){
                return rawsecret.id;
            }));
            if(typeof callback === 'function') callback(data);
        });
    };
    $interval($scope.getnew, 100000);

    // FIXME Some debug binds here.
    window.s = secrets;
    window.v = $scope.viewed;
    window.r = $scope.ripe;
    window.h = $scope.hidden;

    // FIXME find me a place.
    $scope.nojsstyle = 'display: none';

// A controller for composing secrets.
}]).controller('composer', ['$scope', '$http', 'secrets', function(
    $scope, $http, secrets
){
    // FIXME directivise this shit. Or maybe just let G do it properly.
    $scope.authparents = [];
    $scope.addauthparent = function(){
        $scope.authparents.push($scope.authparentid);
        $scope.authparentid = '';
    };

    $scope.authchildren = [];
    $scope.addauthchild = function(){
        $scope.authchildren.push($scope.authchildid);
        $scope.authchildid = '';
    };

    $scope.viewers = [];
    $scope.addviewer = function(){
        $scope.viewers.push($scope.viewerid);
        $scope.viewerid = '';
    };

    $scope.post = function(){
        $http({
            url: '/post',
            method: 'POST',
            params: {
                body: $scope.body,
                parentid: $scope.parentid,
                'authparentids[]': $scope.authparents,
                'authchildids[]': $scope.authchildren,
                'viewerids[]': $scope.viewers

            }
        }).success(function(data){
            $scope.body = '';
            $scope.parentid = '';
            $scope.authparents = [];
            $scope.authchildren = [];
            $scope.viewers = [];
            $scope.getnew(function(){
                $scope.data.activethread = secrets.get(this).thread;
            }.bind(data));
        }).error(function(data){
            console.log('server error:', arguments);
        });
    };
}]);

}());
<commit_msg>Bugfix mark child's legitimacy ASAP, better sort.<commit_after>// FIXME debug.
var log  = console.log;

(function(){'use strict';

// Iterators.
function each(arr, func){
    for(var idx = 0, len = arr.length; idx < len; idx++){
        if(func(arr[idx], idx) === false) break;
    }
}
function map(arr, func){
    var results = [];
    each(arr, function(item){
        var result = func(item);
        if(typeof result !== 'undefined') results.push(result);
    });
    return results;
}
function eachval(dictionary, func){
    each(Object.keys(dictionary), function(key){
        return func(dictionary[key], key);
    });
}

// A dictionary that holds a sorted array of values.
function SortDict(){
    this.keys = [];
    this.dict = {};
    this.get = function(id){return this.dict[id];};
    this.getbypos = function(pos){return this.dict[this.keys[pos]];};

    function binsearch(arr, val){
        var minidx = 0, maxidx = arr.length - 1, idx;
        while(minidx <= maxidx){
            idx = (minidx + maxidx) / 2 | 0;
            if(arr[idx] < val) minidx = idx + 1;
            else maxidx = idx - 1;
        }
        return minidx;
    }

    this.add = function(id, item){
        if(!this.dict[id]) this.keys.splice(binsearch(this.keys, id), 0, id);
        return this.dict[id] = item;
    };

    this.getor = function(id){return this.get(id) || this.add(id, {});};

    this.each = function(callback){
        each(this.keys, function(key){
            return callback(this.get(key), key);
        }.bind(this));
    };

    this.toarray = function(){
        var arr = [];
        this.each(function(member){
            arr.push(member);
        });
        return arr;
    };
}

// Get that angular magick flowing.
angular.module('otp', []).

// A filter for rendering markdown.
// FIXME Sanitize!
filter('markdown', ['$sce', '$window', function($sce, $window){
    return function(markdown){
        return $sce.trustAsHtml($window.marked(markdown));
    };

// A filter for ordering dictionaries.
}]).filter('dictorderBy', function(){
    return function(dict, key, reverse){
        var sorted = new SortDict();
        eachval(dict, function(value, id){
            sorted.add(value[key], value);
        });
        sorted = sorted.toarray();
        if(reverse) return sorted = sorted.reverse();
        return sorted;
    };

// A secrets service to serve us the server injected secrets.
}).service('secrets', ['$window', '$http', function(
    $window, $http
){
    this.index = new SortDict();
    this.get = function(id){return this.index.get(id);};
    this.keys = function(id){return this.index.keys.slice();};
    this.viewers = {};

    // Add a secret, linking it to its relatives.
    this.add = function(rawsecret){
        var secret = this.index.getor(rawsecret.id);

        secret.service = this;
        secret.id = rawsecret.id;
        secret.time = rawsecret.time;
        secret.author = this.viewers[rawsecret.authorid];

        secret.viewers = {};
        each(Object.keys(rawsecret.viewers), function(key){
            secret.viewers[key] = map(rawsecret.viewers[key], function(id){
                return this.viewers[id];
            }.bind(this));
        }.bind(this));

        if(typeof rawsecret.parentid === 'number'){
            secret.parent = this.index.getor(rawsecret.parentid);
            if(
                secret.viewers[secret.id].length === 1 &&
                secret.viewers[secret.parent.id]
            ) secret.legitimate = true;
            else secret.legitimate = false;
        }

        secret.children = map(rawsecret.childids, function(childid){
            return this.index.getor(childid);
        }.bind(this));

        if(typeof rawsecret.body === 'string'){
            secret.body = rawsecret.body;
            secret.view = true;
        // Prepare a function to fetch the unviewed secret from the server.
        }else secret.view = function(callback){
            $http({
                url: '/secrets/' + secret.id,
                method: 'GET',
            }).success(function(data){
                callback(this.service.add(data));
            }.bind(this)).error(function(data){
                console.log('server error:', arguments);
            });
        };
        return secret;
    };

    // Load a bunch of secrets and viewers and such.
    this.load = function(data){
        each(data.rawviewers, function(rawviewer){
            this[rawviewer.id] = rawviewer;
            this[rawviewer.id].lastseen = new Date(rawviewer.lastseen);
        }.bind(this.viewers));
        each(data.rawsecrets, function(rawsecret){
            this.add(rawsecret);
        }.bind(this));
        this.latestsecretid = data.latestsecretid;
    };

    // Update from the server.
    this.update = function(callback){
        $http({
            url: '/secrets',
            method: 'GET',
            params: {afterid: (this.latestsecretid || 0)}
        }).success(function(data){
            this.load(data);
            callback(data);
        }.bind(this)).error(function(data){
            console.log('server error:', arguments);
        });
    };

    // Load the secrets the server injected into the page.
    this.load({
        rawsecrets: $window.rawsecrets,
        rawviewers: $window.rawviewers,
        latestsecretid: $window.latestsecretid
    });

// A controller for displaying threads.
}]).controller('threads', ['$scope', '$interval', 'secrets', function(
    $scope, $interval, secrets
){
    $scope.viewed = [];
    $scope.ripe = [];
    $scope.hidden = [];
    $scope.subs = [];
    $scope.data = {};
    $scope.viewers = secrets.viewers;

    // Create a thread object from a root secret.
    function Thread(rootsecret){
        this.rootsecret = rootsecret;
        this.latestsecretid = this.rootsecret.id;

        // FIXME Replace with something more specific than SortDict?
        this.members = new SortDict();
        this.add = function(members){
            each(members, function(member){
                member.thread = this;
                this.members.add(member.id, member);
                if(member.id > this.latestsecretid){
                    this.latestsecretid = member.id;
                }
            }.bind(this));
        };

        // Get a thread's name.
        this.getname = function(){
            try{
                return this.rootsecret.body.match(/^[^\n]{0,20}($|[\n\s])/)[0];
            }catch(e){
                if(e instanceof TypeError){
                    return this.rootsecret.body.slice(0,19) + '…';
                }else throw e;
            }
        };

        // Get a thread's parent thread, if it exists.
        this.getparent = function(){
            var parent;
            try{
                return this.rootsecret.parent.thread;
            }catch(e){
                if(!e instanceof TypeError) throw e;
                return false;
            }
        }

        // Sort a thread as viewed, ripe, hidden or subthread.
        this.sort = function(){
            var type = 'hidden', parent = null;
            if(this.rootsecret.view === true){
                parent = this.getparent();
                if(parent && this.rootsecret.legitimate){
                    type = 'subs';
                    parent.add(this.members.toarray());
                }else{
                    type = 'viewed';
                    this.name = this.getname();
                }
            }else if(
                this.rootsecret.parent &&
                this.rootsecret.parent.view === true
            ) type = 'ripe';
            else eachval(
                this.rootsecret.viewers,
                function(viewerslist, secretid){
                    if(secretid <= this.rootsecret.id){
                        if(viewerslist.indexOf(secrets.viewers[uid]) > -1){
                            return (type = 'ripe') && false;
                        }
                    }else{
                        if(secrets.get(secretid).view === true){
                            return (type = 'ripe') && false;
                        }
                    }
                }.bind(this)
            );

            // Move the thread if its type has changed.
            var pos;
            if(!this.type || this.type !== type){
                if(this.type){
                    pos = $scope[this.type].indexOf(this);
                    if(pos > -1) $scope[this.type].splice(pos, 1);
                }
                this.type = type;
                $scope[type].unshift(this);
            }
        };

        // Recursively gather a thread of secrets from a root secret.
        function threadsecrets(secret, isunviewed){
            if(typeof isunviewed === 'undefined'){
                isunviewed = (typeof secret.body === 'undefined');
            }else if((typeof secret.body === 'undefined') !== isunviewed){
                return [];
            }
            var members = [secret];
            each(secret.children, function(child){
                if(child.legitimate) members = members.concat(
                    threadsecrets(child, isunviewed)
                );
            });
            return members;
        }

        // Add all threaded descendants of rootsecret.
        this.add(threadsecrets(this.rootsecret));
        this.sort();

        // Make a flat viewers list.
        // TODO aggregate viewers from all members?
        var viewers = [];
        eachval(this.rootsecret.viewers, function(viewerids){
            each(viewerids, function(viewerid){
                if(viewers.indexOf(viewerid) < 0) viewers.push(viewerid);
            });
        });
        this.viewers = viewers;
    }

    // Request all members of a thread and refresh threads when they arrive.
    $scope.viewthread = function(thread){
        var counter = 0;
        thread.members.each(function(member){
            counter++;
            member.view(function(newmember){
                var target, pos;
                counter--;
                if(counter === 0){
                    thread.sort();
                    each($scope.hidden, function(thread){thread.sort();});
                    $scope.data.activethread = thread.rootsecret.thread;
                }
            });
        });
    };

    // Pull threads out of a checklist of IDs.
    function threadchecklist(checklist){
        while(checklist.length > 0){
            new Thread(secrets.get(checklist.shift())).members.each(
                function(member){
                    var pos = checklist.indexOf(member.id);
                    if(pos > -1) checklist.splice(pos, 1);
                }
            );
        }
    }
    threadchecklist(secrets.keys());
    if($scope.viewed.length > 0) $scope.data.activethread = $scope.viewed[0];
    else $scope.data.activethread = null;

    $scope.getnew = function(callback){
        secrets.update(function(data){
            threadchecklist(map(data.rawsecrets, function(rawsecret){
                return rawsecret.id;
            }));
            if(typeof callback === 'function') callback(data);
        });
    };
    $interval($scope.getnew, 100000);

    // FIXME Some debug binds here.
    window.s = secrets;
    window.v = $scope.viewed;
    window.r = $scope.ripe;
    window.h = $scope.hidden;

    // FIXME find me a place.
    $scope.nojsstyle = 'display: none';

// A controller for composing secrets.
}]).controller('composer', ['$scope', '$http', 'secrets', function(
    $scope, $http, secrets
){
    // FIXME directivise this shit. Or maybe just let G do it properly.
    $scope.authparents = [];
    $scope.addauthparent = function(){
        $scope.authparents.push($scope.authparentid);
        $scope.authparentid = '';
    };

    $scope.authchildren = [];
    $scope.addauthchild = function(){
        $scope.authchildren.push($scope.authchildid);
        $scope.authchildid = '';
    };

    $scope.viewers = [];
    $scope.addviewer = function(){
        $scope.viewers.push($scope.viewerid);
        $scope.viewerid = '';
    };

    $scope.post = function(){
        $http({
            url: '/post',
            method: 'POST',
            params: {
                body: $scope.body,
                parentid: $scope.parentid,
                'authparentids[]': $scope.authparents,
                'authchildids[]': $scope.authchildren,
                'viewerids[]': $scope.viewers

            }
        }).success(function(data){
            $scope.body = '';
            $scope.parentid = '';
            $scope.authparents = [];
            $scope.authchildren = [];
            $scope.viewers = [];
            $scope.getnew(function(){
                $scope.data.activethread = secrets.get(this).thread;
            }.bind(data));
        }).error(function(data){
            console.log('server error:', arguments);
        });
    };
}]);

}());
<|endoftext|>


<commit_before>var types = require("hap-nodejs/accessories/types.js");
var TellduAPI = require("telldus-live");

function TelldusLivePlatform(log, config) {
    var that = this;
    that.log = log;

    that.isLoggedIn = false;

    // Login to Telldus Live!
    that.cloud = new TellduAPI.TelldusAPI({publicKey: config["public_key"], privateKey: config["private_key"]})
        .login(config["token"], config["token_secret"], function(err, user) {
            if (!!err) that.log("Login error: " + err.message);
            that.log("User logged in: " + user.firstname + " " + user.lastname + ", " + user.email);
            that.isLoggedIn = true;
        }
    );
}

TelldusLivePlatform.prototype = {

    accessories: function(callback) {
        var that = this;

        that.log("Fetching devices...");

        that.cloud.getDevices(function(err, devices) {

            if (!!err) return that.log('getDevices: ' + err.message);

            var foundAccessories = [];

            // Clean non device
            for (var i = 0; i < devices.length; i++) {
                if (devices[i].type != 'device') {
                    devices.splice(i, 1);
                }
            }

            for (var i = 0; i < devices.length; i++) {
                if (devices[i].type === 'device') {
                    TelldusLiveAccessory.create(that.log, devices[i], that.cloud, function(err, accessory) {
                        if (!!err) that.log("Couldn't load device info");
                        foundAccessories.push(accessory);
                        if (foundAccessories.length >= devices.length) {
                            callback(foundAccessories);
                        }
                    });
                }
            }

        });
    }
};

var TelldusLiveAccessory = function TelldusLiveAccessory(log, cloud, device) {

    this.log   = log;
    this.cloud = cloud;

    var m = device.model.split(':');

    // Set accessory info
    this.device         = device;
    this.id             = device.id;
    this.name           = device.name;
    this.manufacturer   = m[1];
    this.model          = m[0];
    this.state          = device.state;
    this.stateValue     = device.stateValue;
    this.status         = device.status;
};

TelldusLiveAccessory.create = function (log, device, cloud, callback) {

    cloud.getDeviceInfo(device, function(err, device) {

        if (!!err) that.log("Couldn't load device info");

        callback(err, new TelldusLiveAccessory(log, cloud, device));
    });
};

TelldusLiveAccessory.prototype = {

    dimmerValue: function() {

        if (this.state === 1) {
            return 100;
        }

        if (this.state === 16 && this.stateValue != "unde") {
            return parseInt(this.stateValue * 100 / 255);
        }

        return 0;
    },

    informationCharacteristics: function() {
        var that = this;

        informationCharacteristics = [
            {
                cType: types.NAME_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.name,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Name of the accessory",
                designedMaxLength: 255
            },{
                cType: types.MANUFACTURER_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.manufacturer,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Manufacturer",
                designedMaxLength: 255
            },{
                cType: types.MODEL_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.model,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Model",
                designedMaxLength: 255
            },{
                cType: types.SERIAL_NUMBER_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: "A1S2NASF88EW",
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "SN",
                designedMaxLength: 255
            },{
                cType: types.IDENTIFY_CTYPE,
                onUpdate: function () {
                    that.cloud.onOffDevice(that.device, true, function(err, result) {
                        if (!!err) that.log("Error: " + err.message);
                        that.cloud.onOffDevice(that.device, false, function(err, result) {
                            if (!!err) that.log("Error: " + err.message);
                            that.cloud.onOffDevice(that.device, true, function(err, result) {
                                if (!!err) that.log("Error: " + err.message);
                                that.cloud.onOffDevice(that.device, false, function(err, result) {
                                    if (!!err) that.log("Error: " + err.message);
                                    that.cloud.onOffDevice(that.device, true, function(err, result) {
                                        if (!!err) that.log("Error: " + err.message);
                                    })
                                })
                            })
                        })
                    })
                },
                perms: ["pw"],
                format: "bool",
                initialValue: false,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Identify Accessory",
                designedMaxLength: 1
            }
        ];
        return informationCharacteristics;
    },

    controlCharacteristics: function() {
        var that = this;

        cTypes = [{
            cType: types.NAME_CTYPE,
            onUpdate: null,
            perms: ["pr"],
            format: "string",
            initialValue: that.name,
            supportEvents: true,
            supportBonjour: false,
            manfDescription: "Name of service",
            designedMaxLength: 255
        }]

        cTypes.push({
            cType: types.POWER_STATE_CTYPE,
            onUpdate: function(value) {
                if (value == 1) {
                    that.cloud.onOffDevice(that.device, value, function(err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message)
                        } else {
                            that.log(that.name + " - Updated power state: " + (value === true ? 'ON' : 'OFF'));
                        }
                    });
                } else {
                    that.cloud.onOffDevice(that.device, value, function(err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message)
                        } else {
                            that.log(that.name + " - Updated power state: " + (value === true ? 'ON' : 'OFF'));
                        }
                    });
                }
            },
            perms: ["pw","pr","ev"],
            format: "bool",
            initialValue: (that.state != 2 && (that.state === 16 && that.stateValue != "0")) ? 1 : 0,
            supportEvents: true,
            supportBonjour: false,
            manfDescription: "Change the power state",
            designedMaxLength: 1
        })

        if (that.model === "selflearning-dimmer") {
            cTypes.push({
                cType: types.BRIGHTNESS_CTYPE,
                onUpdate: function (value) {
                    that.cloud.dimDevice(that.device, (255 * (value / 100)), function (err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message);
                        } else {
                            that.log(that.name + " - Updated brightness: " + value);
                        }
                    });
                },
                perms: ["pw", "pr", "ev"],
                format: "int",
                initialValue: that.dimmerValue(),
                supportEvents: true,
                supportBonjour: false,
                manfDescription: "Adjust Brightness of Light",
                designedMinValue: 0,
                designedMaxValue: 100,
                designedMinStep: 1,
                unit: "%"
            })
        }

        return cTypes
    },

    getServices: function() {

        var services = [
            {
                sType: types.ACCESSORY_INFORMATION_STYPE,
                characteristics: this.informationCharacteristics()
            },
            {
                sType: types.LIGHTBULB_STYPE,
                characteristics: this.controlCharacteristics()
            }
        ];

        return services;
    }
};

module.exports.platform = TelldusLivePlatform;
module.exports.accessory = TelldusLiveAccessory;<commit_msg>Handle where no model is returned from Telldus Live<commit_after>var types = require("hap-nodejs/accessories/types.js");
var TellduAPI = require("telldus-live");

function TelldusLivePlatform(log, config) {
    var that = this;
    that.log = log;

    that.isLoggedIn = false;

    // Login to Telldus Live!
    that.cloud = new TellduAPI.TelldusAPI({publicKey: config["public_key"], privateKey: config["private_key"]})
        .login(config["token"], config["token_secret"], function(err, user) {
            if (!!err) that.log("Login error: " + err.message);
            that.log("User logged in: " + user.firstname + " " + user.lastname + ", " + user.email);
            that.isLoggedIn = true;
        }
    );
}

TelldusLivePlatform.prototype = {

    accessories: function(callback) {
        var that = this;

        that.log("Fetching devices...");

        that.cloud.getDevices(function(err, devices) {

            if (!!err) return that.log('getDevices: ' + err.message);

            var foundAccessories = [];

            // Clean non device
            for (var i = 0; i < devices.length; i++) {
                if (devices[i].type != 'device') {
                    devices.splice(i, 1);
                }
            }

            for (var i = 0; i < devices.length; i++) {
                if (devices[i].type === 'device') {
                    TelldusLiveAccessory.create(that.log, devices[i], that.cloud, function(err, accessory) {
                        if (!!err) that.log("Couldn't load device info");
                        foundAccessories.push(accessory);
                        if (foundAccessories.length >= devices.length) {
                            callback(foundAccessories);
                        }
                    });
                }
            }

        });
    }
};

var TelldusLiveAccessory = function TelldusLiveAccessory(log, cloud, device) {

    this.log   = log;
    this.cloud = cloud;

    var m = device.model ? device.model.split(':') : ['unknown', 'unknown'] ;

    // Set accessory info
    this.device         = device;
    this.id             = device.id;
    this.name           = device.name;
    this.manufacturer   = m[1];
    this.model          = m[0];
    this.state          = device.state;
    this.stateValue     = device.stateValue;
    this.status         = device.status;
};

TelldusLiveAccessory.create = function (log, device, cloud, callback) {

    cloud.getDeviceInfo(device, function(err, device) {

        if (!!err) that.log("Couldn't load device info");

        callback(err, new TelldusLiveAccessory(log, cloud, device));
    });
};

TelldusLiveAccessory.prototype = {

    dimmerValue: function() {

        if (this.state === 1) {
            return 100;
        }

        if (this.state === 16 && this.stateValue != "unde") {
            return parseInt(this.stateValue * 100 / 255);
        }

        return 0;
    },

    informationCharacteristics: function() {
        var that = this;

        informationCharacteristics = [
            {
                cType: types.NAME_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.name,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Name of the accessory",
                designedMaxLength: 255
            },{
                cType: types.MANUFACTURER_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.manufacturer,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Manufacturer",
                designedMaxLength: 255
            },{
                cType: types.MODEL_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.model,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Model",
                designedMaxLength: 255
            },{
                cType: types.SERIAL_NUMBER_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: "A1S2NASF88EW",
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "SN",
                designedMaxLength: 255
            },{
                cType: types.IDENTIFY_CTYPE,
                onUpdate: function () {
                    that.cloud.onOffDevice(that.device, true, function(err, result) {
                        if (!!err) that.log("Error: " + err.message);
                        that.cloud.onOffDevice(that.device, false, function(err, result) {
                            if (!!err) that.log("Error: " + err.message);
                            that.cloud.onOffDevice(that.device, true, function(err, result) {
                                if (!!err) that.log("Error: " + err.message);
                                that.cloud.onOffDevice(that.device, false, function(err, result) {
                                    if (!!err) that.log("Error: " + err.message);
                                    that.cloud.onOffDevice(that.device, true, function(err, result) {
                                        if (!!err) that.log("Error: " + err.message);
                                    })
                                })
                            })
                        })
                    })
                },
                perms: ["pw"],
                format: "bool",
                initialValue: false,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Identify Accessory",
                designedMaxLength: 1
            }
        ];
        return informationCharacteristics;
    },

    controlCharacteristics: function() {
        var that = this;

        cTypes = [{
            cType: types.NAME_CTYPE,
            onUpdate: null,
            perms: ["pr"],
            format: "string",
            initialValue: that.name,
            supportEvents: true,
            supportBonjour: false,
            manfDescription: "Name of service",
            designedMaxLength: 255
        }]

        cTypes.push({
            cType: types.POWER_STATE_CTYPE,
            onUpdate: function(value) {
                if (value == 1) {
                    that.cloud.onOffDevice(that.device, value, function(err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message)
                        } else {
                            that.log(that.name + " - Updated power state: " + (value === true ? 'ON' : 'OFF'));
                        }
                    });
                } else {
                    that.cloud.onOffDevice(that.device, value, function(err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message)
                        } else {
                            that.log(that.name + " - Updated power state: " + (value === true ? 'ON' : 'OFF'));
                        }
                    });
                }
            },
            perms: ["pw","pr","ev"],
            format: "bool",
            initialValue: (that.state != 2 && (that.state === 16 && that.stateValue != "0")) ? 1 : 0,
            supportEvents: true,
            supportBonjour: false,
            manfDescription: "Change the power state",
            designedMaxLength: 1
        })

        if (that.model === "selflearning-dimmer") {
            cTypes.push({
                cType: types.BRIGHTNESS_CTYPE,
                onUpdate: function (value) {
                    that.cloud.dimDevice(that.device, (255 * (value / 100)), function (err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message);
                        } else {
                            that.log(that.name + " - Updated brightness: " + value);
                        }
                    });
                },
                perms: ["pw", "pr", "ev"],
                format: "int",
                initialValue: that.dimmerValue(),
                supportEvents: true,
                supportBonjour: false,
                manfDescription: "Adjust Brightness of Light",
                designedMinValue: 0,
                designedMaxValue: 100,
                designedMinStep: 1,
                unit: "%"
            })
        }

        return cTypes
    },

    getServices: function() {

        var services = [
            {
                sType: types.ACCESSORY_INFORMATION_STYPE,
                characteristics: this.informationCharacteristics()
            },
            {
                sType: types.LIGHTBULB_STYPE,
                characteristics: this.controlCharacteristics()
            }
        ];

        return services;
    }
};

module.exports.platform = TelldusLivePlatform;
module.exports.accessory = TelldusLiveAccessory;<|endoftext|>


<commit_before>Ext4.onReady(function() {
    if (Densa.defaultButton && Densa.defaultButton.Add) {
        Densa.defaultButton.Add.prototype.defaultText = trlKwf('Add');
    }
    if (Densa.defaultButton && Densa.defaultButton.Delete) {
        Densa.defaultButton.Delete.prototype.defaultText = trlKwf('Delete');
    }
    if (Densa.defaultButton && Densa.defaultButton.ExportCsv) {
        Densa.defaultButton.ExportCsv.prototype.defaultText = trlKwf('Export CSV');
    }
    if (Densa.defaultButton && Densa.defaultButton.Save) {
        Densa.defaultButton.Save.prototype.defaultText = trlKwf('Save');
    }
    if (Densa.editWindow && Densa.editWindow.Window) {
        Densa.editWindow.Window.prototype.saveText = trlKwf('Save');
        Densa.editWindow.Window.prototype.deleteText = trlKwf('Delete');
        Densa.editWindow.Window.prototype.cancelText = trlKwf('Cancel');
        Densa.editWindow.Window.prototype.closeText = trlKwf('Close');
    }
    if (Densa.editWindow && Densa.editWindow.WindowController) {
        Densa.editWindow.WindowController.prototype.addTitle = trlKwf('Add');
        Densa.editWindow.WindowController.prototype.editTitle = trlKwf('Edit');
        Densa.editWindow.WindowController.prototype.saveChangesTitle = trlKwf('Save');
        Densa.editWindow.WindowController.prototype.saveChangesMsg = trlKwf('Do you want to save the changes?');
        Densa.editWindow.WindowController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.editWindow.WindowController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
    }
    if (Densa.form && Densa.form.PanelController) {
        Densa.form.PanelController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.form.PanelController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
        Densa.form.PanelController.prototype.saveValidateErrorTitle = trlKwf('Save');
        Densa.form.PanelController.prototype.saveValidateErrorMsg = trlKwf("Can't save, please fill all red underlined fields correctly.");
        Densa.form.PanelController.prototype.validatingMaskText = trlKwf("Validating...");
    }
    if (Densa.grid && Densa.grid.PanelController) {
        Densa.grid.PanelController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.grid.PanelController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
        Densa.grid.PanelController.prototype.exportProgressTitle = trlKwf('Export');
        Densa.grid.PanelController.prototype.exportProgressMsg = trlKwf('Exporting rows...');

    }
    if (Densa.mvc && Densa.mvc.bindable && Densa.mvc.bindable.ViewController) {
        Densa.mvc.bindable.ViewController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.mvc.bindable.ViewController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
    }
    if (Densa.grid && Densa.grid.controller && Densa.grid.controller.Bind) {
        Densa.grid.controller.Bind.prototype.saveChangesTitle = trlKwf('Save');
        Densa.grid.controller.Bind.prototype.saveChangesMsg = trlKwf('Do you want to save the changes?');
    }
    if (Densa.overrides && Densa.overrides.ComboBox) {
        Densa.overrides.ComboBox.prototype.defaultEmptyText = trlKwf('no selection');
    }

});
<commit_msg>Add translation for Worksheet<commit_after>Ext4.onReady(function() {
    if (Densa.defaultButton && Densa.defaultButton.Add) {
        Densa.defaultButton.Add.prototype.defaultText = trlKwf('Add');
    }
    if (Densa.defaultButton && Densa.defaultButton.Delete) {
        Densa.defaultButton.Delete.prototype.defaultText = trlKwf('Delete');
    }
    if (Densa.defaultButton && Densa.defaultButton.ExportCsv) {
        Densa.defaultButton.ExportCsv.prototype.defaultText = trlKwf('Export CSV');
    }
    if (Densa.defaultButton && Densa.defaultButton.Save) {
        Densa.defaultButton.Save.prototype.defaultText = trlKwf('Save');
    }
    if (Densa.editWindow && Densa.editWindow.Window) {
        Densa.editWindow.Window.prototype.saveText = trlKwf('Save');
        Densa.editWindow.Window.prototype.deleteText = trlKwf('Delete');
        Densa.editWindow.Window.prototype.cancelText = trlKwf('Cancel');
        Densa.editWindow.Window.prototype.closeText = trlKwf('Close');
    }
    if (Densa.editWindow && Densa.editWindow.WindowController) {
        Densa.editWindow.WindowController.prototype.addTitle = trlKwf('Add');
        Densa.editWindow.WindowController.prototype.editTitle = trlKwf('Edit');
        Densa.editWindow.WindowController.prototype.saveChangesTitle = trlKwf('Save');
        Densa.editWindow.WindowController.prototype.saveChangesMsg = trlKwf('Do you want to save the changes?');
        Densa.editWindow.WindowController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.editWindow.WindowController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
    }
    if (Densa.form && Densa.form.PanelController) {
        Densa.form.PanelController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.form.PanelController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
        Densa.form.PanelController.prototype.saveValidateErrorTitle = trlKwf('Save');
        Densa.form.PanelController.prototype.saveValidateErrorMsg = trlKwf("Can't save, please fill all red underlined fields correctly.");
        Densa.form.PanelController.prototype.validatingMaskText = trlKwf("Validating...");
    }
    if (Densa.grid && Densa.grid.PanelController) {
        Densa.grid.PanelController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.grid.PanelController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
        Densa.grid.PanelController.prototype.exportProgressTitle = trlKwf('Export');
        Densa.grid.PanelController.prototype.exportProgressMsg = trlKwf('Exporting rows...');
        Densa.grid.PanelController.prototype.excelExportWorksheetName = trlKwf("Worksheet");
    }
    if (Densa.mvc && Densa.mvc.bindable && Densa.mvc.bindable.ViewController) {
        Densa.mvc.bindable.ViewController.prototype.deleteConfirmTitle = trlKwf('Delete');
        Densa.mvc.bindable.ViewController.prototype.deleteConfirmText = trlKwf('Do you really wish to remove this entry?');
    }
    if (Densa.grid && Densa.grid.controller && Densa.grid.controller.Bind) {
        Densa.grid.controller.Bind.prototype.saveChangesTitle = trlKwf('Save');
        Densa.grid.controller.Bind.prototype.saveChangesMsg = trlKwf('Do you want to save the changes?');
    }
    if (Densa.overrides && Densa.overrides.ComboBox) {
        Densa.overrides.ComboBox.prototype.defaultEmptyText = trlKwf('no selection');
    }

});
<|endoftext|>


<commit_before>var nacl = (typeof window !== 'undefined') ? window.nacl : require('../../' + (process.env.NACL_SRC || 'nacl.min.js'));
var helpers = (typeof require !== 'undefined') ? require('./helpers') : window.helpers;
var log = helpers.log;

if (!nacl) throw new Error('nacl not loaded');

function benchmark(fn, bytes, num) {
  if (!num) num = 100;
  var start = new Date();
  for (var i = 0; i < num; i++) fn();
  var elapsed = (new Date()) - start;
  log.print(' ' + ((bytes*num/1024/1024*1000)/elapsed).toFixed(3), 'MB/s');
  log.print(' ' + ((num*1000)/elapsed).toFixed(3), 'ops/s');
}

function benchmarkOps(fn,  num) {
  var start = new Date();
  for (var i = 0; i < num; i++) {
    fn();
  }
  var elapsed = (new Date()) - start;
  log.print(' ' + ((num*1000)/elapsed).toFixed(3), 'ops/s');
}

function crypto_stream_xor_benchmark() {
  log.start('Benchmarking crypto_stream_xor');
  var m = new Uint8Array(1024),
      n = new Uint8Array(24),
      k = new Uint8Array(32),
      out = new Uint8Array(1024);
  for (i = 0; i < 1024; i++) m[i] = i & 255;
  for (i = 0; i < 24; i++) n[i] = i;
  for (i = 0; i < 32; i++) k[i] = i;
  benchmark(function(){
    nacl.lowlevel.crypto_stream_xor(out, 0, m, 0, m.length, n, k);
  }, m.length);
}

function crypto_onetimeauth_benchmark() {
  log.start('Benchmarking crypto_onetimeauth');
  var m = new Uint8Array(1024),
      out = new Uint8Array(1024),
      k = new Uint8Array([0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1]);
  for (i = 0; i < 1024; i++) {
    m[i] = i & 255;
  }
  benchmark(function(){
    nacl.lowlevel.crypto_onetimeauth(out, 0, m, 0, m.length, k);
  }, m.length);
}

function crypto_secretbox_benchmark() {
  log.start('Benchmarking crypto_secretbox');
  var i, k = new Uint8Array(32), n = new Uint8Array(24),
      m = new Uint8Array(1024), c = new Uint8Array(1024);
  for (i = 0; i < 32; i++) k[i] = 1;
  for (i = 0; i < 24; i++) n[i] = 2;
  for (i = 0; i < 1024; i++) m[i] = 3;
  benchmark(function() {
    nacl.lowlevel.crypto_secretbox(c, m, m.length, n, k);
  }, m.length);
}

function secretbox_seal_open_benchmark() {
  var key = new Uint8Array(32),
      nonce = new Uint8Array(24),
      msg = new Uint8Array(1024),
      box, i;
  for (i = 0; i < 32; i++) key[i] = 1;
  for (i = 0; i < 24; i++) nonce[i] = 2;
  for (i = 0; i < 1024; i++) msg[i] = 3;

  log.start('Benchmarking secretbox');
  benchmark(function() {
    box = nacl.secretbox(msg, nonce, key);
  }, msg.length);
  log.start('Benchmarking secretbox.open');
  benchmark(function() {
    nacl.secretbox.open(box, nonce, key);
  }, msg.length);
}

function crypto_scalarmult_base_benchmark() {
  log.start('Benchmarking crypto_scalarmult_base');
  var n = new Uint8Array(32), q = new Uint8Array(32);
  for (var i = 0; i < 32; i++) n[i] = i;
  benchmarkOps(function() {
    nacl.lowlevel.crypto_scalarmult_base(q, n);
  }, 10);
}

function box_seal_open_benchmark() {
  var pk1 = new Uint8Array(32), sk1 = new Uint8Array(32),
      pk2 = new Uint8Array(32), sk2 = new Uint8Array(32);
  nacl.lowlevel.crypto_box_keypair(pk1, sk1);
  nacl.lowlevel.crypto_box_keypair(pk2, sk2);
  var nonce = nacl.util.decodeUTF8('123456789012345678901234');
  var msg = nacl.util.decodeUTF8((new Array(1024)).join('a'));
  var box = null;
  log.start('Benchmarking box');
  benchmark(function() {
    box = nacl.box(msg, nonce, pk1, sk2);
  }, msg.length, 20);
  log.start('Benchmarking box.open');
  benchmark(function() {
    nacl.box.open(box, nonce, pk2, sk1);
  }, msg.length, 20);
}

function sign_open_benchmark() {
  var k = nacl.sign.keyPair();
  var sk = k.secretKey;
  var pk = k.publicKey;
  var msg = nacl.util.decodeUTF8((new Array(128)).join('a'));
  var sm;
  log.start('Benchmarking sign');
  benchmark(function() {
    sm = nacl.sign(msg, sk);
  }, msg.length, 20);
  log.start('Benchmarking sign.open');
  benchmark(function() {
    nacl.sign.open(sm, pk);
  }, msg.length, 20);
}

function crypto_hash_benchmark() {
  log.start('Benchmarking crypto_hash (1024 bytes)');
  var m = new Uint8Array(1024), out = new Uint8Array(64);
  for (i = 0; i < m.length; i++) m[i] = i & 255;
  benchmark(function(){
    nacl.lowlevel.crypto_hash(out, m, m.length);
  }, m.length);

  log.start('Benchmarking crypto_hash (16 KiB)');
  m = new Uint8Array(16*1024);
  for (i = 0; i < m.length; i++) m[i] = i & 255;
  benchmark(function(){
    nacl.lowlevel.crypto_hash(out, m, m.length);
  }, m.length);
}

crypto_stream_xor_benchmark();
crypto_onetimeauth_benchmark();
crypto_secretbox_benchmark();
crypto_hash_benchmark();
secretbox_seal_open_benchmark();
crypto_scalarmult_base_benchmark();
box_seal_open_benchmark();
sign_open_benchmark();
<commit_msg>Make benchmark adaptive.<commit_after>var nacl = (typeof window !== 'undefined') ? window.nacl : require('../../' + (process.env.NACL_SRC || 'nacl.min.js'));
var helpers = (typeof require !== 'undefined') ? require('./helpers') : window.helpers;
var log = helpers.log;

if (!nacl) throw new Error('nacl not loaded');

function benchmark(fn, bytes, num) {
  if (!num) num = 1000;
  var i, elapsed, start = new Date();
  while (1) {
    for (i = 0; i < num; i++) fn();
    elapsed = (new Date()) - start;
    if (elapsed < 500) {
      num += num*1000/elapsed/2;
    } else {
      break;
    }
  }

  log.print(' ' + ((bytes*num/1024/1024*1000)/elapsed).toFixed(3), 'MB/s');
  log.print(' ' + ((num*1000)/elapsed).toFixed(3), 'ops/s');
}

function benchmarkOps(fn,  num) {
  var i, elapsed, start = new Date();
  while (1) {
    for (i = 0; i < num; i++) {
      fn();
    }
    elapsed = (new Date()) - start;
    if (elapsed < 500) {
      num += num*1000/elapsed/2;
    } else {
      break;
    }
  }
  log.print(' ' + ((num*1000)/elapsed).toFixed(3), 'ops/s');
}

function crypto_stream_xor_benchmark() {
  log.start('Benchmarking crypto_stream_xor');
  var m = new Uint8Array(1024),
      n = new Uint8Array(24),
      k = new Uint8Array(32),
      out = new Uint8Array(1024);
  for (i = 0; i < 1024; i++) m[i] = i & 255;
  for (i = 0; i < 24; i++) n[i] = i;
  for (i = 0; i < 32; i++) k[i] = i;
  benchmark(function(){
    nacl.lowlevel.crypto_stream_xor(out, 0, m, 0, m.length, n, k);
  }, m.length);
}

function crypto_onetimeauth_benchmark() {
  log.start('Benchmarking crypto_onetimeauth');
  var m = new Uint8Array(1024),
      out = new Uint8Array(1024),
      k = new Uint8Array([0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1]);
  for (i = 0; i < 1024; i++) {
    m[i] = i & 255;
  }
  benchmark(function(){
    nacl.lowlevel.crypto_onetimeauth(out, 0, m, 0, m.length, k);
  }, m.length);
}

function crypto_secretbox_benchmark() {
  log.start('Benchmarking crypto_secretbox');
  var i, k = new Uint8Array(32), n = new Uint8Array(24),
      m = new Uint8Array(1024), c = new Uint8Array(1024);
  for (i = 0; i < 32; i++) k[i] = 1;
  for (i = 0; i < 24; i++) n[i] = 2;
  for (i = 0; i < 1024; i++) m[i] = 3;
  benchmark(function() {
    nacl.lowlevel.crypto_secretbox(c, m, m.length, n, k);
  }, m.length);
}

function secretbox_seal_open_benchmark() {
  var key = new Uint8Array(32),
      nonce = new Uint8Array(24),
      msg = new Uint8Array(1024),
      box, i;
  for (i = 0; i < 32; i++) key[i] = 1;
  for (i = 0; i < 24; i++) nonce[i] = 2;
  for (i = 0; i < 1024; i++) msg[i] = 3;

  log.start('Benchmarking secretbox');
  benchmark(function() {
    box = nacl.secretbox(msg, nonce, key);
  }, msg.length);
  log.start('Benchmarking secretbox.open');
  benchmark(function() {
    nacl.secretbox.open(box, nonce, key);
  }, msg.length);
}

function crypto_scalarmult_base_benchmark() {
  log.start('Benchmarking crypto_scalarmult_base');
  var n = new Uint8Array(32), q = new Uint8Array(32);
  for (var i = 0; i < 32; i++) n[i] = i;
  benchmarkOps(function() {
    nacl.lowlevel.crypto_scalarmult_base(q, n);
  }, 10);
}

function box_seal_open_benchmark() {
  var pk1 = new Uint8Array(32), sk1 = new Uint8Array(32),
      pk2 = new Uint8Array(32), sk2 = new Uint8Array(32);
  nacl.lowlevel.crypto_box_keypair(pk1, sk1);
  nacl.lowlevel.crypto_box_keypair(pk2, sk2);
  var nonce = nacl.util.decodeUTF8('123456789012345678901234');
  var msg = nacl.util.decodeUTF8((new Array(1024)).join('a'));
  var box = null;
  log.start('Benchmarking box');
  benchmark(function() {
    box = nacl.box(msg, nonce, pk1, sk2);
  }, msg.length, 20);
  log.start('Benchmarking box.open');
  benchmark(function() {
    nacl.box.open(box, nonce, pk2, sk1);
  }, msg.length, 20);
}

function sign_open_benchmark() {
  var k = nacl.sign.keyPair();
  var sk = k.secretKey;
  var pk = k.publicKey;
  var msg = nacl.util.decodeUTF8((new Array(128)).join('a'));
  var sm;
  log.start('Benchmarking sign');
  benchmark(function() {
    sm = nacl.sign(msg, sk);
  }, msg.length, 20);
  log.start('Benchmarking sign.open');
  benchmark(function() {
    nacl.sign.open(sm, pk);
  }, msg.length, 20);
}

function crypto_hash_benchmark() {
  log.start('Benchmarking crypto_hash (1024 bytes)');
  var m = new Uint8Array(1024), out = new Uint8Array(64);
  for (i = 0; i < m.length; i++) m[i] = i & 255;
  benchmark(function(){
    nacl.lowlevel.crypto_hash(out, m, m.length);
  }, m.length);

  log.start('Benchmarking crypto_hash (16 KiB)');
  m = new Uint8Array(16*1024);
  for (i = 0; i < m.length; i++) m[i] = i & 255;
  benchmark(function(){
    nacl.lowlevel.crypto_hash(out, m, m.length);
  }, m.length);
}

crypto_stream_xor_benchmark();
crypto_onetimeauth_benchmark();
crypto_secretbox_benchmark();
crypto_hash_benchmark();
secretbox_seal_open_benchmark();
crypto_scalarmult_base_benchmark();
box_seal_open_benchmark();
sign_open_benchmark();
<|endoftext|>


<commit_before>/*
 * Create references
 */
var es = require('event-stream');
var gulp = require('gulp');
var glob = require('glob');
var pkg = require('./package.json');
var common = require('./common.js');

/*
 * Auto load all gulp plugins
 */
var gulpLoadPlugins = require("gulp-load-plugins");
var plug = gulpLoadPlugins();

/*
 * Load common utilities for gulp
 */
var gutil = plug.loadUtils(['colors', 'env', 'log', 'date']);

/*
 * Create comments for minified files
 */
var commentHeader = common.createComments(gutil);

/*
 * Could use a staging/development switch.
 * Run `gulp --staging`
 */
var type = gutil.env.staging ? 'staging' : 'development';
gutil.log('Building for', gutil.colors.magenta(type));
gutil.beep();

/*
 * Lint the code
 */
gulp.task('jshint', function () {
    return gulp.src(pkg.paths.js)
        .pipe(plug.jshint('.jshintrc'))
//        .pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/*
 * Create $templateCache from the html templates
 */
gulp.task('templatecache', function () {
    gulp.src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.dev));
});

/*
 * Minify and bundle the JavaScript
 */
gulp.task('js', ['jshint', 'templatecache'], function () {
    var source = [].concat(pkg.paths.js, pkg.paths.dev + 'templates.js');
    return gulp.src(source)
        .pipe(plug.size({showFiles: true}))
        .pipe(plug.sourcemaps.init())

        // Annotate before uglify so the code get's min'd properly.
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, must be explicit there
            add: true
        }))
        .pipe(plug.uglify({
//            sourceMap: true,
//            banner: '/*! <%= pkg.name %> <%= gutil.date("mmm d, yyyy h:MM:ss TT Z") %> */\n',
            mangle: true
        }))
        .pipe(plug.concat('all.min.js', {newLine: ';'}))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(plug.header(commentHeader))
        .pipe(gulp.dest(pkg.paths.dev))
        .pipe(plug.size({showFiles: true}));
});

/*
 * Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function () {
    var source = [].concat(pkg.paths.vendorjs,
        pkg.paths.vendorjs.map(function (path) {
            return path + '.map';
        }));
    source.push('../client/components/jquery/dist/jquery.min.map');
    console.log(source);
    return gulp.src(source)
        .pipe(gulp.dest(pkg.paths.dev + 'vendor'));
});

/*
 * Minify and bundle the CSS
 */
gulp.task('css', function () {
    return gulp.src(pkg.paths.css)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.header(commentHeader))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
//        .pipe(plug.size({showFiles: true}));
});

/*
 * Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function () {
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
});

/*
 * Copy fonts
 */
gulp.task('fonts', function () {
    return gulp.src(pkg.paths.fonts)
        .pipe(gulp.dest(pkg.paths.dev + 'fonts'));
});

/*
 * Compress images
 */
gulp.task('images', function () {
    return gulp.src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(pkg.paths.dev + 'content/images'));
});

/*
 * Inject all the files into the new index.html
 */
gulp.task('htmlinject', ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts'], function () {
    var target = gulp.src('../client/index.html');
    var v = pkg.paths.vendorjssequence.map(function (file) {
        return pkg.paths.dev + 'vendor/' + file;
    });
    var sources = {
        css: gulp.src([pkg.paths.dev + 'content/all.min.css'], {read: false}),
        vendorcss: gulp.src([pkg.paths.dev + 'content/vendor.min.css'], {read: false}),
        js: gulp.src([pkg.paths.dev + 'all.min.js']),
        vendorjs: gulp.src(v)
    };
    var ignorePath = '/../client';

    target
//        .pipe(plug.rename('index.html'))
        .pipe(plug.inject(sources.vendorcss, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.css, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.js, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.vendorjs, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
//        .pipe(gulp.dest('../client/'));
        .pipe(gulp.dest(pkg.paths.dev));
});

/*
 * Bundle the JS, CSS, and compress images.
 * Then copy files to dev and show a toast.
 */
gulp.task('default', ['htmlinject'], function () {
    // Prepare files for dev
    return gulp.src(pkg.paths.dev)
        .pipe(plug.notify({
            onLast: true,
            message: "linted, bundled, and images compressed!"
        }));
});

/*
 * Bundle the JS, CSS, and compress images.
 * Then copy files to staging and show a toast.
 */
gulp.task('stage', ['default'], function () {
    // Copy the files to staging
    return gulp.src(pkg.paths.dev)
        .pipe(gulp.dest(pkg.paths.stage))
        // Notify we are done
        .pipe(plug.notify({
            onLast: true,
            message: "staged!"
        }));
});

/*
 * Remove all files from the output folder
 */
gulp.task('cleanOutput', function () {
    return gulp.src([
        pkg.paths.dev,
        pkg.paths.stage
    ])
        .pipe(plug.clean({force: true}));
});

/*
 * Watch js files
 */
gulp.task('watchjs', function () {
    var js = ['gulpfile.js'].concat(pkg.paths.js);
    var watcher = gulp.watch(js, ['js', 'vendorjs']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/*
 * Watch css files
 */
gulp.task('watchcss', function () {
    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var watcher = gulp.watch(css, ['css', 'vendorcss']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/*
 * Watch all files
 */
gulp.task('watch', ['watchcss', 'watchjs'], function () {
});
<commit_msg>modular: added comment separators to gulpfile.js<commit_after>/*
 * Create references
 */
var es = require('event-stream');
var gulp = require('gulp');
var glob = require('glob');
var pkg = require('./package.json');
var common = require('./common.js');

/************************
 * Auto load all gulp plugins
 ************************/
var gulpLoadPlugins = require("gulp-load-plugins");
var plug = gulpLoadPlugins();

/************************
 * Load common utilities for gulp
 ************************/
var gutil = plug.loadUtils(['colors', 'env', 'log', 'date']);

/************************
 * Create comments for minified files
 ************************/
var commentHeader = common.createComments(gutil);

/************************
 * Could use a staging/development switch.
 * Run `gulp --staging`
 ************************/
var type = gutil.env.staging ? 'staging' : 'development';
gutil.log('Building for', gutil.colors.magenta(type));
gutil.beep();

/************************
 * Lint the code
 ************************/
gulp.task('jshint', function () {
    return gulp.src(pkg.paths.js)
        .pipe(plug.jshint('.jshintrc'))
//        .pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/************************
 * Create $templateCache from the html templates
 ************************/
gulp.task('templatecache', function () {
    gulp.src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.dev));
});

/************************
 * Minify and bundle the JavaScript
 ************************/
gulp.task('js', ['jshint', 'templatecache'], function () {
    var source = [].concat(pkg.paths.js, pkg.paths.dev + 'templates.js');
    return gulp.src(source)
        .pipe(plug.size({showFiles: true}))
        .pipe(plug.sourcemaps.init())

        // Annotate before uglify so the code get's min'd properly.
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, must be explicit there
            add: true
        }))
        .pipe(plug.uglify({
//            sourceMap: true,
//            banner: '/*! <%= pkg.name %> <%= gutil.date("mmm d, yyyy h:MM:ss TT Z") %> */\n',
            mangle: true
        }))
        .pipe(plug.concat('all.min.js', {newLine: ';'}))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(plug.header(commentHeader))
        .pipe(gulp.dest(pkg.paths.dev))
        .pipe(plug.size({showFiles: true}));
});

/************************
 * Copy the Vendor JavaScript
 ************************/
gulp.task('vendorjs', function () {
    var source = [].concat(pkg.paths.vendorjs,
        pkg.paths.vendorjs.map(function (path) {
            return path + '.map';
        }));
    source.push('../client/components/jquery/dist/jquery.min.map');
    console.log(source);
    return gulp.src(source)
        .pipe(gulp.dest(pkg.paths.dev + 'vendor'));
});

/************************
 * Minify and bundle the CSS
 ************************/
gulp.task('css', function () {
    return gulp.src(pkg.paths.css)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.header(commentHeader))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
//        .pipe(plug.size({showFiles: true}));
});

/************************
 * Minify and bundle the Vendor CSS
 ************************/
gulp.task('vendorcss', function () {
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
});

/************************
 * Copy fonts
 ************************/
gulp.task('fonts', function () {
    return gulp.src(pkg.paths.fonts)
        .pipe(gulp.dest(pkg.paths.dev + 'fonts'));
});

/************************
 * Compress images
 ************************/
gulp.task('images', function () {
    return gulp.src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(pkg.paths.dev + 'content/images'));
});

/************************
 * Inject all the files into the new index.html
 ************************/
gulp.task('htmlinject', ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts'], function () {
    var target = gulp.src('../client/index.html');
    var v = pkg.paths.vendorjssequence.map(function (file) {
        return pkg.paths.dev + 'vendor/' + file;
    });
    var sources = {
        css: gulp.src([pkg.paths.dev + 'content/all.min.css'], {read: false}),
        vendorcss: gulp.src([pkg.paths.dev + 'content/vendor.min.css'], {read: false}),
        js: gulp.src([pkg.paths.dev + 'all.min.js']),
        vendorjs: gulp.src(v)
    };
    var ignorePath = '/../client';

    target
//        .pipe(plug.rename('index.html'))
        .pipe(plug.inject(sources.vendorcss, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.css, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.js, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.vendorjs, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
//        .pipe(gulp.dest('../client/'));
        .pipe(gulp.dest(pkg.paths.dev));
});

/************************
 * Bundle the JS, CSS, and compress images.
 * Then copy files to dev and show a toast.
 ************************/
gulp.task('default', ['htmlinject'], function () {
    // Prepare files for dev
    return gulp.src(pkg.paths.dev)
        .pipe(plug.notify({
            onLast: true,
            message: "linted, bundled, and images compressed!"
        }));
});

/************************
 * Bundle the JS, CSS, and compress images.
 * Then copy files to staging and show a toast.
 ************************/
gulp.task('stage', ['default'], function () {
    // Copy the files to staging
    return gulp.src(pkg.paths.dev)
        .pipe(gulp.dest(pkg.paths.stage))
        // Notify we are done
        .pipe(plug.notify({
            onLast: true,
            message: "staged!"
        }));
});

/************************
 * Remove all files from the output folder
 ************************/
gulp.task('cleanOutput', function () {
    return gulp.src([
        pkg.paths.dev,
        pkg.paths.stage
    ])
        .pipe(plug.clean({force: true}));
});

/************************
 * Watch js files
 ************************/
gulp.task('watchjs', function () {
    var js = ['gulpfile.js'].concat(pkg.paths.js);
    var watcher = gulp.watch(js, ['js', 'vendorjs']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/************************
 * Watch css files
 ************************/
gulp.task('watchcss', function () {
    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var watcher = gulp.watch(css, ['css', 'vendorcss']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/************************
 * Watch all files
 ************************/
gulp.task('watch', ['watchcss', 'watchjs'], function () {
});<|endoftext|>