<commit_before>// ==UserScript==
// @name        OSM Dark Theme
// @namespace   http://about.me/marcoantoniofrias

// @include     http://openstreetmap.org/*
// @include     https://openstreetmap.org/*
// @include     http://*.openstreetmap.org/*
// @include     https://*.openstreetmap.org/*

// @license     BSD License; http://www.opensource.org/licenses/bsd-license.php
// @version     0.2
// @grant       none
// ==/UserScript==

// Load prerequisites
loadGlobalCSS();

// Functions
function addGlobalStyle(device, css) {
  var elmHead, elmStyle;
  elmHead = document.getElementsByTagName('head')[0];
  elmStyle = document.createElement('style');
  elmStyle.type = 'text/css';
  elmStyle.media = device;
  elmHead.appendChild(elmStyle);
  elmStyle.innerHTML = css;
}

function loadGlobalCSS() {
  addGlobalStyle('screen',
    'body { background-color: #232323; color: #888; } ' +
    'a { color: #888; } a:hover { color: #fff; } ' +
    'input[type="text"], input[type="email"], input[type="url"], input[type="password"], textarea { background-color: #2d2d2d; border: 1px solid #181818; color: #888; } ' +
    'input[type="button"], input[type="submit"], input[type="reset"], a.button { background: #2d2d2d; border: 1px solid #181818; color: #888; } ' +
    'input[type="button"]:hover, input[type="submit"]:hover, input[type="reset"]:hover, a.button:hover { background: #373737; } ' +
    '/* navbar */ ' +
    'header h1 a { color: #888; } ' +
    'nav.primary > ul { border: 1px solid #181818; } ' +
    'nav.primary > ul > li, nav.primary > ul > li.dropdown > a.tab { border-right: 1px solid #181818; } ' +
    'nav.primary > ul > li > a:hover { background: #2d2d2d; } ' +
    'nav.primary > ul > li.current { background-color: #2d2d2d; } ' +
    'nav.primary > ul > li.current > a:hover { background: #373737; } ' +
    'nav.primary a.tab, nav.primary .dropdown-toggle { color: #888; } ' +
    'nav.primary a.tab:hover, nav.primary .dropdown-toggle:hover { color: #fff; } ' +
    'nav.primary .caret, nav.secondary .caret { border-top-color: #888; } ' +
    'nav.secondary > ul a:hover, nav.secondary > ul .dropdown-toggle:hover { color: #fff; } ' +
    'nav.secondary .user-menu { border: 1px solid #181818; } ' +
    'nav.secondary .user-menu > li { border-right: 1px solid #181818; } ' +
    'nav.secondary .user-menu > li:hover a { background: #2d2d2d; } ' +
    'nav.secondary .user-menu.logged-in > a:hover > .user-button { color: #fff; } ' +
    'nav.secondary #inboxanchor, .count-number { background: #a40000; color: #fff; } ' +
    '.dropdown-menu { background-color: #232323; border: 1px solid #181818; } ' +
    '.dropdown-menu > li > a { color: #888; } ' +
    '.dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus, .dropdown-submenu:hover > a, .dropdown-submenu:focus > a { background-color: #2d2d2d; color: #fff; } ' +
    '.dropdown-menu .divider { background-color: #232323; border-bottom: 1px solid #181818; } ' +
    '/* sidebar-left */ ' +
    '.search_form, .directions_form { background-color: #232323; } ' +
    '.search_form .describe_location, .directions_form .describe_location { color: #888; } ' +
    '.search_form input:focus, .directions_form input:focus { box-shadow: 0px 0px 7px #555555; } ' +
    '.map-layout #sidebar { background: #232323; } ' +
    '#turnbyturn tr.turn:hover { background: #2d2d2d; } ' +
    '#turnbyturn td.instruction, #turnbyturn td.distance { border-bottom: 1px solid #181818; } ' +
    '.buttons input[type="submit"], .buttons input[type="button"], .buttons input[type="reset"], .buttons .button, .buttons .button_to { border-right: 1px solid #181818; } ' +
    'input[type="button"]:disabled, input[type="submit"]:disabled, input[type="reset"]:disabled, a.button:disabled { background: #555753; } ' +
    'input[type="button"]:disabled:hover, input[type="submit"]:disabled:hover, input[type="reset"]:disabled:hover, a.button:disabled:hover { background: #232323; } ' +
    '#sidebar .changesets li { border-bottom: 1px solid #181818; } ' +
    '#sidebar .changesets li.selected { border-bottom: 1px solid #181818; background: #2d2d2d; } ' +
    '#sidebar .changesets h4 a { color: #888; } ' +
    '#sidebar_content .browse-section { border-bottom: 1px solid #181818; } ' +
    '#sidebar_content .browse-tag-list { background-color: #232323; border: 1px solid #181818; } ' +
    '#sidebar_content .browse-tag-list .browse-tag-k { background-color: #2d2d2d; } ' +
    '#sidebar_content .browse-tag-list .browse-tag-v { background-color: #232323; border-left: 1px solid #181818; } ' +
    '#sidebar_content .browse-tag-list th, #sidebar_content .browse-tag-list td { border-bottom: 1px solid #181818; } ' +
    '/* sidebar-right (map-ui) */ ' +
    '.map-layout #map-ui { background: #232323; } ' +
    '.map-layout #map-ui .section { border-bottom: 1px solid #181818; } ' +
    '.layers-ui .base-layers li { border: 2px solid #181818; } ' +
    '.layers-ui .base-layers li.active { border-color: #000; } ' +
    '.layers-ui .base-layers li.active:hover { border-color: #181818; } ' +
    '.layers-ui .base-layers li label { background: rgba(35, 35, 35, 0.9); } ' +
    '.leaflet-container { background: #232323; } ' +
    '.leaflet-container a.leaflet-popup-close-button { color: #888; } ' +
    '.leaflet-popup-content-wrapper, .leaflet-popup-tip { background: #232323; } ' +
    '.share-ui .share-tabs a.active { background-color: #232323; } ' +
    '.share-ui .share-tabs a:first-child, .share-ui .share-tabs a:last-child { border: 1px solid #181818; } ' +
    '.share-ui .share-tabs a { background-color: #232323; border-top: 1px solid #181818; border-right: 1px solid #181818; border-bottom: 1px solid #181818; color: #888; } ' +
    '.share-ui #geo_uri { width: 100%; font-family: monospace; font-size: small; line-height: 1.3; } ' +
    '/* leaflet-control */ ' +
    '.leaflet-control .control-button.active { background-color: #2d2d2d; } ' +
    '/* content */ ' +
    '.content-heading { background: #2d2d2d; } ' +
    '.standard-form .form-divider { border-top: 1px solid #181818; } ' +
    '.deemphasize { color: #fff; } ' +
    '.deemphasize a { color: #888; } ' +
    '.fillL { background-color: none; } '
  );
}
<commit_msg>more support + fixes bugs<commit_after>// ==UserScript==
// @name        OSM Dark Theme
// @namespace   http://about.me/marcoantoniofrias

// @include     http://openstreetmap.org/*
// @include     https://openstreetmap.org/*
// @include     http://www.openstreetmap.org/*
// @include     https://www.openstreetmap.org/*

// @license     BSD License; http://www.opensource.org/licenses/bsd-license.php
// @version     0.3
// @grant       none
// ==/UserScript==

// Load prerequisites
loadGlobalCSS();

// Functions
function addGlobalStyle(device, css) {
  var elmHead, elmStyle;
  elmHead = document.getElementsByTagName('head')[0];
  elmStyle = document.createElement('style');
  elmStyle.type = 'text/css';
  elmStyle.media = device;
  elmHead.appendChild(elmStyle);
  elmStyle.innerHTML = css;
}

function loadGlobalCSS() {
  addGlobalStyle('screen',
    'body { background-color: #232323; color: #888; } ' +
    'a { color: #888; } a:hover { color: #fff; } ' +
    'h4, h5 { color: #888; } ' +
    'input[type="text"], input[type="email"], input[type="url"], input[type="password"], textarea { background-color: #2d2d2d; border: 1px solid #181818; color: #888; } ' +
    'input[type="button"], input[type="submit"], input[type="reset"], a.button { background: #2d2d2d; border: 1px solid #181818; color: #888; } ' +
    'input[type="button"]:hover, input[type="submit"]:hover, input[type="reset"]:hover, a.button:hover { background: #373737; } ' +
    'input[type="button"]:disabled, input[type="submit"]:disabled, input[type="reset"]:disabled, a.button:disabled { background: #555753; } ' +
    'input[type="button"]:disabled:hover, input[type="submit"]:disabled:hover, input[type="reset"]:disabled:hover, a.button:disabled:hover { background: #232323; } ' +
    '/* navbar */ ' +
    'header h1 a { color: #888; } ' +
    'nav.primary > ul { border: 1px solid #181818; } ' +
    'nav.primary > ul > li, nav.primary > ul > li.dropdown > a.tab { border-right: 1px solid #181818; } ' +
    'nav.primary > ul > li > a:hover { background: #2d2d2d; } ' +
    'nav.primary > ul > li.current { background-color: #2d2d2d; } ' +
    'nav.primary > ul > li.current > a:hover { background: #373737; } ' +
    'nav.primary a.tab, nav.primary .dropdown-toggle { color: #888; } ' +
    'nav.primary a.tab:hover, nav.primary .dropdown-toggle:hover { color: #fff; } ' +
    'nav.primary .caret, nav.secondary .caret { border-top-color: #888; } ' +
    'nav.secondary > ul a:hover, nav.secondary > ul .dropdown-toggle:hover { color: #fff; } ' +
    'nav.secondary .user-menu { border: 1px solid #181818; } ' +
    'nav.secondary .user-menu > li { border-right: 1px solid #181818; } ' +
    'nav.secondary .user-menu > li:hover a { background: #2d2d2d; } ' +
    'nav.secondary .user-menu.logged-in > a:hover > .user-button { color: #fff; } ' +
    'nav.secondary #inboxanchor, .count-number { background: #a40000; color: #fff; } ' +
    '.dropdown-menu { background-color: #232323; border: 1px solid #181818; } ' +
    '.dropdown-menu > li > a { color: #888; } ' +
    '.dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus, .dropdown-submenu:hover > a, .dropdown-submenu:focus > a { background-color: #2d2d2d; color: #fff; } ' +
    '.dropdown-menu .divider { background-color: #232323; border-bottom: 1px solid #181818; } ' +
    '/* sidebar-left */ ' +
    '.search_form, .directions_form { background-color: #232323; } ' +
    '.search_form .describe_location, .directions_form .describe_location { color: #888; } ' +
    '.search_form input:focus, .directions_form input:focus { box-shadow: 0px 0px 7px #555555; } ' +
    '.map-layout #sidebar { background: #232323; } ' +
    '#turnbyturn tr.turn:hover { background: #2d2d2d; } ' +
    '#turnbyturn td.instruction, #turnbyturn td.distance { border-bottom: 1px solid #181818; } ' +
    '.buttons input[type="submit"], .buttons input[type="button"], .buttons input[type="reset"], .buttons .button, .buttons .button_to { border-right: 1px solid #181818; } ' +
    '#sidebar .changesets li { border-bottom: 1px solid #181818; } ' +
    '#sidebar .changesets li.selected { border-bottom: 1px solid #181818; background: #2d2d2d; } ' +
    '#sidebar .changesets h4 a { color: #888; } ' +
    '#sidebar_content .browse-section { border-bottom: 1px solid #181818; } ' +
    '#sidebar_content .browse-tag-list { background-color: #232323; border: 1px solid #181818; } ' +
    '#sidebar_content .browse-tag-list .browse-tag-k { background-color: #2d2d2d; } ' +
    '#sidebar_content .browse-tag-list .browse-tag-v { background-color: #232323; border-left: 1px solid #181818; } ' +
    '#sidebar_content .browse-tag-list th, #sidebar_content .browse-tag-list td { border-bottom: 1px solid #181818; } ' +
    '/* sidebar-right (map-ui) */ ' +
    '.map-layout #map-ui { background: #232323; } ' +
    '.map-layout #map-ui .section { border-bottom: 1px solid #181818; } ' +
    '.layers-ui .base-layers li { border: 2px solid #181818; } ' +
    '.layers-ui .base-layers li.active { border-color: #000; } ' +
    '.layers-ui .base-layers li.active:hover { border-color: #181818; } ' +
    '.layers-ui .base-layers li label { background: rgba(35, 35, 35, 0.9); } ' +
    '.share-ui .share-tabs a { background-color: #232323; border-top: 1px solid #181818; border-right: 1px solid #181818; border-bottom: 1px solid #181818; color: #888; } ' +
    '.share-ui .share-tabs a.active { background-color: #232323; } ' +
    '.share-ui .share-tabs a:first-child, .share-ui .share-tabs a:last-child { border: 1px solid #181818; } ' +
    '.share-ui #geo_uri { width: 100%; font-family: monospace; font-size: small; line-height: 1.3; } ' +
    '/* leaflet */ ' +
    '.layer-list { border: 1px solid #181818; } ' +
    '.layer-list li { background-color: #232323; color: #888;  } ' +
    '.layer-list li:not(:last-child) { border-bottom: 1px solid #181818; } ' +
    '.leaflet-container { background: #232323; } ' +
    '.leaflet-container a { color: #888; } ' +
    '.leaflet-container a.leaflet-popup-close-button { color: #888; } ' +
    '.leaflet-control .control-button.active { background-color: #2d2d2d; } ' +
    '.leaflet-popup-content-wrapper, .leaflet-popup-tip { background: #232323; } ' +
    '/* content */ ' +
    '.content-heading { background: #2d2d2d; } ' +
    '.standard-form .form-divider { border-top: 1px solid #181818; } ' +
    '.deemphasize { color: #fff; } ' +
    '.deemphasize a { color: #888; } ' +
    '.fillL { background-color: #232323; } ' +
    '/* options */ ' +
    '.activity-block { border-bottom: 1px solid #181818; } ' +
    '.diary_post { border-top: 1px solid #181818; } ' +
    '.diary_entry .diary-comment { border-top: 1px dashed #181818; } ' +
    '.diary_entry .diary-comment:first-child { border-top: 1px solid #181818; } ' +
    '.diary_entry #newcomment { border-top: 1px solid #181818; } ' +
    'img.user_thumbnail { border: 1px solid #181818; } ' +
    '.messages { border: 1px solid #181818; } ' +
    '.messages tbody tr { border-top: 1px solid #181818; } ' +
    '.messages tr td { border-right: 1px solid #181818; } ' +
    '.messages .inbox-row-unread { background: #2d2d2d; } ' +
    '.messages .inbox-row { background: #232323; } ' +
    '.note_list tr.creator { background-color: #232323; } ' +
    '.richtext blockquote, .prose blockquote { border-left: 20px solid #2d2d2d; color: #484848; } ' +
    '.richtext img, .prose img { background-color: #2d2d2d; } ' +
    '.richtext_container .richtext_help { background-color: #2d2d2d; } ' +
    '.richtext_container .richtext_help h4.heading, .richtext_container .richtext_help li { border-bottom: 1px solid #181818; } ' +
    '.richtext_container .richtext_content .richtext_preview { background-color: #2d2d2d; } ' +
    '.site-about #content { background-color: #232323; } ' +
    '.site-about #content .content-inner { color: #888; } ' +
    '.site-about #content .text { background: #232323; } ' +
    '.table0, .item0 { background: #2d2d2d; } ' +
    '.table1, .item1 { background: #232323; } ' +
    'ul.secondary-actions > li { border-left: 1px solid #181818; } ' +
    'input.deemphasize[type="button"], input.deemphasize[type="submit"], input.deemphasize[type="reset"], a.button.deemphasize { background: #232323; } ' +
    'input.deemphasize[type="button"]:hover, input.deemphasize[type="submit"]:hover, input.deemphasize[type="reset"]:hover, a.button.deemphasize:hover { background: #2d2d2d; } ' +
    '/* editor */ ' +
    '.notice { background: #232323; } ' +
    '.notice .zoom-to { color: #888; } ' +
    '.notice .zoom-to:hover { background: #2d2d2d; } '
  );
}
<|endoftext|>


<commit_before>/*
 * sprintf.js
 * Objective-J
 *
 * Created by Thomas Robinson.
 * Copyright 2008-2010, 280 North, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

// sprintf:

var formatRegex = new RegExp("([^%]+|%(?:\\d+\\$)?[\\+\\-\\ \\#0]*[0-9\\*]*(.[0-9\\*]+)?[hlL]?[cbBdieEfgGosuxXpn%@])", "g");
var tagRegex = new RegExp("(%)(?:(\\d+)\\$)?([\\+\\-\\ \\#0]*)([0-9\\*]*)((?:.[0-9\\*]+)?)([hlL]?)([cbBdieEfgGosuxXpn%@])");

exports.sprintf = function(format)
{
    var format = arguments[0],
        tokens = format.match(formatRegex),
        index = 0,
        result = "",
        arg = 1;

    for (var i = 0; i < tokens.length; i++)
    {
        var t = tokens[i];
        if (format.substring(index, index + t.length) != t)
        {
            return result;
        }
        index += t.length;

        if (t.charAt(0) !== "%")
            result += t;

        else if (t === "%%")
            result += "%";

        else
        {
            var subtokens = t.match(tagRegex);
            if (subtokens.length != 8 || subtokens[0] != t)
            {
                return result;
            }

            var percentSign     = subtokens[1],
                argIndex        = subtokens[2],
                flags           = subtokens[3],
                widthString     = subtokens[4],
                precisionString = subtokens[5],
                length          = subtokens[6],
                specifier       = subtokens[7];

            if (argIndex === undefined || argIndex === null || argIndex === "")
                argIndex = arg++;
            else
                argIndex = Number(argIndex);

            var width = null;
            if (widthString == "*")
                width = arguments[argIndex];
            else if (widthString != "")
                width = Number(widthString);

            var precision = null;
            if (precisionString == ".*")
                precision = arguments[argIndex];
            else if (precisionString != "")
                precision = Number(precisionString.substring(1));

            var leftJustify = (flags.indexOf("-") >= 0);
            var padZeros    = (flags.indexOf("0") >= 0);

            var subresult = "";

            if (RegExp("[bBdiufeExXo]").test(specifier))
            {
                var num = Number(arguments[argIndex]);

                var sign = "";
                if (num < 0)
                {
                    sign = "-";
                }
                else
                {
                    if (flags.indexOf("+") >= 0)
                        sign = "+";
                    else if (flags.indexOf(" ") >= 0)
                        sign = " ";
                }

                if (specifier == "d" || specifier == "i" || specifier == "u")
                {
                    var number = String(Math.abs(Math.floor(num)));

                    subresult = justify(sign, "", number, "", width, leftJustify, padZeros)
                }

                if (specifier == "f")
                {
                    var number = String((precision != null) ? Math.abs(num).toFixed(precision) : Math.abs(num));
                    var suffix = (flags.indexOf("#") >= 0 && number.indexOf(".") < 0) ? "." : "";

                    subresult = justify(sign, "", number, suffix, width, leftJustify, padZeros);
                }

                if (specifier == "e" || specifier == "E")
                {
                    var number = String(Math.abs(num).toExponential(precision != null ? precision : 21));
                    var suffix = (flags.indexOf("#") >= 0 && number.indexOf(".") < 0) ? "." : "";

                    subresult = justify(sign, "", number, suffix, width, leftJustify, padZeros);
                }

                if (specifier == "x" || specifier == "X")
                {
                    var number = String(Math.abs(num).toString(16));
                    var prefix = (flags.indexOf("#") >= 0 && num != 0) ? "0x" : "";

                    subresult = justify(sign, prefix, number, "", width, leftJustify, padZeros);
                }

                if (specifier == "b" || specifier == "B")
                {
                    var number = String(Math.abs(num).toString(2));
                    var prefix = (flags.indexOf("#") >= 0 && num != 0) ? "0b" : "";

                    subresult = justify(sign, prefix, number, "", width, leftJustify, padZeros);
                }

                if (specifier == "o")
                {
                    var number = String(Math.abs(num).toString(8));
                    var prefix = (flags.indexOf("#") >= 0 && num != 0) ? "0" : "";

                    subresult = justify(sign, prefix, number, "", width, leftJustify, padZeros);
                }

                if (RegExp("[A-Z]").test(specifier))
                    subresult = subresult.toUpperCase();
                else
                    subresult = subresult.toLowerCase();
            }
            else
            {
                var subresult = "";

                if (specifier == "%")
                    subresult = "%";
                else if (specifier == "c")
                    subresult = String(arguments[argIndex]).charAt(0);
                else if (specifier == "s" || specifier == "@")
                    subresult = String(arguments[argIndex]);
                else if (specifier == "p" || specifier == "n")
                {
                    subresult = "";
                }

                subresult = justify("", "", subresult, "", width, leftJustify, false);
            }

            result += subresult;
        }
    }
    return result;
}

function justify(sign, prefix, string, suffix, width, leftJustify, padZeros)
{
    var length = (sign.length + prefix.length + string.length + suffix.length);
    if (leftJustify)
    {
        return sign + prefix + string + suffix + pad(width - length, " ");
    }
    else
    {
        if (padZeros)
            return sign + prefix + pad(width - length, "0") + string + suffix;
        else
            return pad(width - length, " ") + sign + prefix + string + suffix;
    }
}

function pad(n, ch)
{
    return Array(MAX(0,n)+1).join(ch);
}
<commit_msg>Formatting, optimizations.<commit_after>/*
 * sprintf.js
 * Objective-J
 *
 * Created by Thomas Robinson.
 * Copyright 2008-2010, 280 North, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

// sprintf:

var formatRegex = /([^%]+|%(?:\d+\$)?[\+\-\ \#0]*[0-9\*]*(.[0-9\*]+)?[hlL]?[cbBdieEfgGosuxXpn%@])/g,
    tagRegex = /(%)(?:(\d+)\$)?([\+\-\ \#0]*)([0-9\*]*)((?:.[0-9\*]+)?)([hlL]?)([cbBdieEfgGosuxXpn%@])/;

exports.sprintf = function(format)
{
    var format = arguments[0],
        tokens = format.match(formatRegex),
        index = 0,
        result = "",
        arg = 1;

    for (var i = 0; i < tokens.length; i++)
    {
        var t = tokens[i];

        if (format.substring(index, index + t.length) !== t)
            return result;

        index += t.length;

        if (t.charAt(0) !== "%")
            result += t;

        else if (t === "%%")
            result += "%";

        else
        {
            var subtokens = t.match(tagRegex);

            if (subtokens.length !== 8 || subtokens[0] !== t)
                return result;

            var percentSign     = subtokens[1],
                argIndex        = subtokens[2],
                flags           = subtokens[3],
                widthString     = subtokens[4],
                precisionString = subtokens[5],
                length          = subtokens[6],
                specifier       = subtokens[7];

            if (argIndex === undefined || argIndex === null || argIndex === "")
                argIndex = arg++;
            else
                argIndex = Number(argIndex);

            var width = null;

            if (widthString == "*")
                width = arguments[argIndex];
            else if (widthString !== "")
                width = Number(widthString);

            var precision = null;

            if (precisionString === ".*")
                precision = arguments[argIndex];
            else if (precisionString !== "")
                precision = Number(precisionString.substring(1));

            var leftJustify = (flags.indexOf("-") >= 0),
                padZeros    = (flags.indexOf("0") >= 0),
                subresult   = "";

            if (/[bBdiufeExXo]/.test(specifier))
            {
                var num = Number(arguments[argIndex]),
                    sign = "";

                if (num < 0)
                {
                    sign = "-";
                }
                else
                {
                    if (flags.indexOf("+") >= 0)
                        sign = "+";
                    else if (flags.indexOf(" ") >= 0)
                        sign = " ";
                }

                if (specifier === "d" || specifier === "i" || specifier === "u")
                {
                    var number = String(Math.abs(Math.floor(num)));

                    subresult = justify(sign, "", number, "", width, leftJustify, padZeros)
                }

                if (specifier == "f")
                {
                    var number = String((precision !== null) ? Math.abs(num).toFixed(precision) : Math.abs(num)),
                        suffix = (flags.indexOf("#") >= 0 && number.indexOf(".") < 0) ? "." : "";

                    subresult = justify(sign, "", number, suffix, width, leftJustify, padZeros);
                }

                if (specifier === "e" || specifier === "E")
                {
                    var number = String(Math.abs(num).toExponential(precision !== null ? precision : 21)),
                        suffix = (flags.indexOf("#") >= 0 && number.indexOf(".") < 0) ? "." : "";

                    subresult = justify(sign, "", number, suffix, width, leftJustify, padZeros);
                }

                if (specifier == "x" || specifier == "X")
                {
                    var number = String(Math.abs(num).toString(16));
                    var prefix = (flags.indexOf("#") >= 0 && num != 0) ? "0x" : "";

                    subresult = justify(sign, prefix, number, "", width, leftJustify, padZeros);
                }

                if (specifier == "b" || specifier == "B")
                {
                    var number = String(Math.abs(num).toString(2));
                    var prefix = (flags.indexOf("#") >= 0 && num != 0) ? "0b" : "";

                    subresult = justify(sign, prefix, number, "", width, leftJustify, padZeros);
                }

                if (specifier == "o")
                {
                    var number = String(Math.abs(num).toString(8));
                    var prefix = (flags.indexOf("#") >= 0 && num != 0) ? "0" : "";

                    subresult = justify(sign, prefix, number, "", width, leftJustify, padZeros);
                }

                if (/[A-Z]/.test(specifier))
                    subresult = subresult.toUpperCase();
                else
                    subresult = subresult.toLowerCase();
            }
            else
            {
                var subresult = "";

                if (specifier === "%")
                    subresult = "%";
                else if (specifier === "c")
                    subresult = String(arguments[argIndex]).charAt(0);
                else if (specifier === "s" || specifier === "@")
                    subresult = String(arguments[argIndex]);
                else if (specifier === "p" || specifier === "n")
                    subresult = "";

                subresult = justify("", "", subresult, "", width, leftJustify, false);
            }

            result += subresult;
        }
    }

    return result;
}

function justify(sign, prefix, string, suffix, width, leftJustify, padZeros)
{
    var length = (sign.length + prefix.length + string.length + suffix.length);

    if (leftJustify)
    {
        return sign + prefix + string + suffix + pad(width - length, " ");
    }
    else
    {
        if (padZeros)
            return sign + prefix + pad(width - length, "0") + string + suffix;
        else
            return pad(width - length, " ") + sign + prefix + string + suffix;
    }
}

function pad(n, ch)
{
    return Array(MAX(0,n)+1).join(ch);
}
<|endoftext|>


<commit_before>/**
 * Created by nikolaykozhukharenko on 3/6/16.
 */

import { LOAD_ALL_ENROLMENTS, LOAD_ENROLMENT_BY_ID } from './constants'
import { _START, _SUCCESS, _FAIL } from '../../constants'
import createReducer from '../../utils/create-reducer'

const initialState = {
  isLoading: false,
  loaded: true,
  count: 0,
  limit: 50,
  offset: 0,
  resources: [],
  error: null
};

const actionHandlers = {
  [LOAD_ALL_ENROLMENTS + _START]: (state, action) => {
    console.log('LOAD_ALL_ENROLMENTS + _START ', action);
    return Object.assign(  {}, state,
      {
        isLoading: true
      },
      action
    )
  },

  [LOAD_ALL_ENROLMENTS + _SUCCESS]: (state, action) => {
    console.log('LOAD_ALL_ENROLMENTS _SUCCESS action', action);
    console.log('LOAD_ALL_ENROLMENTS _SUCCESS  state', state);
    return Object.assign({},
      state,
      {
        isLoading: false,
        loaded: true
      },
      action
    )
  },

  [LOAD_ALL_ENROLMENTS + _FAIL]: (state, action) => action.resources,

  [LOAD_ENROLMENT_BY_ID]: () => ({ token: null })
};

export default createReducer(initialState, actionHandlers)<commit_msg>add reverse map fro dictionary<commit_after>/**
 * Created by nikolaykozhukharenko on 3/6/16.
 */

import { LOAD_ALL_ENROLMENTS, LOAD_ENROLMENT_BY_ID } from './constants'
import { _START, _SUCCESS, _FAIL } from '../../constants'
import createReducer from '../../utils/create-reducer'

const initialState = {
  isLoading: false,
  loaded: true,
  count: 0,
  limit: 50,
  offset: 0,
  resources: [],
  error: null
};

const actionHandlers = {
  [LOAD_ALL_ENROLMENTS + _START]: (state, action) => {
    console.log('LOAD_ALL_ENROLMENTS + _START ', action);
    return Object.assign(  {}, state,
      {
        isLoading: true,
        loaded: false, // data is not loaded!
        resources: [] // clear data
      },
      action
    )
  },

  [LOAD_ALL_ENROLMENTS + _SUCCESS]: (state, action) => {
    console.log('LOAD_ALL_ENROLMENTS _SUCCESS action', action);
    console.log('LOAD_ALL_ENROLMENTS _SUCCESS  state', state);
    return Object.assign({},
      state,
      {
        isLoading: false,
        loaded: true
      },
      action
    )
  },

  [LOAD_ALL_ENROLMENTS + _FAIL]: (state, action) => action.resources,

  [LOAD_ENROLMENT_BY_ID]: () => ({ token: null })
};

export default createReducer(initialState, actionHandlers)<|endoftext|>


<commit_before>/**
	_moon.DatePicker_ is a control that can be used to display--or allow the
	selection of--a day, month, and year.

		{
			kind: "moon.DatePicker",
			noneText: "Pick a Date",
			content: "Date",
			onChange: "changed"
		}

	Set the _value_ property to a standard JavaScript Date object to initialize
	the picker, or to change it programmatically at runtime.
*/
enyo.kind({
	name: "moon.DatePicker",
	kind: "moon.DateTimePickerBase",
	//* @public
	published: {
		//* Optional minimum year value
		minYear: 1900,
		//* Optional maximum year value
		maxYear: 2099,
		//* Optional label for day
		dayText: moon.$L("day"),		// i18n "DAY" label in moon.DatePicker widget
		//* Optional label for month
		monthText: moon.$L("month"),	// i18n "MONTH" label in moon.DatePicker widget
		//* Optional label for year
		yearText: moon.$L("year")		// i18n "YEAR" label in moon.DatePicker widget
	},
	//*@protected
	iLibFormatType: "date",
	defaultOrdering: "mdy",
	setupPickers: function(ordering) {
		var orderingArr = ordering.toLowerCase().split("");
		var doneArr = [];
		var o,f,l;
		for(f = 0, l = orderingArr.length; f < l; f++) {
			o = orderingArr[f];
			if (doneArr.indexOf(o) < 0) {
				doneArr.push(o);
			}
		}

		for(f = 0, l = doneArr.length; f < l; f++) {
			o = doneArr[f];

			switch (o) {
			case 'd':
				this.createComponent(
					{classes: "moon-date-picker-wrap", components:[
						{kind:"moon.IntegerPicker", name:"day", classes:"moon-date-picker-field", min:1,
						max:this.monthLength(this.value.getFullYear(), this.value.getMonth()), value:this.value.getDate()},
						{name: "dayLabel", content: this.dayText, classes: "moon-date-picker-label moon-divider-text"}
					]});
				break;
			case 'm':
				this.createComponent(
					{classes: "moon-date-picker-wrap", components:[
						{kind:"moon.IntegerPicker", name:"month", classes:"moon-date-picker-field", min:1, max:12, value:this.value.getMonth()+1},
						{name: "monthLabel", content: this.monthText, classes: "moon-date-picker-label moon-divider-text"}
					]});
				break;
			case 'y':
				this.createComponent(
					{classes: "moon-date-picker-wrap year", components:[
						{kind:"moon.IntegerPicker", name:"year", classes:"moon-date-picker-field year", value:this.value.getFullYear(), min:this.minYear, max:this.maxYear},
						{name: "yearLabel", content: this.yearText, classes: "moon-date-picker-label moon-divider-text"}
					]});
				break;
			default:
				break;
			}
		}
		this.inherited(arguments);
	},
	formatValue: function() {
		if (this._tf) {
			return this._tf.format(new ilib.Date.GregDate({unixtime: this.value.getTime(), timezone:"UTC"}));
		} else {
			return this.getMonthName()[this.value.getMonth()] + " " + this.value.getDate() + ", " + this.value.getFullYear();
		}
	},
	updateValue: function(inSender, inEvent) {
		var day = this.$.day.getValue(),
			month = this.$.month.getValue()-1,
			year = this.$.year.getValue();

		var maxDays = this.monthLength(year, month);
		this.setValue(new Date(year, month, (day <= maxDays) ? day : maxDays));
	},
	setChildPickers: function(inOld) {
		this.$.year.setValue(this.value.getFullYear());
		this.$.month.setValue(this.value.getMonth()+1);

		if (inOld &&
			(inOld.getFullYear() != this.value.getFullYear() ||
			inOld.getMonth() != this.value.getMonth())) {
			this.$.day.setMax(this.monthLength(this.value.getFullYear(), this.value.getMonth()));
			this.$.day.updateScrollBounds();
			this.$.day.updateOverlays();
		}
		this.$.day.setValue(this.value.getDate());

		this.$.currentValue.setContent(this.formatValue());
	},
	getMonthName: function() {
		// Only used when ilib is not loaded
		return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
	},
	//* Returns number of days in a particular month/year.
	monthLength: function(inYear, inMonth) {
		return 32 - new Date(inYear, inMonth, 32).getDate();
	},
	yearTextChanged: function (inOldvalue, inNewValue) {
		this.$.yearLabel.setContent(inNewValue);
	},
	monthTextChanged: function (inOldvalue, inNewValue) {
		this.$.monthLabel.setContent(inNewValue);
	},
	dayTextChanged: function (inOldvalue, inNewValue) {
		this.$.dayLabel.setContent(inNewValue);
	}
});
<commit_msg>Update overlays after setting value<commit_after>/**
	_moon.DatePicker_ is a control that can be used to display--or allow the
	selection of--a day, month, and year.

		{
			kind: "moon.DatePicker",
			noneText: "Pick a Date",
			content: "Date",
			onChange: "changed"
		}

	Set the _value_ property to a standard JavaScript Date object to initialize
	the picker, or to change it programmatically at runtime.
*/
enyo.kind({
	name: "moon.DatePicker",
	kind: "moon.DateTimePickerBase",
	//* @public
	published: {
		//* Optional minimum year value
		minYear: 1900,
		//* Optional maximum year value
		maxYear: 2099,
		//* Optional label for day
		dayText: moon.$L("day"),		// i18n "DAY" label in moon.DatePicker widget
		//* Optional label for month
		monthText: moon.$L("month"),	// i18n "MONTH" label in moon.DatePicker widget
		//* Optional label for year
		yearText: moon.$L("year")		// i18n "YEAR" label in moon.DatePicker widget
	},
	//*@protected
	iLibFormatType: "date",
	defaultOrdering: "mdy",
	setupPickers: function(ordering) {
		var orderingArr = ordering.toLowerCase().split("");
		var doneArr = [];
		var o,f,l;
		for(f = 0, l = orderingArr.length; f < l; f++) {
			o = orderingArr[f];
			if (doneArr.indexOf(o) < 0) {
				doneArr.push(o);
			}
		}

		for(f = 0, l = doneArr.length; f < l; f++) {
			o = doneArr[f];

			switch (o) {
			case 'd':
				this.createComponent(
					{classes: "moon-date-picker-wrap", components:[
						{kind:"moon.IntegerPicker", name:"day", classes:"moon-date-picker-field", min:1,
						max:this.monthLength(this.value.getFullYear(), this.value.getMonth()), value:this.value.getDate()},
						{name: "dayLabel", content: this.dayText, classes: "moon-date-picker-label moon-divider-text"}
					]});
				break;
			case 'm':
				this.createComponent(
					{classes: "moon-date-picker-wrap", components:[
						{kind:"moon.IntegerPicker", name:"month", classes:"moon-date-picker-field", min:1, max:12, value:this.value.getMonth()+1},
						{name: "monthLabel", content: this.monthText, classes: "moon-date-picker-label moon-divider-text"}
					]});
				break;
			case 'y':
				this.createComponent(
					{classes: "moon-date-picker-wrap year", components:[
						{kind:"moon.IntegerPicker", name:"year", classes:"moon-date-picker-field year", value:this.value.getFullYear(), min:this.minYear, max:this.maxYear},
						{name: "yearLabel", content: this.yearText, classes: "moon-date-picker-label moon-divider-text"}
					]});
				break;
			default:
				break;
			}
		}
		this.inherited(arguments);
	},
	formatValue: function() {
		if (this._tf) {
			return this._tf.format(new ilib.Date.GregDate({unixtime: this.value.getTime(), timezone:"UTC"}));
		} else {
			return this.getMonthName()[this.value.getMonth()] + " " + this.value.getDate() + ", " + this.value.getFullYear();
		}
	},
	updateValue: function(inSender, inEvent) {
		var day = this.$.day.getValue(),
			month = this.$.month.getValue()-1,
			year = this.$.year.getValue();

		var maxDays = this.monthLength(year, month);
		this.setValue(new Date(year, month, (day <= maxDays) ? day : maxDays));
	},
	setChildPickers: function(inOld) {
		var updateDays = inOld &&
			(inOld.getFullYear() != this.value.getFullYear() ||
			inOld.getMonth() != this.value.getMonth());
		this.$.year.setValue(this.value.getFullYear());
		this.$.month.setValue(this.value.getMonth()+1);

		if (updateDays) {
			this.$.day.setMax(this.monthLength(this.value.getFullYear(), this.value.getMonth()));
			this.$.day.updateScrollBounds();
		}
		this.$.day.setValue(this.value.getDate());
		if (updateDays) {
			this.$.day.updateOverlays();
		}

		this.$.currentValue.setContent(this.formatValue());
	},
	getMonthName: function() {
		// Only used when ilib is not loaded
		return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
	},
	//* Returns number of days in a particular month/year.
	monthLength: function(inYear, inMonth) {
		return 32 - new Date(inYear, inMonth, 32).getDate();
	},
	yearTextChanged: function (inOldvalue, inNewValue) {
		this.$.yearLabel.setContent(inNewValue);
	},
	monthTextChanged: function (inOldvalue, inNewValue) {
		this.$.monthLabel.setContent(inNewValue);
	},
	dayTextChanged: function (inOldvalue, inNewValue) {
		this.$.dayLabel.setContent(inNewValue);
	}
});
<|endoftext|>


<commit_before>/*
This class stores samples for a badge and convert them into talking intervals
It uses a moving RMS to determine a threshold. Since multiplication is
easier than a root operation, we calculate MS and not RMS.
*/

function DataAnalyzer(sampleFreq) {
    this.sampleFreq= sampleFreq;

    // if at least this amount of time happens between a null signal
    // and a talk signal, they are considered to have started talking.
    var MIN_TALK_LENGTH = 300;
    // If we get no signal for this amount of time, consider them no
    // longer talking.
    var TALK_TIMEOUT = 1000;
    // Time length used for taking talking intervals in ms
    var BUFFER_LENGTH = 1000 * 60 * 200; // 5 minutes

    var samples = []; // array of samples : timestamp, volume
    var smoother = new SmoothArray(); // array object used for caluclating smooth value
    var rmsThreshold = new RMSThreshold();

    // Adds a sample. Code assumes that the timestamp is monotonically increasing
    // Timestamp is a Date object
    this.addSample = function(vol,timestamp) {
        // remove old objects samples array
        while (samples.length > 0  &&(timestamp - samples[0].timestamp > BUFFER_LENGTH)) {
            //console.log("Removing from samples:",samples[0]);
            samples.shift();
        }

        // Calc smoothened volume
        var sv = smoother.push(vol);

        // update RMS with new sample
        rmsThreshold.addSample(sv,timestamp);
        var meanSquare = rmsThreshold.getThreshold();

        // speaking indicator is 1 if smoothened volume is above the threshold
        var isSpeak = rmsThreshold.compareToThreshold(sv);

        // add sample to array
        samples.push({'vol': vol, 'sv' : sv, 'meanSquare' : meanSquare , 'isSpeak' : isSpeak,'timestamp': timestamp});
    };

    // Returns true if the two samples are "close" enough together
    this.isWithinTalkTimeout = function (curr, next) {
        var diffInMs = next - curr;
        return  diffInMs <= TALK_TIMEOUT;
    };

    // Returns true if talk interval is long enough
    this.isMinTalkLength = function(talkInterval) {
        var talkIntervalInMs = talkInterval.endTime - talkInterval.startTime;
        return talkIntervalInMs >= MIN_TALK_LENGTH;
    };

    this.generateTalkIntervals = function() {
        var talkIntervals = []; // startTime, endTime

        function isSpeak(sample) {
            return sample.isSpeak == 1;
        }
        var speakSamples = samples.filter(isSpeak);

        i = 0;
        while (i < speakSamples.length) {
            j = i;

            // traverse the array while samples belong to the same talking interval
            while (j < speakSamples.length - 1 && this.isWithinTalkTimeout(speakSamples[j].timestamp, speakSamples[j+1].timestamp))
            {
                j = j + 1
            }

            // new interval ended. Because each sample is sampleFreq millisecond long, we add this to the endTime
            var newTalkInterval = {'startTime':speakSamples[i].timestamp, 'endTime':new Date(speakSamples[j].timestamp.getTime() + this.sampleFreq)};
            if (this.isMinTalkLength(newTalkInterval)) {
                //console.log("Adding: ",newTalkInterval.startTime,".",newTalkInterval.startTime.getMilliseconds()," ",newTalkInterval.endTime,".",newTalkInterval.endTime.getMilliseconds());
                talkIntervals.push(newTalkInterval);
            }

            // set i to hold the next startTime
            i = j + 1
        }
        return talkIntervals;
    };

    this.getSamples = function() {
        return samples;
    };
}

// Class for handling the threshold
function RMSThreshold() {
    var samples = []; // samples used for thresholding
    var meanSquaredThreshold = 0; // (R)MS threshold. It's a sum of squared volumes
    var meanSquaredThresholdCount = 0; // number of elements in the sum. required for calcualting the mean

    // Time length used for RMS threshold in ms
    var BUFFER_LENGTH = 1000 * 30 * 1; // 30 seconds

    this.addSample = function(v,timestamp) {
        // remove old objects samples array and update MS
        while (samples.length > 0  &&(timestamp - samples[0].timestamp > BUFFER_LENGTH)) {
            var toDel = samples.shift();
            meanSquaredThreshold = meanSquaredThreshold - (toDel.v * toDel.v);
            meanSquaredThresholdCount--;
        }

        // adding sample and updating the threshold
        samples.push({'v': v, 'timestamp': timestamp});
        meanSquaredThreshold = meanSquaredThreshold + (v*v);
        meanSquaredThresholdCount++;
    };
    this.getThreshold = function() {
        return meanSquaredThreshold/meanSquaredThresholdCount;
    };

    this.compareToThreshold = function(v) {
        return v*v > meanSquaredThreshold/meanSquaredThresholdCount ? 1 : 0;
    }

}

// Class for smoothening the volume signal
function SmoothArray() {
    // Number of samples that will be used for smoothing the samples
    var SAMPLES_SMOOTHING = 5;
    var smoothArray = [];
    var pos = 0;

    this.push = function(vol) {
        // adds the sample to the correct location
        smoothArray[pos] = vol;
        pos = (pos +1) % SAMPLES_SMOOTHING;

        // returns smoothened value
        var sum = smoothArray.reduce(function(a, b) { return a + b; });
        var mean = sum / smoothArray.length;
        return mean;
    };

    this.getSmoothArray = function() {
        return smoothArray;
    }
}

function dateToString(d) {
    var s = d.getFullYear().toString()+"-"+d.getMonth().toString()+"-"+d.getDate().toString();
    s = s + " "+d.getHours().toString()+":"+d.getMinutes().toString()+":"+d.getSeconds()+"."+d.getMilliseconds().toString();
    return s;
}
<commit_msg>Fixed but in threshold book keeping. Code cleanup<commit_after>// if at least this amount of time happens between a null signal
// and a talk signal, they are considered to have started talking.
var MIN_TALK_LENGTH = 300;
// If we get no signal for this amount of time, consider them no
// longer talking.
var TALK_TIMEOUT = 1000;
// Time length used for taking talking intervals in ms
var BUFFER_LENGTH = 1000 * 60 * 5; // 5 minutes
// Time length used for RMS threshold in ms
var RMS_BUFFER_LENGTH = 1000 * 30 * 1; // 30 seconds

/*
This class stores samples for a badge and convert them into talking intervals
It uses a moving RMS to determine a threshold. Since multiplication is
easier than a root operation, we calculate MS and not RMS.
*/
function DataAnalyzer(sampleFreq) {
    this.sampleFreq= sampleFreq;
    var samples = []; // array of samples : timestamp, volume
    var smoother = new SmoothArray(); // array object used for caluclating smooth value
    var rmsThreshold = new RMSThreshold();

    this.purgeSamples = function(timestamp) {
        while (samples.length > 0  &&(timestamp - samples[0].timestamp > BUFFER_LENGTH)) {
            //console.log("Removing from samples:",samples[0]);
            samples.shift();
        }
    }

    // Adds a sample. Code assumes that the timestamp is monotonically increasing
    // Timestamp is a Date object
    this.addSample = function(vol,timestamp) {
        // remove old objects samples array
        this.purgeSamples(timestamp);

        // Calc smoothened volume
        var sv = smoother.push(vol);

        // update RMS with new sample
        rmsThreshold.addSample(sv,timestamp);
        var meanSquare = rmsThreshold.getThreshold();

        // speaking indicator is 1 if smoothened volume is above the threshold
        var isSpeak = rmsThreshold.compareToThreshold(sv);

        // add sample to array
        samples.push({'vol': vol, 'sv' : sv, 'meanSquare' : meanSquare , 'isSpeak' : isSpeak,'timestamp': timestamp});
    };

    // Returns true if the two samples are "close" enough together
    this.isWithinTalkTimeout = function (curr, next) {
        var diffInMs = next - curr;
        return  diffInMs <= TALK_TIMEOUT;
    };

    // Returns true if talk interval is long enough
    this.isMinTalkLength = function(talkInterval) {
        var talkIntervalInMs = talkInterval.endTime - talkInterval.startTime;
        return talkIntervalInMs >= MIN_TALK_LENGTH;
    };

    this.generateTalkIntervals = function() {
        var talkIntervals = []; // startTime, endTime

        function isSpeak(sample) {
            return sample.isSpeak == 1;
        }
        var speakSamples = samples.filter(isSpeak);

        i = 0;
        while (i < speakSamples.length) {
            j = i;

            // traverse the array while samples belong to the same talking interval
            while (j < speakSamples.length - 1 && this.isWithinTalkTimeout(speakSamples[j].timestamp, speakSamples[j+1].timestamp))
            {
                j = j + 1
            }

            // new interval ended. Because each sample is sampleFreq millisecond long, we add this to the endTime
            var newTalkInterval = {'startTime':speakSamples[i].timestamp, 'endTime':new Date(speakSamples[j].timestamp.getTime() + this.sampleFreq)};
            if (this.isMinTalkLength(newTalkInterval)) {
                //console.log("Adding: ",newTalkInterval.startTime,".",newTalkInterval.startTime.getMilliseconds()," ",newTalkInterval.endTime,".",newTalkInterval.endTime.getMilliseconds());
                talkIntervals.push(newTalkInterval);
            }

            // set i to hold the next startTime
            i = j + 1
        }
        return talkIntervals;
    };

    this.getSamples = function() {
        return samples;
    };
}

/*
Class for handling the threshold
 */
function RMSThreshold() {
    var samples = []; // samples used for thresholding
    var meanSquaredThreshold = 0; // (R)MS threshold. It's a sum of squared volumes
    var meanSquaredThresholdCount = 0; // number of elements in the sum. required for calcualting the mean

    this.addSample = function(v,timestamp) {
        // remove old objects samples array and update MS
        while (samples.length > 0  &&(timestamp - samples[0].timestamp > RMS_BUFFER_LENGTH)) {
            var toDel = samples.shift();
            meanSquaredThreshold = meanSquaredThreshold - (toDel.v * toDel.v);
            meanSquaredThresholdCount--;
        }

        // adding sample and updating the threshold
        samples.push({'v': v, 'timestamp': timestamp});
        meanSquaredThreshold = meanSquaredThreshold + (v*v);
        meanSquaredThresholdCount++;
    };
    this.getThreshold = function() {
        return meanSquaredThreshold/meanSquaredThresholdCount;
    };

    this.compareToThreshold = function(v) {
        return v*v > meanSquaredThreshold/meanSquaredThresholdCount ? 1 : 0;
    }

}

/*
Class for smoothening the volume signal
*/
function SmoothArray() {
    // Number of samples that will be used for smoothing the samples
    var SAMPLES_SMOOTHING = 5;
    var smoothArray = [];
    var pos = 0;

    this.push = function(vol) {
        // adds the sample to the correct location
        smoothArray[pos] = vol;
        pos = (pos +1) % SAMPLES_SMOOTHING;

        // returns smoothened value
        var sum = smoothArray.reduce(function(a, b) { return a + b; });
        var mean = sum / smoothArray.length;
        return mean;
    };

    this.getSmoothArray = function() {
        return smoothArray;
    }
}

function dateToString(d) {
    var s = d.getFullYear().toString()+"-"+d.getMonth().toString()+"-"+d.getDate().toString();
    s = s + " "+d.getHours().toString()+":"+d.getMinutes().toString()+":"+d.getSeconds()+"."+d.getMilliseconds().toString();
    return s;
}
<|endoftext|>


<commit_before>import { observable } from "mobx";

export default class ProjectStore {
  @observable name = "";
  @observable tests = [];
  @observable suite = [];
}
<commit_msg>set the name in the constructor<commit_after>import { observable } from "mobx";

export default class ProjectStore {
  @observable name = "";
  @observable tests = [];
  @observable suite = [];

  constructor(name) {
    this.name = name;
  }
}
<|endoftext|>


<commit_before>(function (enyo, scope) {

	/**
	* An [Async]{@link enyo.Async} task specifically designed to wrap [JSONP]{@glossary JSONP}
	* requests to a remote server. Be sure to read about the use cases for
	* [JSONP]{@glossary JSONP} requests, along with the document on
	* [Consuming Web Services](building-apps/managing-data/consuming-web-services.html)
	* in the Enyo Developer Guide.
	*
	* @class enyo.JsonRequest
	* @extends enyo.Async
	* @public
	*/
	enyo.kind(
		/** @lends enyo.JsonRequest.prototype */ {

		/**
		* @private
		*/
		name: 'enyo.JsonpRequest',

		/**
		* @private
		*/
		kind: 'enyo.Async',

		/**
		* @private
		*/
		published: {

			/**
			* The URL for the service.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default ''
			* @public
			*/
			url: '',

			/**
			* The optional character set to use to interpret the return data.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default null
			* @public
			*/
			charset: null,

			/**
			* The name of the [function]{@glossary Function} that is included in the
			* encoded arguments and used to wrap the return value from the server.
			* This may also be set to `null` in some cases.
			*
			* @see enyo.JsonRequest#overrideCallback
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default 'callback'
			* @public
			*/
			callbackName: 'callback',

			/**
			* If `true`, will append a random number as a parameter for GET requests to
			* (attempt to) force a new fetch of the resource instead of reusing a local
			* cache.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {Boolean}
			* @default true
			* @public
			*/
			cacheBust: true,

			/**
			* In cases where a backend is inflexible with regard to
			* [callback]{@link enyo.JsonRequest#callback} names, this property may be used to
			* specify a global [function]{@glossary Function} instead. Note that when using
			* this, it will replace any existing function with the given
			* name and only one [JsonRequest]{@link enyo.JsonRequest} using this property may
			* be active at a time.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default null
			* @public
			*/
			overrideCallback: null
		},

		/**
		* @private
		*/
		protectedStatics: {
			// Counter to allow creation of unique name for each JSONP request
			nextCallbackID: 0
		},

		/**
		* @private
		*/
		addScriptElement: function () {
			var script = document.createElement('script');
			script.src = this.src;
			script.async = 'async';
			if (this.charset) {
				script.charset = this.charset;
			}
			// most modern browsers also have an onerror handler
			script.onerror = this.bindSafely(function() {
				// we don't get an error code, so we'll just use the generic 400 error status
				this.fail(400);
			});
			// add script before existing script to make sure it's in a valid part of document
			// http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/
			var first = document.getElementsByTagName('script')[0];
			first.parentNode.insertBefore(script, first);
			this.scriptTag = script;
		},

		/**
		* @private
		*/
		removeScriptElement: function () {
			var script = this.scriptTag;
			this.scriptTag = null;
			script.onerror = null;
			if (script.parentNode) {
				script.parentNode.removeChild(script);
			}
		},

		/**
		* @private
		*/
		constructor: enyo.inherit(function (sup) {
			return function (params) {
				enyo.mixin(this, params);
				sup.apply(this, arguments);
			};
		}),

		/**
		* Initiates the asynchronous routine and will supply the given value if it completes
		* successfully. Overloaded from [enyo.Async.go()]{@link enyo.Async#go}.
		*
		* @param {*} value The value to pass to responders.
		* @returns {this} The callee for chaining.
		* @public
		*/
		go: function (value) {
			this.startTimer();
			this.jsonp(value);
			return this;
		},

		/**
		* @private
		*/
		jsonp: function (params) {
			var callbackFunctionName = this.overrideCallback ||
				'enyo_jsonp_callback_' + (enyo.JsonpRequest.nextCallbackID++);
			//
			this.src = this.buildUrl(params, callbackFunctionName);
			this.addScriptElement();
			//
			window[callbackFunctionName] = this.bindSafely(this.respond);
			//
			// setup cleanup handlers for JSONP completion and failure
			var cleanup = this.bindSafely(function() {
				this.removeScriptElement();
				window[callbackFunctionName] = null;
			});
			this.response(cleanup);
			this.error(cleanup);
		},

		/**
		* @private
		*/
		buildUrl: function(params, fn) {
			var parts = this.url.split('?');
			var uri = parts.shift() || '';
			var args = parts.length? parts.join('?').split('&'): [];
			//
			var bodyArgs = this.bodyArgsFromParams(params, fn);
			args.push(bodyArgs);
			if (this.cacheBust) {
				args.push(Math.random());
			}
			//
			return [uri, args.join('&')].join('?');
		},

		/**
		* If `params` is a string, we follow the convention of replacing the string
		* `'=?'` with the callback name. If `params` is an object (the more common
		* case), we add an argument using the `callbackName` published property.
		*
		* @private
		*/
		bodyArgsFromParams: function(params, fn) {
			if (enyo.isString(params)) {
				return params.replace('=?', '=' + fn);
			} else {
				params = enyo.clone(params, true);
				if (this.callbackName) {
					params[this.callbackName] = fn;
				}
				return enyo.Ajax.objectToQuery(params);
			}
		}
	});

})(enyo, this);<commit_msg>BHV-12191: Fix bodyArgsFromParams to work with a null params<commit_after>(function (enyo, scope) {

	/**
	* An [Async]{@link enyo.Async} task specifically designed to wrap [JSONP]{@glossary JSONP}
	* requests to a remote server. Be sure to read about the use cases for
	* [JSONP]{@glossary JSONP} requests, along with the document on
	* [Consuming Web Services](building-apps/managing-data/consuming-web-services.html)
	* in the Enyo Developer Guide.
	*
	* @class enyo.JsonRequest
	* @extends enyo.Async
	* @public
	*/
	enyo.kind(
		/** @lends enyo.JsonRequest.prototype */ {

		/**
		* @private
		*/
		name: 'enyo.JsonpRequest',

		/**
		* @private
		*/
		kind: 'enyo.Async',

		/**
		* @private
		*/
		published: {

			/**
			* The URL for the service.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default ''
			* @public
			*/
			url: '',

			/**
			* The optional character set to use to interpret the return data.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default null
			* @public
			*/
			charset: null,

			/**
			* The name of the [function]{@glossary Function} that is included in the
			* encoded arguments and used to wrap the return value from the server.
			* This may also be set to `null` in some cases.
			*
			* @see enyo.JsonRequest#overrideCallback
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default 'callback'
			* @public
			*/
			callbackName: 'callback',

			/**
			* If `true`, will append a random number as a parameter for GET requests to
			* (attempt to) force a new fetch of the resource instead of reusing a local
			* cache.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {Boolean}
			* @default true
			* @public
			*/
			cacheBust: true,

			/**
			* In cases where a backend is inflexible with regard to
			* [callback]{@link enyo.JsonRequest#callback} names, this property may be used to
			* specify a global [function]{@glossary Function} instead. Note that when using
			* this, it will replace any existing function with the given
			* name and only one [JsonRequest]{@link enyo.JsonRequest} using this property may
			* be active at a time.
			*
			* @memberof enyo.JsonRequest.prototype
			* @type {String}
			* @default null
			* @public
			*/
			overrideCallback: null
		},

		/**
		* @private
		*/
		protectedStatics: {
			// Counter to allow creation of unique name for each JSONP request
			nextCallbackID: 0
		},

		/**
		* @private
		*/
		addScriptElement: function () {
			var script = document.createElement('script');
			script.src = this.src;
			script.async = 'async';
			if (this.charset) {
				script.charset = this.charset;
			}
			// most modern browsers also have an onerror handler
			script.onerror = this.bindSafely(function() {
				// we don't get an error code, so we'll just use the generic 400 error status
				this.fail(400);
			});
			// add script before existing script to make sure it's in a valid part of document
			// http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/
			var first = document.getElementsByTagName('script')[0];
			first.parentNode.insertBefore(script, first);
			this.scriptTag = script;
		},

		/**
		* @private
		*/
		removeScriptElement: function () {
			var script = this.scriptTag;
			this.scriptTag = null;
			script.onerror = null;
			if (script.parentNode) {
				script.parentNode.removeChild(script);
			}
		},

		/**
		* @private
		*/
		constructor: enyo.inherit(function (sup) {
			return function (params) {
				enyo.mixin(this, params);
				sup.apply(this, arguments);
			};
		}),

		/**
		* Initiates the asynchronous routine and will supply the given value if it completes
		* successfully. Overloaded from [enyo.Async.go()]{@link enyo.Async#go}.
		*
		* @param {*} value The value to pass to responders.
		* @returns {this} The callee for chaining.
		* @public
		*/
		go: function (value) {
			this.startTimer();
			this.jsonp(value);
			return this;
		},

		/**
		* @private
		*/
		jsonp: function (params) {
			var callbackFunctionName = this.overrideCallback ||
				'enyo_jsonp_callback_' + (enyo.JsonpRequest.nextCallbackID++);
			//
			this.src = this.buildUrl(params, callbackFunctionName);
			this.addScriptElement();
			//
			window[callbackFunctionName] = this.bindSafely(this.respond);
			//
			// setup cleanup handlers for JSONP completion and failure
			var cleanup = this.bindSafely(function() {
				this.removeScriptElement();
				window[callbackFunctionName] = null;
			});
			this.response(cleanup);
			this.error(cleanup);
		},

		/**
		* @private
		*/
		buildUrl: function(params, fn) {
			var parts = this.url.split('?');
			var uri = parts.shift() || '';
			var args = parts.length? parts.join('?').split('&'): [];
			//
			var bodyArgs = this.bodyArgsFromParams(params, fn);
			args.push(bodyArgs);
			if (this.cacheBust) {
				args.push(Math.random());
			}
			//
			return [uri, args.join('&')].join('?');
		},

		/**
		* If `params` is a string, we follow the convention of replacing the string
		* `'=?'` with the callback name. If `params` is an object (the more common
		* case), we add an argument using the `callbackName` published property.
		*
		* @private
		*/
		bodyArgsFromParams: function(params, fn) {
			if (enyo.isString(params)) {
				return params.replace('=?', '=' + fn);
			} else {
				params = enyo.clone((params == null) ? {} : params, true);
				if (this.callbackName) {
					params[this.callbackName] = fn;
				}
				return enyo.Ajax.objectToQuery(params);
			}
		}
	});

})(enyo, this);<|endoftext|>


<commit_before>(function () {
    'use strict';

    var module = angular.module('TextCoder.controllers', [
        'TextCoder.services',
        'angularSpinner',
        'angucomplete-alt',
        'smart-table'
    ]);

    module.config(['$interpolateProvider', function ($interpolateProvider) {
        $interpolateProvider.startSymbol('{$');
        $interpolateProvider.endSymbol('$}');
    }]);

    module.config(['usSpinnerConfigProvider', function (usSpinnerConfigProvider) {
        usSpinnerConfigProvider.setDefaults({
            color: '#111'
        });
    }]);

    var DictionaryController = function ($scope, Dictionary) {
        $scope.Dictionary = Dictionary;

    };
    DictionaryController.$inject = [
        '$scope',
        'TextCoder.services.Dictionary'
    ];
    module.controller('TextCoder.controllers.DictionaryController', DictionaryController);

    var ViewController = function ($scope, Dictionary, SVMResult, FeatureVector, UserFeatures, usSpinnerService) {

        $scope.spinnerOptions = {
            radius: 20,
            width: 6,
            length: 10,
            color: "#000000"
        };
        var dist_max_height = 20; // in pixel

        $scope.svm_results = undefined;
        $scope.vector = undefined;
        $scope.features = [];

        $scope.load = function(){
            var request = SVMResult.load(Dictionary.id);
            if (request) {
                usSpinnerService.spin('table-spinner');
                request.then(function() {
                    usSpinnerService.stop('table-spinner');
                    SVMResult.dist_scale.range([0, dist_max_height]);
                    $scope.svm_results = SVMResult.data;
                });
            }

        };

        // load the svm results
        $scope.load();

        $scope.style = function(code, codeIndex){
            var fullColors =
                [["#f6faea","#e5f1c0","#d4e897","#bada58","#98bc29","#769220","#556817","#333f0e","#222a09"],
                ["#f4eef6","#dfcde4","#bf9cc9","#aa7bb7","#865195","#683f74","#4a2d53","#35203b","#1e1221"],
                ["#fce8f1","#f7bbd4","#f28db7","#ec5f9a","#e41b6e","#b71558","#911146","#720d37","#440821"],
                ["#e9f0fb","#bed1f4","#92b3ed","#5185e1","#2361cf","#1a4899","#12336d","#0b1f41","#07142c"],
                ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]];

            var colorIndex = 0;
            if (codeIndex < fullColors.length) { colorIndex = codeIndex;}
            var colors = fullColors[colorIndex];

            var css = {
                'background-color' : 'none',
                'color': 'black'
            };
            var code_order = (Math.floor(code.order / 2));
            if (code_order  < colors.length ){
                css['background-color'] = colors[colors.length - code_order  - 1];
                if ( code_order  < 3)
                    css['color'] = '#ccc';
            }
            return css;
        };
        $scope.dist = function(code){
            var css = {
                'background-color': 'steelblue',
                'width' : 15,
                'height': SVMResult.dist_scale(code.train_count)
            };
            return css;
        };
        $scope.on_off = function(count){
            var css = {
                'background-color' : 'none',
                'color': 'black'
            };
            if (count > 0){
                css['background-color'] = "#fee0d2";
                //css['color'] = '#ccc';
            }
            return css;
        };
        $scope.active = function(tid){
            return ($scope.vector && $scope.vector.message.id == tid) ? "active" : "";
        };

        $scope.load_vector = function(tid){
            var request = FeatureVector.load(tid);
            if (request) {
                usSpinnerService.spin('vector-spinner');
                request.then(function() {
                    usSpinnerService.stop('vector-spinner');

                    var text = FeatureVector.data.message.text;
                    var characters = text.split("");
                    var tokens = FeatureVector.data.tokens;

                    var tokenItems = [];
                    var charToToken = [];

                    var lowerText = text.toLowerCase();
                    var currentIndex = 0;
                    for (var i = 0; i < tokens.length; i++)
                    {
                        var token = tokens[i];
                        if (token != null && token.length > 0)
                        {
                            var foundIndex = lowerText.substr(currentIndex).indexOf(token) + currentIndex;

                            var tokenItem = {
                                text: token,
                                index: i
                            };

                            currentIndex = foundIndex;
                            tokenItem.startIndex = currentIndex;
                            currentIndex += token.length - 1;
                            tokenItem.endIndex = currentIndex;

                            tokenItems.push(tokenItem);

                            for (var j = tokenItem.startIndex; j <= tokenItem.endIndex; j++)
                            {
                                charToToken[j] = i;
                            }
                        }
                    }

                    $scope.vector = FeatureVector.data;
                    $scope.vector.message.tokens = tokenItems;
                    $scope.vector.message.characters = characters;
                    $scope.vector.message.charToToken = charToToken;
                });
            }
        };

        $scope.getter = {
            'vector': function(feature){
                return $scope.vector.feature_vector[feature.word_index];
            }
        };

        // Feature selection logic and states
        $scope.hoveredCharStart = -1;
        $scope.hoveredCharEnd = -1;
        $scope.clickStartTokenItem = undefined;
        $scope.selectedTokens = undefined;
        $scope.selectedTokenIndices = new Map();

        $scope.featureList = {};

        var updateSelection = function(startIndex, endIndex, isSelected, shouldClear) {
            if (shouldClear) {
                $scope.selectedTokenIndices.clear();
            }

            for (var i = startIndex; i <= endIndex; i++) {
                var existing = $scope.selectedTokenIndices.get(i);
                if (existing == i && !isSelected) {
                    $scope.selectedTokenIndices.delete(i);
                }
                else if (existing != i && isSelected) {
                    $scope.selectedTokenIndices.set(i, i);
                }
            }
        };

        var isTokenSelectedAtCharIndex = function (charIndex){
            if ($scope.vector && $scope.vector.message) {
                var tokenIndex = $scope.vector.message.charToToken[charIndex];
                if (tokenIndex != undefined && $scope.selectedTokenIndices.get(tokenIndex) == tokenIndex) {
                    return true;
                }
            }

            return false;
        };

        $scope.onCharMouseEnter = function(charIndex){
            //console.log("onCharMouseEnter:" + charIndex);

            if ($scope.vector && $scope.vector.message){
                var tokenIndex = $scope.vector.message.charToToken[charIndex];

                if (tokenIndex != undefined && $scope.vector.message.tokens[tokenIndex] != undefined) {
                    var tokenItem = $scope.vector.message.tokens[tokenIndex];
                    $scope.hoveredCharStart = tokenItem.startIndex;
                    $scope.hoveredCharEnd = tokenItem.endIndex;

                    // If we're in the middle of selection, update selected char indices
                    if ($scope.clickStartTokenItem != undefined) {

                        var ctrlClick = event.ctrlKey || (event.metaKey && !event.ctrlKey);

                        if (tokenIndex < $scope.clickStartTokenItem.index) {
                            updateSelection(tokenIndex, $scope.clickStartTokenItem.index, true, !ctrlClick);
                        }
                        else if (tokenIndex > $scope.clickStartTokenItem.index) {
                            updateSelection($scope.clickStartTokenItem.index, tokenIndex, true, !ctrlClick);
                        }
                    }
                }
                else {
                    $scope.hoveredCharStart = -1;
                    $scope.hoveredCharEnd = -1;
                }
            }
        };

        $scope.onCharMouseLeave = function(charIndex){
            //console.log("onCharMouseLeave:" + charIndex);

            $scope.hoveredCharStart = -1;
            $scope.hoveredCharEnd = -1;
        };

        $scope.onCharMouseDown = function(charIndex, event){
            //console.log("onCharMouseDown:" + charIndex);

            if ($scope.vector && $scope.vector.message) {

                var tokenIndex = $scope.vector.message.charToToken[charIndex];

                if (tokenIndex != undefined && $scope.vector.message.tokens[tokenIndex] != undefined) {

                    var tokenItem = $scope.vector.message.tokens[tokenIndex];

                    var ctrlClick = event.ctrlKey || (event.metaKey && !event.ctrlKey);

                    // if there was a selection at this tokenIndex and mouse was clicked with command/ctrl button,
                    // clear the selection on this token index
                    if ($scope.selectedTokenIndices.get(tokenIndex) == tokenIndex && ctrlClick) {
                        $scope.clickStartTokenItem = undefined;
                        updateSelection(tokenIndex, tokenIndex, false, false);
                    }
                    else {
                        $scope.clickStartTokenItem = tokenItem;
                        updateSelection(tokenIndex, tokenIndex, true, !ctrlClick);
                    }
                }
                else {
                    $scope.clickStartTokenItem = undefined;
                    $scope.selectedTokenIndices.clear();
                }
            }
        };

        $scope.onCharMouseUp = function(charIndex) {
            $scope.clickStartTokenItem = undefined;
            $scope.selectedTokens = undefined;

            if ($scope.selectedTokenIndices.size > 0) {
                if ($scope.vector && $scope.vector.message) {

                    // Get sorted list of selected token indices
                    var indices = [];
                    $scope.selectedTokenIndices.forEach(function (val) {
                        indices.push(val);
                    });
                    indices.sort(function (a, b) {
                        return a - b;
                    });

                    var tokens = [];
                    var currentTokenIndex = -1;
                    for (var i = 0; i < indices.length; i++) {
                        var tokenIndex = indices[i];

                        if (tokenIndex != currentTokenIndex) {
                            tokens.push($scope.vector.message.tokens[tokenIndex].text);
                            currentTokenIndex = tokenIndex;
                        }
                    }

                    $scope.selectedTokens = tokens;
                }
            }
        };

        $scope.charStyle = function(charIndex) {
            var style = {};
            if (charIndex >= $scope.hoveredCharStart && charIndex <= $scope.hoveredCharEnd) {
                style["background"] = "#ffcc99";
            }

            if (isTokenSelectedAtCharIndex(charIndex) || (isTokenSelectedAtCharIndex(charIndex - 1) && isTokenSelectedAtCharIndex(charIndex + 1))) {
                style["background"] = "#ff6600";
            }
            return style;
        };

        $scope.addFeature = function(tokens){
            if (tokens && tokens.length > 0){

                var key = tokens.join(" ");
                console.log("addFeature for: " + key);

                // check if it already exists
                var existingTokens = $scope.featureList[key];

                if (!existingTokens) {
                    var request = UserFeatures.add(tokens);
                    if (request) {
                        usSpinnerService.spin('vector-spinner');
                        request.then(function() {
                            usSpinnerService.stop('vector-spinner');
                            var featureId = UserFeatures.data;
                            $scope.featureList[key] = {
                                id: featureId,
                                tokens: tokens
                            };
                        });
                    }
                }
                else {
                    console.log("feature already exists: " + key);
                }

                $scope.clickStartTokenItem = undefined;
                $scope.selectedTokens = null;
                $scope.selectedTokenIndices.clear();
            }
        };

        $scope.removeFeature = function(feature){
            if (feature){
                var key = feature.tokens.join(" ");
                console.log("removeFeature for: " + key);

                // check if it already exists
                var existingTokens = $scope.featureList[key];

                if (existingTokens) {

                    var request = UserFeatures.remove(feature.id);
                    if (request) {
                        usSpinnerService.spin('vector-spinner');
                        request.then(function() {
                            usSpinnerService.stop('vector-spinner');
                            delete $scope.featureList[key];
                        });
                    }
                }
                else {
                    console.log("feature does not exist: " + key);
                }
            }
        }
    };

    ViewController.$inject = [
        '$scope',
        'TextCoder.services.Dictionary',
        'TextCoder.services.SVMResult',
        'TextCoder.services.FeatureVector',
        'TextCoder.services.UserFeatures',
        'usSpinnerService'
    ];
    module.controller('TextCoder.controllers.ViewController', ViewController);

    module.directive('datetimeFormat', function() {
      return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {
          ngModelController.$parsers.push(function(data) {
            //convert data from view format to model format
            data = moment.utc(data, "YYYY-MM-DD HH:mm:ss");
            if (data.isValid()) return data.toDate();
            else return undefined;
          });

          ngModelController.$formatters.push(function(data) {
            //convert data from model format to view format
              if (data !== undefined) return moment.utc(data).format("YYYY-MM-DD HH:mm:ss"); //converted
              return data;
          });
        }
      }
    });

    module.directive('whenScrolled', function() {
        return function(scope, element, attr) {
            var raw = element[0];

            var checkBounds = function(evt) {
                if (Math.abs(raw.scrollTop + $(raw).height() - raw.scrollHeight) < 10) {
                    scope.$apply(attr.whenScrolled);
                }

            };
            element.bind('scroll load', checkBounds);
        };
    });

    module.directive('ngEnter', function () {
        return function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if(event.which === 13) {
                    scope.$apply(function (){
                        scope.$eval(attrs.ngEnter);
                    });

                    event.preventDefault();
                }
            });
        };
    });
})();
<commit_msg>fix tweet feature ordering problem<commit_after>(function () {
    'use strict';

    var module = angular.module('TextCoder.controllers', [
        'TextCoder.services',
        'angularSpinner',
        'angucomplete-alt',
        'smart-table'
    ]);

    module.config(['$interpolateProvider', function ($interpolateProvider) {
        $interpolateProvider.startSymbol('{$');
        $interpolateProvider.endSymbol('$}');
    }]);

    module.config(['usSpinnerConfigProvider', function (usSpinnerConfigProvider) {
        usSpinnerConfigProvider.setDefaults({
            color: '#111'
        });
    }]);

    var DictionaryController = function ($scope, Dictionary) {
        $scope.Dictionary = Dictionary;

    };
    DictionaryController.$inject = [
        '$scope',
        'TextCoder.services.Dictionary'
    ];
    module.controller('TextCoder.controllers.DictionaryController', DictionaryController);

    var ViewController = function ($scope, Dictionary, SVMResult, FeatureVector, UserFeatures, usSpinnerService) {

        $scope.spinnerOptions = {
            radius: 20,
            width: 6,
            length: 10,
            color: "#000000"
        };
        var dist_max_height = 20; // in pixel

        $scope.svm_results = undefined;
        $scope.vector = undefined;
        $scope.features = [];

        $scope.load = function(){
            var request = SVMResult.load(Dictionary.id);
            if (request) {
                usSpinnerService.spin('table-spinner');
                request.then(function() {
                    usSpinnerService.stop('table-spinner');
                    SVMResult.dist_scale.range([0, dist_max_height]);
                    $scope.svm_results = SVMResult.data;
                });
            }

        };

        // load the svm results
        $scope.load();

        $scope.style = function(code, codeIndex){
            var fullColors =
                [["#f6faea","#e5f1c0","#d4e897","#bada58","#98bc29","#769220","#556817","#333f0e","#222a09"],
                ["#f4eef6","#dfcde4","#bf9cc9","#aa7bb7","#865195","#683f74","#4a2d53","#35203b","#1e1221"],
                ["#fce8f1","#f7bbd4","#f28db7","#ec5f9a","#e41b6e","#b71558","#911146","#720d37","#440821"],
                ["#e9f0fb","#bed1f4","#92b3ed","#5185e1","#2361cf","#1a4899","#12336d","#0b1f41","#07142c"],
                ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]];

            var colorIndex = 0;
            if (codeIndex < fullColors.length) { colorIndex = codeIndex;}
            var colors = fullColors[colorIndex];

            var css = {
                'background-color' : 'none',
                'color': 'black'
            };
            var code_order = (Math.floor(code.order / 2));
            if (code_order  < colors.length ){
                css['background-color'] = colors[colors.length - code_order  - 1];
                if ( code_order  < 3)
                    css['color'] = '#ccc';
            }
            return css;
        };
        $scope.dist = function(code){
            var css = {
                'background-color': 'steelblue',
                'width' : 15,
                'height': SVMResult.dist_scale(code.train_count)
            };
            return css;
        };
        $scope.on_off = function(count){
            var css = {
                'background-color' : 'none',
                'color': 'black'
            };
            if (count > 0){
                css['background-color'] = "#fee0d2";
                //css['color'] = '#ccc';
            }
            return css;
        };
        $scope.active = function(tid){
            return ($scope.vector && $scope.vector.message.id == tid) ? "active" : "";
        };

        $scope.load_vector = function(tid){
            var request = FeatureVector.load(tid);
            if (request) {
                usSpinnerService.spin('vector-spinner');
                request.then(function() {
                    usSpinnerService.stop('vector-spinner');

                    var text = FeatureVector.data.message.text;
                    var characters = text.split("");
                    var tokens = FeatureVector.data.tokens;

                    var tokenItems = [];
                    var charToToken = [];

                    var lowerText = text.toLowerCase();
                    var currentIndex = 0;
                    for (var i = 0; i < tokens.length; i++)
                    {
                        var token = tokens[i];
                        if (token != null && token.length > 0)
                        {
                            var foundIndex = lowerText.substr(currentIndex).indexOf(token) + currentIndex;

                            var tokenItem = {
                                text: token,
                                index: i
                            };

                            currentIndex = foundIndex;
                            tokenItem.startIndex = currentIndex;
                            currentIndex += token.length - 1;
                            tokenItem.endIndex = currentIndex;

                            tokenItems.push(tokenItem);

                            for (var j = tokenItem.startIndex; j <= tokenItem.endIndex; j++)
                            {
                                charToToken[j] = i;
                            }
                        }
                    }

                    $scope.vector = FeatureVector.data;
                    $scope.vector.message.tokens = tokenItems;
                    $scope.vector.message.characters = characters;
                    $scope.vector.message.charToToken = charToToken;
                });
            }
        };

        $scope.getter = {
            'vector': function(feature){
                return $scope.vector.feature_vector[feature.feature_index];
            }
        };

        // Feature selection logic and states
        $scope.hoveredCharStart = -1;
        $scope.hoveredCharEnd = -1;
        $scope.clickStartTokenItem = undefined;
        $scope.selectedTokens = undefined;
        $scope.selectedTokenIndices = new Map();

        $scope.featureList = {};

        var updateSelection = function(startIndex, endIndex, isSelected, shouldClear) {
            if (shouldClear) {
                $scope.selectedTokenIndices.clear();
            }

            for (var i = startIndex; i <= endIndex; i++) {
                var existing = $scope.selectedTokenIndices.get(i);
                if (existing == i && !isSelected) {
                    $scope.selectedTokenIndices.delete(i);
                }
                else if (existing != i && isSelected) {
                    $scope.selectedTokenIndices.set(i, i);
                }
            }
        };

        var isTokenSelectedAtCharIndex = function (charIndex){
            if ($scope.vector && $scope.vector.message) {
                var tokenIndex = $scope.vector.message.charToToken[charIndex];
                if (tokenIndex != undefined && $scope.selectedTokenIndices.get(tokenIndex) == tokenIndex) {
                    return true;
                }
            }

            return false;
        };

        $scope.onCharMouseEnter = function(charIndex){
            //console.log("onCharMouseEnter:" + charIndex);

            if ($scope.vector && $scope.vector.message){
                var tokenIndex = $scope.vector.message.charToToken[charIndex];

                if (tokenIndex != undefined && $scope.vector.message.tokens[tokenIndex] != undefined) {
                    var tokenItem = $scope.vector.message.tokens[tokenIndex];
                    $scope.hoveredCharStart = tokenItem.startIndex;
                    $scope.hoveredCharEnd = tokenItem.endIndex;

                    // If we're in the middle of selection, update selected char indices
                    if ($scope.clickStartTokenItem != undefined) {

                        var ctrlClick = event.ctrlKey || (event.metaKey && !event.ctrlKey);

                        if (tokenIndex < $scope.clickStartTokenItem.index) {
                            updateSelection(tokenIndex, $scope.clickStartTokenItem.index, true, !ctrlClick);
                        }
                        else if (tokenIndex > $scope.clickStartTokenItem.index) {
                            updateSelection($scope.clickStartTokenItem.index, tokenIndex, true, !ctrlClick);
                        }
                    }
                }
                else {
                    $scope.hoveredCharStart = -1;
                    $scope.hoveredCharEnd = -1;
                }
            }
        };

        $scope.onCharMouseLeave = function(charIndex){
            //console.log("onCharMouseLeave:" + charIndex);

            $scope.hoveredCharStart = -1;
            $scope.hoveredCharEnd = -1;
        };

        $scope.onCharMouseDown = function(charIndex, event){
            //console.log("onCharMouseDown:" + charIndex);

            if ($scope.vector && $scope.vector.message) {

                var tokenIndex = $scope.vector.message.charToToken[charIndex];

                if (tokenIndex != undefined && $scope.vector.message.tokens[tokenIndex] != undefined) {

                    var tokenItem = $scope.vector.message.tokens[tokenIndex];

                    var ctrlClick = event.ctrlKey || (event.metaKey && !event.ctrlKey);

                    // if there was a selection at this tokenIndex and mouse was clicked with command/ctrl button,
                    // clear the selection on this token index
                    if ($scope.selectedTokenIndices.get(tokenIndex) == tokenIndex && ctrlClick) {
                        $scope.clickStartTokenItem = undefined;
                        updateSelection(tokenIndex, tokenIndex, false, false);
                    }
                    else {
                        $scope.clickStartTokenItem = tokenItem;
                        updateSelection(tokenIndex, tokenIndex, true, !ctrlClick);
                    }
                }
                else {
                    $scope.clickStartTokenItem = undefined;
                    $scope.selectedTokenIndices.clear();
                }
            }
        };

        $scope.onCharMouseUp = function(charIndex) {
            $scope.clickStartTokenItem = undefined;
            $scope.selectedTokens = undefined;

            if ($scope.selectedTokenIndices.size > 0) {
                if ($scope.vector && $scope.vector.message) {

                    // Get sorted list of selected token indices
                    var indices = [];
                    $scope.selectedTokenIndices.forEach(function (val) {
                        indices.push(val);
                    });
                    indices.sort(function (a, b) {
                        return a - b;
                    });

                    var tokens = [];
                    var currentTokenIndex = -1;
                    for (var i = 0; i < indices.length; i++) {
                        var tokenIndex = indices[i];

                        if (tokenIndex != currentTokenIndex) {
                            tokens.push($scope.vector.message.tokens[tokenIndex].text);
                            currentTokenIndex = tokenIndex;
                        }
                    }

                    $scope.selectedTokens = tokens;
                }
            }
        };

        $scope.charStyle = function(charIndex) {
            var style = {};
            if (charIndex >= $scope.hoveredCharStart && charIndex <= $scope.hoveredCharEnd) {
                style["background"] = "#ffcc99";
            }

            if (isTokenSelectedAtCharIndex(charIndex) || (isTokenSelectedAtCharIndex(charIndex - 1) && isTokenSelectedAtCharIndex(charIndex + 1))) {
                style["background"] = "#ff6600";
            }
            return style;
        };

        $scope.addFeature = function(tokens){
            if (tokens && tokens.length > 0){

                var key = tokens.join(" ");
                console.log("addFeature for: " + key);

                // check if it already exists
                var existingTokens = $scope.featureList[key];

                if (!existingTokens) {
                    var request = UserFeatures.add(tokens);
                    if (request) {
                        usSpinnerService.spin('vector-spinner');
                        request.then(function() {
                            usSpinnerService.stop('vector-spinner');
                            var featureId = UserFeatures.data;
                            $scope.featureList[key] = {
                                id: featureId,
                                tokens: tokens
                            };
                        });
                    }
                }
                else {
                    console.log("feature already exists: " + key);
                }

                $scope.clickStartTokenItem = undefined;
                $scope.selectedTokens = null;
                $scope.selectedTokenIndices.clear();
            }
        };

        $scope.removeFeature = function(feature){
            if (feature){
                var key = feature.tokens.join(" ");
                console.log("removeFeature for: " + key);

                // check if it already exists
                var existingTokens = $scope.featureList[key];

                if (existingTokens) {

                    var request = UserFeatures.remove(feature.id);
                    if (request) {
                        usSpinnerService.spin('vector-spinner');
                        request.then(function() {
                            usSpinnerService.stop('vector-spinner');
                            delete $scope.featureList[key];
                        });
                    }
                }
                else {
                    console.log("feature does not exist: " + key);
                }
            }
        }
    };

    ViewController.$inject = [
        '$scope',
        'TextCoder.services.Dictionary',
        'TextCoder.services.SVMResult',
        'TextCoder.services.FeatureVector',
        'TextCoder.services.UserFeatures',
        'usSpinnerService'
    ];
    module.controller('TextCoder.controllers.ViewController', ViewController);

    module.directive('datetimeFormat', function() {
      return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {
          ngModelController.$parsers.push(function(data) {
            //convert data from view format to model format
            data = moment.utc(data, "YYYY-MM-DD HH:mm:ss");
            if (data.isValid()) return data.toDate();
            else return undefined;
          });

          ngModelController.$formatters.push(function(data) {
            //convert data from model format to view format
              if (data !== undefined) return moment.utc(data).format("YYYY-MM-DD HH:mm:ss"); //converted
              return data;
          });
        }
      }
    });

    module.directive('whenScrolled', function() {
        return function(scope, element, attr) {
            var raw = element[0];

            var checkBounds = function(evt) {
                if (Math.abs(raw.scrollTop + $(raw).height() - raw.scrollHeight) < 10) {
                    scope.$apply(attr.whenScrolled);
                }

            };
            element.bind('scroll load', checkBounds);
        };
    });

    module.directive('ngEnter', function () {
        return function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if(event.which === 13) {
                    scope.$apply(function (){
                        scope.$eval(attrs.ngEnter);
                    });

                    event.preventDefault();
                }
            });
        };
    });
})();
<|endoftext|>


<commit_before>/* @flow weak */

import React from 'react';
import moment from 'moment';

export default class StatusBar extends React.Component {
  props: {
    notebook: any,
    lastSaved: typeof Date,
    kernelSpecName: string,
    executionState: string,
  };

  shouldComponentUpdate(nextProps) {
    if (this.props.notebook !== nextProps.notebook ||
        this.props.lastSaved !== nextProps.lastSaved) {
      return true;
    }
    return false;
  }

  render() {
    return (

          {
            this.props.lastSaved ?

 Last saved {moment(this.props.lastSaved).fromNow()}
 :

 Not saved yet

          }

{this.props.kernelSpecName} | {this.props.executionState}

    );
  }
}
<commit_msg>fix(StatusBar): props should be placed after shouldComponentUpdate<commit_after>/* @flow weak */

import React from 'react';
import moment from 'moment';

export default class StatusBar extends React.Component {
  shouldComponentUpdate(nextProps) {
    if (this.props.notebook !== nextProps.notebook ||
        this.props.lastSaved !== nextProps.lastSaved) {
      return true;
    }
    return false;
  }

  props: {
    notebook: any,
    lastSaved: typeof Date,
    kernelSpecName: string,
    executionState: string,
  };

  render() {
    return (

          {
            this.props.lastSaved ?

 Last saved {moment(this.props.lastSaved).fromNow()}
 :

 Not saved yet

          }

{this.props.kernelSpecName} | {this.props.executionState}

    );
  }
}
<|endoftext|>