<commit_before>var utils = {
        /* modified from http://blog.stevenlevithan.com/archives/date-time-format */
        dateFormat: function () {
            var token = /d{1,4}|m{1,4}|yy(?:yy)?/g,
                pad = function (val, len) {
                    val = String(val);
                    len = len || 2;
                    while (val.length < len) val = "0" + val;
                    return val;
                };

            return function (date, mask, offset) {
                var date = Date.parse(date) ? new Date(date) : utils.parseISO8601(date), // parse date for IE8 since it's so lame
                    d = date.getDate(),
                    m = date.getMonth(),
                    y = date.getFullYear(),
                    flags = {
                        d:    d,
                        dd:   pad(d),
                        m:    m + 1,
                        mm:   pad(m + 1),
                        yy:   String(y).slice(2),
                        yyyy: y
                    };

                return mask.replace(token, function ($0) {
                    return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
                });
            };
        }(),
        dateParse: function () {
            var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?/g;

            return function (str, mask) {
                var date = new Date(0),
                    matches = [],
                    order = [],
                    pattern = "",
                    depad = function(v){
                        return parseInt(v, 10);
                    },
                    modifiers = {
                        m:  function(v){return v - 1;},
                        mm: function(v){return v - 1;},
                        yy: function(v){return 2000 + v;}
                    },
                    methods = {
                        d:    "Date",
                        dd:   "Date",
                        m:    "Month",
                        mm:   "Month",
                        yy:   "FullYear",
                        yyyy: "FullYear",
                        H:    "Hours",
                        HH:   "Hours",
                        MM:   "Minutes"
                    },
                    patterns = {
                        d:    "[1-3]?\\d",
                        dd:   "[0-3]\\d",
                        m:    "1?\\d",
                        mm:   "[01]\\d",
                        yy:   "\\d{2}",
                        yyyy: "[12]\\d{3}",
                        H:    "[12]?\\d",
                        HH:   "[0-2]\\d",
                        MM:   "[0-5]\\d"
                    };

                mask = mask.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

                pattern = mask.replace(token, function ($0) {
                    if ($0 in methods && $0 in patterns) {
                        order.push({
                            "method": methods[$0],
                            "modifier": modifiers[$0]
                        });
                        return "(" + patterns[$0] + ")";
                    } else {
                        $0.slice(1, $0.length - 1);
                    }
                });

                matches = str.match(RegExp(pattern));

                for (var i = 1, l = matches.length; i < l; i++) {
                    var match = depad(matches[i]),
                        order_item = order[i - 1],
                        method = order_item.method,
                        modifier = order_item.modifier;

                    if (modifier) {
                        match = modifier(match);
                    }

                    if (method) {
                        date["setUTC" + method](match);
                    }
                }

                if (offset) {
                    date.setTime(date.getTime() + (+offset * 60 * 1000));
                }

                return date;
            };
        }(),
        parseISO8601: function(dateString) {
            var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*/,
                date = new Date(NaN),
                month,
                parts = isoExp.exec(dateString);

            if(parts) {
                month = +parts[2];
                date.setFullYear(parts[1], month - 1, parts[3]);
                if(month != date.getMonth() + 1) {
                    date.setTime(NaN);
                }
            }
            return date;
        }
    };<commit_msg>Add nano templating function<commit_after>var utils = {
        /* modified from http://blog.stevenlevithan.com/archives/date-time-format */
        dateFormat: function () {
            var token = /d{1,4}|m{1,4}|yy(?:yy)?/g,
                pad = function (val, len) {
                    val = String(val);
                    len = len || 2;
                    while (val.length < len) val = "0" + val;
                    return val;
                };

            return function (date, mask, offset) {
                var date = Date.parse(date) ? new Date(date) : utils.parseISO8601(date), // parse date for IE8 since it's so lame
                    d = date.getDate(),
                    m = date.getMonth(),
                    y = date.getFullYear(),
                    flags = {
                        d:    d,
                        dd:   pad(d),
                        m:    m + 1,
                        mm:   pad(m + 1),
                        yy:   String(y).slice(2),
                        yyyy: y
                    };

                return mask.replace(token, function ($0) {
                    return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
                });
            };
        }(),
        dateParse: function () {
            var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?/g;

            return function (str, mask) {
                var date = new Date(0),
                    matches = [],
                    order = [],
                    pattern = "",
                    depad = function(v){
                        return parseInt(v, 10);
                    },
                    modifiers = {
                        m:  function(v){return v - 1;},
                        mm: function(v){return v - 1;},
                        yy: function(v){return 2000 + v;}
                    },
                    methods = {
                        d:    "Date",
                        dd:   "Date",
                        m:    "Month",
                        mm:   "Month",
                        yy:   "FullYear",
                        yyyy: "FullYear",
                        H:    "Hours",
                        HH:   "Hours",
                        MM:   "Minutes"
                    },
                    patterns = {
                        d:    "[1-3]?\\d",
                        dd:   "[0-3]\\d",
                        m:    "1?\\d",
                        mm:   "[01]\\d",
                        yy:   "\\d{2}",
                        yyyy: "[12]\\d{3}",
                        H:    "[12]?\\d",
                        HH:   "[0-2]\\d",
                        MM:   "[0-5]\\d"
                    };

                mask = mask.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

                pattern = mask.replace(token, function ($0) {
                    if ($0 in methods && $0 in patterns) {
                        order.push({
                            "method": methods[$0],
                            "modifier": modifiers[$0]
                        });
                        return "(" + patterns[$0] + ")";
                    } else {
                        $0.slice(1, $0.length - 1);
                    }
                });

                matches = str.match(RegExp(pattern));

                for (var i = 1, l = matches.length; i < l; i++) {
                    var match = depad(matches[i]),
                        order_item = order[i - 1],
                        method = order_item.method,
                        modifier = order_item.modifier;

                    if (modifier) {
                        match = modifier(match);
                    }

                    if (method) {
                        date["setUTC" + method](match);
                    }
                }

                if (offset) {
                    date.setTime(date.getTime() + (+offset * 60 * 1000));
                }

                return date;
            };
        }(),
        /* Nano Templates - https://github.com/trix/nano */
        nano: function(template, data) {
            return template.replace(
                /\{\{([\w\.]*)\}\}/g,
                function(str, key) {
                    var keys = key.split("."), v = data[keys.shift()];
                    for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]];
                    return (typeof v !== "undefined" && v !== null) ? v : "";
                }
            );
        },
        parseISO8601: function(dateString) {
            var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*/,
                date = new Date(NaN),
                month,
                parts = isoExp.exec(dateString);

            if(parts) {
                month = +parts[2];
                date.setFullYear(parts[1], month - 1, parts[3]);
                if(month != date.getMonth() + 1) {
                    date.setTime(NaN);
                }
            }
            return date;
        }
    };<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

"use strict";
var admin= require('commander'),
    pkgJson = require('../package.json'),
    auth = require('./operational'),
   // device = require('./device'),
    components = require('./components'),
    configurator = require('./configurator');

admin.version(pkgJson.version);
/*
 * Add commando as option
 */
auth.addCommand(admin);
//device.addCommand(admin);
components.addCommand(admin);
configurator.addCommand(admin);

admin.parse(process.argv);
/*
 * Run if the command were specified at parameter
 */
//device.runCommand(admin);

/*
 * Help and verions also as commands
 */
if (!admin.args.length) {
    admin.help();
}
admin
    .command('help')
    .description('output usage information')
    .action(admin.help());
admin
    .command('version')
    .description('output the version number')
    .action(admin.version(pkgJson.version));

<commit_msg>Fixed help always showing<commit_after>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

"use strict";
var admin= require('commander'),
    pkgJson = require('../package.json'),
    auth = require('./operational'),
   // device = require('./device'),
    components = require('./components'),
    configurator = require('./configurator');

admin.version(pkgJson.version);
/*
 * Add commando as option
 */
auth.addCommand(admin);
//device.addCommand(admin);
components.addCommand(admin);
configurator.addCommand(admin);

admin.parse(process.argv);
/*
 * Run if the command were specified at parameter
 */
//device.runCommand(admin);

/*
 * Help and verions also as commands
 */
if (!admin.args.length || admin.args[0] === 'help') {
    admin.help();
}
admin
    .command('version')
    .description('output the version number')
    .action(admin.version(pkgJson.version));

<|endoftext|>


<commit_before>// DO NOT EDIT THIS FILE!!! IT WILL BE AUTOMATICALLY GENERATED FROM src/i18n
/*global systemDictionary:true */
'use strict';

systemDictionary = {
    'HomeMatic Address': {
        'en': 'HomeMatic Address',
        'de': 'HomeMatic Adresse',
        'ru': 'Адрес HomeMatic',
        'pt': 'Endereço HomeMatic',
        'nl': 'HomeMatic-adres',
        'fr': 'Adresse de HomeMatic',
        'it': 'Indirizzo HomeMatic',
        'es': 'Dirección HomeMatic',
        'pl': 'Adres HomeMatic',
        'zh-cn': 'HomeMatic地址'
    },
    'Adapter Address': {
        'en': 'Adapter Address',
        'de': 'Adapter Adresse',
        'ru': 'Собственный адрес',
        'pt': 'Endereço do adaptador',
        'nl': 'Adapter adres',
        'fr': "Adresse de l'adaptateur",
        'it': "Indirizzo dell'adattatore",
        'es': 'Dirección del adaptador',
        'pl': 'Adres adaptera',
        'zh-cn': '适配器地址'
    },
    'Daemon': {
        'en': 'Daemon',
        'de': 'Daemon',
        'ru': 'Служба',
        'pt': 'Daemon',
        'nl': 'Demon',
        'fr': 'Démon',
        'it': 'Demone',
        'es': 'Demonio',
        'pl': 'Daemon',
        'zh-cn': '守护进程'
    },
    'HomeMatic Port': {
        'en': 'HomeMatic Port',
        'de': 'HomeMatic Port',
        'ru': 'Порт HomeMatic',
        'pt': 'HomeMatic Port',
        'nl': 'HomeMatic-poort',
        'fr': 'AccueilMatic Port',
        'it': 'HomeMatic Port',
        'es': 'Puerto HomeMatic',
        'pl': 'Port HomeMatic',
        'zh-cn': 'HomeMatic港口'
    },
    'Adapter Callback Address': {
        'en': 'Adapter Callback Address',
        'de': 'Adapter Callback Adresse',
        'ru': 'Собственный Callback адрес',
        'pt': 'Endereço de retorno de chamada do adaptador',
        'nl': 'Adapter-callback-adres',
        'fr': "Adresse de rappel de l'adaptateur",
        'it': "Indirizzo di richiamata dell'adattatore",
        'es': 'Dirección de devolución de llamada del adaptador',
        'pl': 'Adres zwrotny adaptera',
        'zh-cn': '适配器回调地址'
    },
    'Adapter Port': {
        'en': 'Adapter Port',
        'de': 'Adapter Port',
        'ru': 'Порт драйвера ioBroker',
        'pt': 'Porta adaptadora',
        'nl': 'Adapterpoort',
        'fr': "Port de l'adaptateur",
        'it': "Porta dell'adattatore",
        'es': 'Puerto adaptador',
        'pl': 'Port adaptera',
        'zh-cn': '适配器端口'
    },
    'Protocol': {
        'en': 'Protocol',
        'de': 'Protokoll',
        'ru': 'Протокол',
        'pt': 'Protocolo',
        'nl': 'Protocol',
        'fr': 'Protocole',
        'it': 'Protocollo',
        'es': 'Protocolo',
        'pl': 'Protokół',
        'zh-cn': '协议'
    },
    'Check communication interval (sec)': {
        'en': 'Check communication interval(sec)',
        'de': 'Verbindungs-Test Intervall(s)',
        'ru': 'Интервал проверки соединения(сек)',
        'pt': 'Verifique o intervalo de comunicação (seg)',
        'nl': 'Controleer communicatie-interval (sec)',
        'fr': "Vérifier l'intervalle de communication (sec)",
        'it': "Controllare l'intervallo di comunicazione (sec)",
        'es': 'Verificar el intervalo de comunicación (sec)',
        'pl': 'Sprawdź interwał komunikacji (s)',
        'zh-cn': '检查通信间隔（秒）'
    },
    'Reconnect interval (sec)': {
        'en': 'Reconnect interval (sec)',
        'de': 'Wiederverbindungs-Intervall(sek)',
        'ru': 'Интервал повтора соединения(сек)',
        'pt': 'Intervalo de Reconexão (segundo)',
        'nl': 'Verbindingsinterval opnieuw verbinden (sec)',
        'fr': 'Intervalle de reconnexion (sec)',
        'it': 'Intervallo di riconnessione (sec)',
        'es': 'Intervalo de reconexión (sec)',
        'pl': 'Interwał ponownego połączenia (s)',
        'zh-cn': '重新连接间隔（秒）'
    },
    'Listen on all IPs': {
        'en': 'Listen on all IPs',
        'de': 'Auf alle IPs hören',
        'ru': 'Слушать на всех IP адресах',
        'pt': 'Ouça todos os IPs',
        'nl': "Luister op alle IP's",
        'fr': 'Écoutez sur toutes les adresses IP',
        'it': 'Ascolta su tutti gli IP',
        'es': 'Escuchar en todas las direcciones IP',
        'pl': 'Posłuchaj na wszystkich IP',
        'zh-cn': '收听所有IP'
    },
    "Don't delete devices": {
        'en': "Don't delete devices",
        'de': 'Geräte nicht löschen',
        'ru': 'Не удалять устройства',
        'pt': 'Não exclua dispositivos',
        'nl': 'Verwijder geen apparaten',
        'fr': 'Ne pas supprimer les appareils',
        'it': 'Non eliminare i dispositivi',
        'es': 'No eliminar dispositivos',
        'pl': 'Nie usuwaj urządzeń',
        'zh-cn': '不要删除设备'
    },
    'Additional settings': {
        'en': 'Additional settings',
        'de': 'Zusätzliche Einstellungen',
        'ru': 'Дополнительные настройки',
        'pt': 'Configurações adicionais',
        'nl': 'Aanvullende instellingen',
        'fr': 'Paramètres additionnels',
        'it': 'Altre impostazioni',
        'es': 'Ajustes adicionales',
        'pl': 'Dodatkowe ustawienia',
        'zh-cn': '其他设置'
    },
    'Homematic RPC adapter settings': {
        'en': 'Homematic RPC adapter settings',
        'de': 'Homematic RPC Adapter Einstellungen',
        'ru': 'Настройки Homematic RPC драйвера',
        'pt': 'Configurações do adaptador Homematic RPC',
        'nl': 'Homematische RPC-adapterinstellingen',
        'fr': "Paramètres de l'adaptateur RPC homématique",
        'it': "Impostazioni dell'adattatore RPC Homematic",
        'es': 'Configuración del adaptador Homematic RPC',
        'pl': 'Homematyczne ustawienia adaptera RPC',
        'zh-cn': 'Homematic RPC适配器设置'
    },
    'This IP is unreachable from %s': {
        'en': 'This IP is unreachable from %s',
        'de': 'Diese IP ist nicht erreichbar von %s',
        'ru': 'Этот IP не доступен для %s',
        'pt': 'Este IP é inacessível de %s',
        'nl': 'Deze IP is onbereikbaar van %s',
        'fr': 'Cette adresse IP est inaccessible depuis %s',
        'it': 'Questo IP non è raggiungibile da %s',
        'es': 'Este IP es inalcanzable desde %s',
        'pl': 'To IP jest nieosiągalne z %s',
        'zh-cn': '此IP无法从％s访问 %s'
    },
    'Please specify callback address': {
        'en': 'Please specify callback address.',
        'de': 'Bitte Callback IP-Adresse eingeben.',
        'ru': 'Введите IP адрес для callback.',
        'pt': 'Por favor, especifique o endereço de retorno de chamada.',
        'nl': 'Geef het callback-adres op.',
        'fr': "Veuillez spécifier l'adresse de rappel.",
        'it': "Si prega di specificare l'indirizzo di richiamata.",
        'es': 'Por favor, especifique la dirección de devolución de llamada.',
        'pl': 'Proszę podać adres zwrotny.',
        'zh-cn': '请指定回拨地址。'
    },
    'Ok': {
        'en': 'Ok',
        'de': 'Ok',
        'ru': 'Ok',
        'pt': 'Está bem',
        'nl': 'OK',
        'fr': "D'accord",
        'it': 'Ok',
        'es': 'De acuerdo',
        'pl': 'Ok',
        'zh-cn': '好'
    },
    'Force objects re-init': {
        'en': 'Synchronize objects (once)',
        'de': 'Synchronisiere Geräte neu (einmalig)',
        'ru': 'Синхронизировать объекты (один раз)',
        'pt': 'Sincronizar objetos (uma vez)',
        'nl': 'Synchroniseer objecten (één keer)',
        'fr': 'Synchroniser des objets (une fois)',
        'it': 'Sincronizza oggetti (una volta)',
        'es': 'Sincronizar objetos (una vez)',
        'pl': 'Synchronizuj obiekty (raz)',
        'zh-cn': '同步对象（一次）'
    },
    'Use https': {
        'en': 'Use https',
        'de': 'Nutze https',
        'ru': 'использовать https',
        'pt': 'use https',
        'nl': 'gebruik https',
        'fr': 'utiliser https',
        'it': 'usa https',
        'es': 'usar https',
        'pl': 'użyj https',
        'zh-cn': '使用https'
    },
    'Username': {
        'en': 'Username',
        'de': 'Nutzername',
        'ru': 'имя пользователя',
        'pt': 'Username',
        'nl': 'Gebruikersnaam',
        'fr': "Nom d'utilisateur",
        'it': 'Nome utente',
        'es': 'Nombre de usuario',
        'pl': 'Nazwa Użytkownika',
        'zh-cn': '用户名'
    },
    'Password': {
        'en': 'Password',
        'de': 'Passwort',
        'ru': 'пароль',
        'pt': 'Senha',
        'nl': 'Wachtwoord',
        'fr': 'Mot de passe',
        'it': "Parola d'ordine",
        'es': 'Contraseña',
        'pl': 'Hasło',
        'zh-cn': '密码'
    },
    'BIN-RPC does not work with HTTPS. HTTPS has been disabled.': {
        'en': 'BIN-RPC does not work with HTTPS. HTTPS has been disabled.',
        'de': 'BIN-RPC ist nicht HTTPS kompatibel. HTTPS wurde deaktiviert.',
        'ru': 'BIN-RPC не работает с HTTPS. HTTPS отключен.',
        'pt': 'O BIN-RPC não funciona com HTTPS. HTTPS foi desativado.',
        'nl': 'BIN-RPC werkt niet met HTTPS. HTTPS is uitgeschakeld.',
        'fr': 'BIN-RPC ne fonctionne pas avec HTTPS. HTTPS a été désactivé.',
        'it': 'BIN-RPC non funziona con HTTPS. HTTPS è stato disabilitato.',
        'es': 'BIN-RPC no funciona con HTTPS. HTTPS ha sido desactivado.',
        'pl': 'BIN-RPC nie działa z HTTPS. HTTPS został wyłączony.',
        'zh-cn': 'BIN-RPC不适用于HTTPS。 HTTPS已被禁用。'
    }
};
<commit_msg>Update words.js<commit_after>// DO NOT EDIT THIS FILE!!! IT WILL BE AUTOMATICALLY GENERATED FROM src/i18n
/*global systemDictionary:true */
'use strict';

systemDictionary = {
    'HomeMatic Address': {
        'en': 'HomeMatic Address',
        'de': 'HomeMatic Adresse',
        'ru': 'Адрес HomeMatic',
        'pt': 'Endereço HomeMatic',
        'nl': 'HomeMatic-adres',
        'fr': 'Adresse de HomeMatic',
        'it': 'Indirizzo HomeMatic',
        'es': 'Dirección HomeMatic',
        'pl': 'Adres HomeMatic',
        'zh-cn': 'HomeMatic地址'
    },
    'Adapter Address': {
        'en': 'Adapter Address',
        'de': 'Adapter Adresse',
        'ru': 'Собственный адрес',
        'pt': 'Endereço do adaptador',
        'nl': 'Adapter adres',
        'fr': "Adresse de l'adaptateur",
        'it': "Indirizzo dell'adattatore",
        'es': 'Dirección del adaptador',
        'pl': 'Adres adaptera',
        'zh-cn': '适配器地址'
    },
    'Daemon': {
        'en': 'Daemon',
        'de': 'Daemon',
        'ru': 'Служба',
        'pt': 'Daemon',
        'nl': 'Demon',
        'fr': 'Démon',
        'it': 'Demone',
        'es': 'Demonio',
        'pl': 'Daemon',
        'zh-cn': '守护进程'
    },
    'HomeMatic Port': {
        'en': 'HomeMatic Port',
        'de': 'HomeMatic Port',
        'ru': 'Порт HomeMatic',
        'pt': 'HomeMatic Port',
        'nl': 'HomeMatic-poort',
        'fr': 'AccueilMatic Port',
        'it': 'HomeMatic Port',
        'es': 'Puerto HomeMatic',
        'pl': 'Port HomeMatic',
        'zh-cn': 'HomeMatic港口'
    },
    'Adapter Callback Address': {
        'en': 'Adapter Callback Address',
        'de': 'Adapter Callback Adresse',
        'ru': 'Собственный Callback адрес',
        'pt': 'Endereço de retorno de chamada do adaptador',
        'nl': 'Adapter-callback-adres',
        'fr': "Adresse de rappel de l'adaptateur",
        'it': "Indirizzo di richiamata dell'adattatore",
        'es': 'Dirección de devolución de llamada del adaptador',
        'pl': 'Adres zwrotny adaptera',
        'zh-cn': '适配器回调地址'
    },
    'Adapter Port': {
        'en': 'Adapter Port',
        'de': 'Adapter Port',
        'ru': 'Порт драйвера ioBroker',
        'pt': 'Porta adaptadora',
        'nl': 'Adapterpoort',
        'fr': "Port de l'adaptateur",
        'it': "Porta dell'adattatore",
        'es': 'Puerto adaptador',
        'pl': 'Port adaptera',
        'zh-cn': '适配器端口'
    },
    'Protocol': {
        'en': 'Protocol',
        'de': 'Protokoll',
        'ru': 'Протокол',
        'pt': 'Protocolo',
        'nl': 'Protocol',
        'fr': 'Protocole',
        'it': 'Protocollo',
        'es': 'Protocolo',
        'pl': 'Protokół',
        'zh-cn': '协议'
    },
    'Check communication interval (sec)': {
        'en': 'Check communication interval(sec)',
        'de': 'Verbindungs-Test Intervall(s)',
        'ru': 'Интервал проверки соединения(сек)',
        'pt': 'Verifique o intervalo de comunicação (seg)',
        'nl': 'Controleer communicatie-interval (sec)',
        'fr': "Vérifier l'intervalle de communication (sec)",
        'it': "Controllare l'intervallo di comunicazione (sec)",
        'es': 'Verificar el intervalo de comunicación (sec)',
        'pl': 'Sprawdź interwał komunikacji (s)',
        'zh-cn': '检查通信间隔（秒）'
    },
    'Reconnect interval (sec)': {
        'en': 'Reconnect interval (sec)',
        'de': 'Wiederverbindungs-Intervall(sek)',
        'ru': 'Интервал повтора соединения(сек)',
        'pt': 'Intervalo de Reconexão (segundo)',
        'nl': 'Verbindingsinterval opnieuw verbinden (sec)',
        'fr': 'Intervalle de reconnexion (sec)',
        'it': 'Intervallo di riconnessione (sec)',
        'es': 'Intervalo de reconexión (sec)',
        'pl': 'Interwał ponownego połączenia (s)',
        'zh-cn': '重新连接间隔（秒）'
    },
    'Listen on all IPs': {
        'en': 'Listen on all IPs',
        'de': 'Auf alle IPs hören',
        'ru': 'Слушать на всех IP адресах',
        'pt': 'Ouça todos os IPs',
        'nl': "Luister op alle IP's",
        'fr': 'Écoutez sur toutes les adresses IP',
        'it': 'Ascolta su tutti gli IP',
        'es': 'Escuchar en todas las direcciones IP',
        'pl': 'Posłuchaj na wszystkich IP',
        'zh-cn': '收听所有IP'
    },
    "Don't delete devices": {
        'en': "Don't delete devices",
        'de': 'Geräte nicht löschen',
        'ru': 'Не удалять устройства',
        'pt': 'Não exclua dispositivos',
        'nl': 'Verwijder geen apparaten',
        'fr': 'Ne pas supprimer les appareils',
        'it': 'Non eliminare i dispositivi',
        'es': 'No eliminar dispositivos',
        'pl': 'Nie usuwaj urządzeń',
        'zh-cn': '不要删除设备'
    },
    'Additional settings': {
        'en': 'Additional settings',
        'de': 'Zusätzliche Einstellungen',
        'ru': 'Дополнительные настройки',
        'pt': 'Configurações adicionais',
        'nl': 'Aanvullende instellingen',
        'fr': 'Paramètres additionnels',
        'it': 'Altre impostazioni',
        'es': 'Ajustes adicionales',
        'pl': 'Dodatkowe ustawienia',
        'zh-cn': '其他设置'
    },
    'Homematic RPC adapter settings': {
        'en': 'Homematic RPC adapter settings',
        'de': 'Homematic RPC Adapter Einstellungen',
        'ru': 'Настройки Homematic RPC драйвера',
        'pt': 'Configurações do adaptador Homematic RPC',
        'nl': 'Homematische RPC-adapterinstellingen',
        'fr': "Paramètres de l'adaptateur RPC homématique",
        'it': "Impostazioni dell'adattatore RPC Homematic",
        'es': 'Configuración del adaptador Homematic RPC',
        'pl': 'Homematyczne ustawienia adaptera RPC',
        'zh-cn': 'Homematic RPC适配器设置'
    },
    'This IP is unreachable from %s': {
        'en': 'This IP is unreachable from %s',
        'de': 'Diese IP ist nicht erreichbar von %s',
        'ru': 'Этот IP не доступен для %s',
        'pt': 'Este IP é inacessível de %s',
        'nl': 'Deze IP is onbereikbaar van %s',
        'fr': 'Cette adresse IP est inaccessible depuis %s',
        'it': 'Questo IP non è raggiungibile da %s',
        'es': 'Este IP es inalcanzable desde %s',
        'pl': 'To IP jest nieosiągalne z %s',
        'zh-cn': '此IP无法从％s访问 %s'
    },
    'Please specify callback address': {
        'en': 'Please specify callback address.',
        'de': 'Bitte Callback IP-Adresse eingeben.',
        'ru': 'Введите IP адрес для callback.',
        'pt': 'Por favor, especifique o endereço de retorno de chamada.',
        'nl': 'Geef het callback-adres op.',
        'fr': "Veuillez spécifier l'adresse de rappel.",
        'it': "Si prega di specificare l'indirizzo di richiamata.",
        'es': 'Por favor, especifique la dirección de devolución de llamada.',
        'pl': 'Proszę podać adres zwrotny.',
        'zh-cn': '请指定回拨地址。'
    },
    'Ok': {
        'en': 'Ok',
        'de': 'Ok',
        'ru': 'Ok',
        'pt': 'Está bem',
        'nl': 'OK',
        'fr': "D'accord",
        'it': 'Ok',
        'es': 'De acuerdo',
        'pl': 'Ok',
        'zh-cn': '好'
    },
    'Force objects re-init': {
        'en': 'Synchronize objects (once)',
        'de': 'Geräte neu einlesen (einmalig)',
        'ru': 'Синхронизировать объекты (один раз)',
        'pt': 'Sincronizar objetos (uma vez)',
        'nl': 'Synchroniseer objecten (één keer)',
        'fr': 'Synchroniser des objets (une fois)',
        'it': 'Sincronizza oggetti (una volta)',
        'es': 'Sincronizar objetos (una vez)',
        'pl': 'Synchronizuj obiekty (raz)',
        'zh-cn': '同步对象（一次）'
    },
    'Use https': {
        'en': 'Use https',
        'de': 'Nutze https',
        'ru': 'использовать https',
        'pt': 'use https',
        'nl': 'gebruik https',
        'fr': 'utiliser https',
        'it': 'usa https',
        'es': 'usar https',
        'pl': 'użyj https',
        'zh-cn': '使用https'
    },
    'Username': {
        'en': 'Username',
        'de': 'Nutzername',
        'ru': 'имя пользователя',
        'pt': 'Username',
        'nl': 'Gebruikersnaam',
        'fr': "Nom d'utilisateur",
        'it': 'Nome utente',
        'es': 'Nombre de usuario',
        'pl': 'Nazwa Użytkownika',
        'zh-cn': '用户名'
    },
    'Password': {
        'en': 'Password',
        'de': 'Passwort',
        'ru': 'пароль',
        'pt': 'Senha',
        'nl': 'Wachtwoord',
        'fr': 'Mot de passe',
        'it': "Parola d'ordine",
        'es': 'Contraseña',
        'pl': 'Hasło',
        'zh-cn': '密码'
    },
    'BIN-RPC does not work with HTTPS. HTTPS has been disabled.': {
        'en': 'BIN-RPC does not work with HTTPS. HTTPS has been disabled.',
        'de': 'BIN-RPC ist nicht HTTPS kompatibel. HTTPS wurde deaktiviert.',
        'ru': 'BIN-RPC не работает с HTTPS. HTTPS отключен.',
        'pt': 'O BIN-RPC não funciona com HTTPS. HTTPS foi desativado.',
        'nl': 'BIN-RPC werkt niet met HTTPS. HTTPS is uitgeschakeld.',
        'fr': 'BIN-RPC ne fonctionne pas avec HTTPS. HTTPS a été désactivé.',
        'it': 'BIN-RPC non funziona con HTTPS. HTTPS è stato disabilitato.',
        'es': 'BIN-RPC no funciona con HTTPS. HTTPS ha sido desactivado.',
        'pl': 'BIN-RPC nie działa z HTTPS. HTTPS został wyłączony.',
        'zh-cn': 'BIN-RPC不适用于HTTPS。 HTTPS已被禁用。'
    }
};
<|endoftext|>


<commit_before>"use strict";

var fs = require( "fs" );
var parseString = require( "xml2js" ).parseString;

var parse = {};

function getCounter( source, type ) {
    return source.counter.filter( function ( counter )
    {
        return counter.$.type === type;
    })[0];
}

var unpackage = function ( report )
{
    var packages = report.package;

    var output = []

    packages.forEach( function ( pack )
    {
        var cov = pack.sourcefile.map( function ( s )
        {
            var fullPath = pack.$.name + '/' + s.$.name
            var className = fullPath.substring( 0, fullPath.lastIndexOf( '.' ) );

            var c = pack.class.filter( function( cl )
            {
                return cl.$.name == className;
            })[0];

            var methods = getCounter( s, "METHOD" );
            var lines = getCounter( s, "LINE" );
            var branches = getCounter( s, "BRANCH" );

            var classCov = {
                title: s.$.name,
                file: fullPath,
                functions: {
                    found: Number( methods.$.covered ) + Number( methods.$.missed ),
                    hit:  Number( methods.$.covered ),
                    details: !c.method ? [] : c.method.map( function ( m )
                    {
                        var hit = m.counter.some( function ( counter )
                        {
                            return counter.$.type == "METHOD" && counter.$.covered == "1";
                        });
                        return {
                            name: m.$.name,
                            line: Number( m.$.line ),
                            hit: hit ? 1 : 0
                        };
                    } )
                },
                lines: {
                    found: Number( lines.$.covered ) + Number( lines.$.missed ),
                    hit:  Number( lines.$.covered ),
                    details: !s.line ? [] : s.line.map( function ( l )
                    {
                        return {
                            line: Number( l.$.nr ),
                            hit: Number( l.$.ci )
                        };
                    } )
                },
                branches: {
                    found: Number( branches.$.covered ) + Number( branches.$.missed ),
                    hit:  Number( branches.$.covered ),
                    details: !s.line ? [] : [].concat.apply( [],
                        s.line.filter( function ( l )
                        {
                            return Number( l.$.mb ) > 0 || Number( l.$.cb ) > 0;
                        })
                        .map( function ( l )
                        {
                            var branches = [];
                            var count = Number( l.$.mb ) + Number( l.$.cb );

                            for ( var i = 0; i < count; ++i )
                            {
                                branches = branches.concat( {
                                    line: Number( l.$.nr ),
                                    block: 0,
                                    branch: Number( i ),
                                    taken:  i < Number( l.$.cb ) ? 1 : 0
                                } )
                            }

                            return branches;
                        } )
                    )
                }
            };

            return classCov;
        });

        output = output.concat( cov );
    });

    return output;
};

parse.parseContent = function ( xml, cb )
{
    parseString( xml, function ( err, parseResult )
    {
        if( err )
        {
            return cb( err );
        }

        var result = unpackage( parseResult.report );

        cb( err, result );
    } );
};

parse.parseFile = function( file, cb )
{
    fs.readFile( file, "utf8", function ( err, content )
    {
        if( err )
        {
            return cb( err );
        }

        parse.parseContent( content, cb );
    } );
};

module.exports = parse;
<commit_msg>linting<commit_after>"use strict";

var fs = require( "fs" );
var parseString = require( "xml2js" ).parseString;

var parse = {};

function getCounter( source, type ) {
    return source.counter.filter( function ( counter )
    {
        return counter.$.type === type;
    })[0];
}

var unpackage = function ( report )
{
    var packages = report.package;

    var output = [];

    packages.forEach( function ( pack )
    {
        var cov = pack.sourcefile.map( function ( s )
        {
            var fullPath = pack.$.name + '/' + s.$.name;
            var className = fullPath.substring( 0, fullPath.lastIndexOf( '.' ) );

            var c = pack.class.filter( function( cl )
            {
                return cl.$.name === className;
            })[0];

            var methods = getCounter( s, "METHOD" );
            var lines = getCounter( s, "LINE" );
            var branches = getCounter( s, "BRANCH" );

            var classCov = {
                title: s.$.name,
                file: fullPath,
                functions: {
                    found: Number( methods.$.covered ) + Number( methods.$.missed ),
                    hit:  Number( methods.$.covered ),
                    details: !c.method ? [] : c.method.map( function ( m )
                    {
                        var hit = m.counter.some( function ( counter )
                        {
                            return counter.$.type === "METHOD" && counter.$.covered === "1";
                        });
                        return {
                            name: m.$.name,
                            line: Number( m.$.line ),
                            hit: hit ? 1 : 0
                        };
                    } )
                },
                lines: {
                    found: Number( lines.$.covered ) + Number( lines.$.missed ),
                    hit:  Number( lines.$.covered ),
                    details: !s.line ? [] : s.line.map( function ( l )
                    {
                        return {
                            line: Number( l.$.nr ),
                            hit: Number( l.$.ci )
                        };
                    } )
                },
                branches: {
                    found: Number( branches.$.covered ) + Number( branches.$.missed ),
                    hit:  Number( branches.$.covered ),
                    details: !s.line ? [] : [].concat.apply( [],
                        s.line.filter( function ( l )
                        {
                            return Number( l.$.mb ) > 0 || Number( l.$.cb ) > 0;
                        })
                        .map( function ( l )
                        {
                            var branches = [];
                            var count = Number( l.$.mb ) + Number( l.$.cb );

                            for ( var i = 0; i < count; ++i )
                            {
                                branches = branches.concat( {
                                    line: Number( l.$.nr ),
                                    block: 0,
                                    branch: Number( i ),
                                    taken:  i < Number( l.$.cb ) ? 1 : 0
                                } );
                            }

                            return branches;
                        } )
                    )
                }
            };

            return classCov;
        });

        output = output.concat( cov );
    });

    return output;
};

parse.parseContent = function ( xml, cb )
{
    parseString( xml, function ( err, parseResult )
    {
        if( err )
        {
            return cb( err );
        }

        var result = unpackage( parseResult.report );

        cb( err, result );
    } );
};

parse.parseFile = function( file, cb )
{
    fs.readFile( file, "utf8", function ( err, content )
    {
        if( err )
        {
            return cb( err );
        }

        parse.parseContent( content, cb );
    } );
};

module.exports = parse;
<|endoftext|>


<commit_before>import stream from 'stream'

export function toObj () {

}

export default class Json2obj extends stream.Transform {

	constructor (
		{
			writableObjectMode = true,
			readableObjectMode = false
		} = {}
	) {
		super({writableObjectMode, readableObjectMode})

		this.internalBuffer = []

		this.vertexMap = new Map
		this.textureCoordinateSet = new Set
		this.vertexNormalSet = new Set
		this.parameterVerticeSet = new Set
		this.faceSet = new Set
	}

	_mergeVertices (jsonEvent) {

		this.faceSet.add(jsonEvent.vertices.map(
			vertex => {

				let vertexString = JSON.stringify(vertex)

				if (this.vertexMap.has(vertexString)) {
					return this.vertexMap.get(vertexString)
				}
				else {
					let vertexMapSize = this.vertexMap.size + 1
					this.vertexMap.set(vertexString, vertexMapSize)
					return vertexMapSize
				}

				this.vertexSet.add()
			}
		))
	}

	_processJsonEvent (jsonEvent) {
		if (jsonEvent.hasOwnProperty('vertices')) {
			this._mergeVertices(jsonEvent)
		}
	}

	_transform (chunk, encoding, done) {

		if (this._writableState.objectMode) {
			console.assert(
				typeof chunk === 'object',
				'Chunk must be of type "object" ' +
				'or writableObjectMode must be set to false'
			)
			this._processJsonEvent(chunk)
		}

		else {

			if (Buffer.isBuffer(chunk))
				chunk = chunk.toString()

			this.internalBuffer = this.internalBuffer.concat(chunk.split('\n'))

			let jsonEventString

			while (jsonEventString = this.internalBuffer.shift()) {
				let jsonEvent = JSON.parse(jsonEventString)
				this._processJsonEvent(jsonEvent)
			}
		}

		done()
	}

	_flush (done) {

		this.push('o Solid Object\n\n')

		for (let vertexString of this.vertexMap.keys()) {
			let vertex = JSON.parse(vertexString)
			this.push(`v ${vertex.x} ${vertex.y} ${vertex.z}\n`)
		}

		this.push(
			'\nf ' +
			[...this.faceSet]
				.map(face => face.join(' '))
				.join('\nf ') +
			'\n'
		)

		done()
	}
}
<commit_msg>Remove dead code<commit_after>import stream from 'stream'

export function toObj () {

}

export default class Json2obj extends stream.Transform {

	constructor (
		{
			writableObjectMode = true,
			readableObjectMode = false
		} = {}
	) {
		super({writableObjectMode, readableObjectMode})

		this.internalBuffer = []

		this.vertexMap = new Map
		this.textureCoordinateSet = new Set
		this.vertexNormalSet = new Set
		this.parameterVerticeSet = new Set
		this.faceSet = new Set
	}

	_mergeVertices (jsonEvent) {

		this.faceSet.add(jsonEvent.vertices.map(
			vertex => {

				let vertexString = JSON.stringify(vertex)

				if (this.vertexMap.has(vertexString)) {
					return this.vertexMap.get(vertexString)
				}
				else {
					let vertexMapSize = this.vertexMap.size + 1
					this.vertexMap.set(vertexString, vertexMapSize)
					return vertexMapSize
				}
			}
		))
	}

	_processJsonEvent (jsonEvent) {
		if (jsonEvent.hasOwnProperty('vertices')) {
			this._mergeVertices(jsonEvent)
		}
	}

	_transform (chunk, encoding, done) {

		if (this._writableState.objectMode) {
			console.assert(
				typeof chunk === 'object',
				'Chunk must be of type "object" ' +
				'or writableObjectMode must be set to false'
			)
			this._processJsonEvent(chunk)
		}

		else {

			if (Buffer.isBuffer(chunk))
				chunk = chunk.toString()

			this.internalBuffer = this.internalBuffer.concat(chunk.split('\n'))

			let jsonEventString

			while (jsonEventString = this.internalBuffer.shift()) {
				let jsonEvent = JSON.parse(jsonEventString)
				this._processJsonEvent(jsonEvent)
			}
		}

		done()
	}

	_flush (done) {

		this.push('o Solid Object\n\n')

		for (let vertexString of this.vertexMap.keys()) {
			let vertex = JSON.parse(vertexString)
			this.push(`v ${vertex.x} ${vertex.y} ${vertex.z}\n`)
		}

		this.push(
			'\nf ' +
			[...this.faceSet]
				.map(face => face.join(' '))
				.join('\nf ') +
			'\n'
		)

		done()
	}
}
<|endoftext|>


<commit_before>var PIXI = require('pixi.js'),
    common = require('../_shared/js');

common.setup(function (app) {
    var filterNames = Object.keys(PIXI.filters),
        filters = [],
        switches = [];

    // initialize all the filters!
    filterNames.forEach(function (filterName) {
        if (setup[filterName]) {
            switches.push(false);

            var folder = app.gui.addFolder(filterName);

            folder.add(switches, switches.length - 1).name('enable');

            filters.push(
                setup[filterName](folder)
            );
        }
    });

    // create the background
    var bg = PIXI.Sprite.fromImage('img/displacement_bg.jpg');
    app.root.addChild(bg);

    bg.texture.baseTexture.once('loaded', function () {
        app.onResize();
    });

    // create the fishies, use a container for each fish texture so they are batched
    var containers = [
            app.root.addChild(new PIXI.DisplayObjectContainer()),
            app.root.addChild(new PIXI.DisplayObjectContainer()),
            app.root.addChild(new PIXI.DisplayObjectContainer()),
            app.root.addChild(new PIXI.DisplayObjectContainer())
        ],
        textures = [
            PIXI.Texture.fromImage('img/displacement_fish1.png'),
            PIXI.Texture.fromImage('img/displacement_fish2.png'),
            PIXI.Texture.fromImage('img/displacement_fish3.png'),
            PIXI.Texture.fromImage('img/displacement_fish4.png')
        ],
        fishies = [],
        padding = 100;

    for (var i = 0; i < 28; i++) {
        var fishId = i % 4;

        var fish = new PIXI.Sprite(textures[fishId]);

        fish.anchor.x = fish.anchor.y = 0.5;

        containers[fishId].addChild(fish);

        fish.direction = Math.random() * PIXI.math.PI_2;
        fish.speed = 2 + Math.random() * 2;
        fish.turnSpeed = Math.random() - 0.8;

        fish.position.x = Math.random() * (app.renderer.width + padding);
        fish.position.y = Math.random() * (app.renderer.height + padding);

        fish.scale.set(0.8 + Math.random() * 0.3);

        fishies.push(fish);
    }

    // create the overlay
    var overlay = new PIXI.extras.TilingSprite(PIXI.Texture.fromImage('img/zeldaWaves.png'), app.renderer.width, app.renderer.height);
    overlay.alpha = 0.1;
    app.root.addChild(overlay);

    var count = 0.0;

    // setup the tick method.
    app.tick = function () {
        var filtersToApply = filters.filter(checkFilter);

        app.root.filters = filtersToApply.length > 0 ? filtersToApply : null;

        for (var i = 0; i < fishies.length; ++i) {
            var fish = fishies[i];

            fish.direction += fish.turnSpeed * 0.01;
            fish.position.x += Math.sin(fish.direction) * fish.speed;
            fish.position.y += Math.cos(fish.direction) * fish.speed;

            fish.rotation = -fish.direction - Math.PI/2;

            // wrap..
            if (fish.position.x < -padding) {
                fish.position.x += app.renderer.width + (padding * 2);
            }

            if (fish.position.x > (app.renderer.width + padding)) {
                fish.position.x -= app.renderer.width + (padding * 2);
            }

            if (fish.position.y < -padding) {
                fish.position.y += app.renderer.height + (padding * 2);
            }

            if (fish.position.y > (app.renderer.height + padding)) {
                fish.position.y -= app.renderer.height + (padding * 2);
            }
        }

        count += 0.1;

        // displacementFilter.offset.x = count * 10;
        // displacementFilter.offset.y = count * 10;

        overlay.tilePosition.x = count * -10;
        overlay.tilePosition.y = count * -10;
    };

    app.onResize = function () {
        bg.width = app.renderer.width;
        bg.height = app.renderer.height;
    };

    // kickoff the animation
    app.animate();

    function checkFilter(filter, i) {
        return switches[i];
    }
});

var setup = {
    AsciiFilter: function (folder) {
        var filter = new PIXI.filters.AsciiFilter();

        folder.add(filter, 'size', 1, 32).name('size');

        return filter;
    },
    BloomFilter: function (folder) {
        var filter = new PIXI.filters.BloomFilter();

        folder.add(filter, 'blur', 0, 32).name('blur');

        return filter;
    },
    BlurFilter: function (folder) {
        var filter = new PIXI.filters.BlurFilter();

        folder.add(filter, 'blurX', 0, 32).name('blurX');
        folder.add(filter, 'blurY', 0, 32).name('blurY');

        return filter;
    },
    GrayFilter: function (folder) {
        var filter = new PIXI.filters.GrayFilter();

        folder.add(filter, 'gray', 0, 1).name('gray');

        return filter;
    }
};
<commit_msg>Add more filters<commit_after>var PIXI = require('pixi.js'),
    common = require('../_shared/js');

// register each filter
var setup = {
    AsciiFilter: function (folder) {
        var filter = new PIXI.filters.AsciiFilter();

        folder.add(filter, 'size', 1, 25).step(1).name('Letter Size');

        return filter;
    },
    BloomFilter: function (folder) {
        var filter = new PIXI.filters.BloomFilter();

        folder.add(filter, 'blur', 0, 32).name('Blur Factor');

        return filter;
    },
    BlurFilter: function (folder) {
        var filter = new PIXI.filters.BlurFilter();

        folder.add(filter, 'blurX', 0, 32).name('Blur Factor X');
        folder.add(filter, 'blurY', 0, 32).name('Blur Factor Y');

        return filter;
    },
    /*
    TODO (cengler) - How to model the matrix in dat.gui?

    ColorMatrixFilter: function (folder) {
        var filter = new PIXI.filters.ColorMatrixFilter();

        folder.add(filter, 'step', 1, 100);

        return filter;
    },
    */
    ColorStepFilter: function (folder) {
        var filter = new PIXI.filters.ColorStepFilter();

        folder.add(filter, 'step', 1, 100).name('Color Step');

        return filter;
    },
    DotScreenFilter: function (folder) {
        var filter = new PIXI.filters.DotScreenFilter();

        folder.add(filter, 'angle', 0, PIXI.math.PI_2).name('Dot Angle');
        folder.add(filter, 'scale', 0, 1).name('Dot Scale');

        return filter;
    },
    GrayFilter: function (folder) {
        var filter = new PIXI.filters.GrayFilter();

        folder.add(filter, 'gray', 0, 1).name('Grayscale');

        return filter;
    },
    NoiseFilter: function (folder) {
        var filter = new PIXI.filters.NoiseFilter();

        folder.add(filter, 'noise', 0, 2).name('Amount of Noise');

        return filter;
    }
};

// Setup and run the example app
common.setup(function (app) {
    var filterNames = Object.keys(PIXI.filters),
        filters = [],
        switches = [];

    // initialize all the filters!
    filterNames.forEach(function (filterName) {
        if (setup[filterName]) {
            switches.push(false);

            var folder = app.gui.addFolder(filterName);

            folder.add(switches, switches.length - 1).name('enable');

            filters.push(
                setup[filterName](folder)
            );
        }
    });

    // create the background
    var bg = PIXI.Sprite.fromImage('img/displacement_bg.jpg');
    app.root.addChild(bg);

    bg.texture.baseTexture.once('loaded', function () {
        app.onResize();
    });

    // create the fishies, use a container for each fish texture so they are batched
    var containers = [
            app.root.addChild(new PIXI.DisplayObjectContainer()),
            app.root.addChild(new PIXI.DisplayObjectContainer()),
            app.root.addChild(new PIXI.DisplayObjectContainer()),
            app.root.addChild(new PIXI.DisplayObjectContainer())
        ],
        textures = [
            PIXI.Texture.fromImage('img/displacement_fish1.png'),
            PIXI.Texture.fromImage('img/displacement_fish2.png'),
            PIXI.Texture.fromImage('img/displacement_fish3.png'),
            PIXI.Texture.fromImage('img/displacement_fish4.png')
        ],
        fishies = [],
        padding = 100;

    for (var i = 0; i < 28; i++) {
        var fishId = i % 4;

        var fish = new PIXI.Sprite(textures[fishId]);

        fish.anchor.x = fish.anchor.y = 0.5;

        containers[fishId].addChild(fish);

        fish.direction = Math.random() * PIXI.math.PI_2;
        fish.speed = 2 + Math.random() * 2;
        fish.turnSpeed = Math.random() - 0.8;

        fish.position.x = Math.random() * (app.renderer.width + padding);
        fish.position.y = Math.random() * (app.renderer.height + padding);

        fish.scale.set(0.8 + Math.random() * 0.3);

        fishies.push(fish);
    }

    // create the overlay
    var waveTexture = PIXI.Texture.fromImage('img/zeldaWaves.png');
    var overlay = new PIXI.extras.TilingSprite(waveTexture, app.renderer.width, app.renderer.height);

    overlay.alpha = 0.1;

    app.root.addChild(overlay);

    var count = 0.0;

    // setup the tick method.
    app.tick = function () {
        var filtersToApply = filters.filter(checkFilter);

        app.root.filters = filtersToApply.length > 0 ? filtersToApply : null;

        for (var i = 0; i < fishies.length; ++i) {
            var fish = fishies[i];

            fish.direction += fish.turnSpeed * 0.01;
            fish.position.x += Math.sin(fish.direction) * fish.speed;
            fish.position.y += Math.cos(fish.direction) * fish.speed;

            fish.rotation = -fish.direction - Math.PI/2;

            // wrap..
            if (fish.position.x < -padding) {
                fish.position.x += app.renderer.width + (padding * 2);
            }

            if (fish.position.x > (app.renderer.width + padding)) {
                fish.position.x -= app.renderer.width + (padding * 2);
            }

            if (fish.position.y < -padding) {
                fish.position.y += app.renderer.height + (padding * 2);
            }

            if (fish.position.y > (app.renderer.height + padding)) {
                fish.position.y -= app.renderer.height + (padding * 2);
            }
        }

        count += 0.1;

        // displacementFilter.offset.x = count * 10;
        // displacementFilter.offset.y = count * 10;

        overlay.tilePosition.x = count * -10;
        overlay.tilePosition.y = count * -10;
    };

    app.onResize = function () {
        bg.width = app.renderer.width;
        bg.height = app.renderer.height;
    };

    // kickoff the animation
    app.animate();

    function checkFilter(filter, i) {
        return switches[i];
    }
});
<|endoftext|>


<commit_before>/******************************************************************
Copyright (c) 2011 Tom Blackmore
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************/
var ac = (function() {

    if(window.applicationCache) {
        var appCache = window.applicationCache;

        var log = (function() {
            var cacheEvents = [];
            /* event comments taken from
            http://dev.opera.com/articles/view/offline-applications-html5-appcache/ */

            // cached: This is fired when all the resources have finished downloading, and
            // application is cached.
            cacheEvents[0] = 'cached';
            // checking: This gets fired when browser is checking for attempting to download the
            // manifest for the first time, or is checking if there is an updated version of the
            // manifest file.
            cacheEvents[1] = 'checking';
            // downloading: If the browser is downloading the cache for the first time, or if is
            // downloading an updated cache, then this is fired.
            cacheEvents[2] = 'downloading';
            // error: This can be fired for a number of reasons. If the manifest file can't be
            // found, then the application cache download process has to be aborted, in which case
            // this event can be fired. It can also be fired in case the manifest file is present,
            // but any of the files mentioned in the manifest file can't be downloaded properly.
            // It can even be fired in case the manifest file changes while the update is being run
            // (in which case the browser will wait a while before trying again), or in any other
            // case where there is a fatal error.
            cacheEvents[3] = 'error';
            // noupdate: If there is no updated version of the manifest file on the server, then
            // noupdate is fired.
            cacheEvents[4] = 'noupdate';
            // obsolete: This is fired if the manifest file cannot be found (404 error or 410 error).
            cacheEvents[5] = 'obsolete';
            // progress: This is fired for each and every file which is downloaded as part of the
            // AppCache.
            cacheEvents[6] = 'progress';
            // updateready: Once resources have finished re-downloading for an updated cached file,
            // then updateready is called. Once this happens, then we can use swapCache() (as
            // explained later in the article) to make the browser to use this newly updated cache.
            cacheEvents[6] = 'updateready';

            var cacheStatusValues = [];
            /* status comments taken from
            http://dev.opera.com/articles/view/offline-applications-html5-appcache/ */

            // uncached: If the page is not linked to the application cache.
            // Also, the the very first time the application cache is being downloaded,
            // then during the time it is being downloaded, the AppCache will have a status of uncached.
            cacheStatusValues[0] = 'uncached';
            // idle: When the browser has the latest version of the AppCache,
            // and there aren no updated versions to download, then the status is set to Idle.
            cacheStatusValues[1] = 'idle';
            // checking: The duration of when the page is checking for an updated manifest file,
            // then the status is set to Checking.
            cacheStatusValues[2] = 'checking';
            // downloading: The duration of when the page is actually downloading a new cache
            // (if an updated manifest file has been detected), the status is set to downloading
            cacheStatusValues[3] = 'downloading';
            // updateready: Once the browser finishes downloading that new cache,
            // it is ready to be used (but still not being used yet).
            // During this time, the status is set as updateready
            cacheStatusValues[4] = 'updateready';
            // obsolete: In case the manifest file cannot be found, then the status is set to
            // obsolete and the application cache gets deleted. It is important to know, that
            // in case the manifest file (or any file mentioned in the manifest file except
            // those which have a fallback) fail to load, then it will be counted as an error
            // and the old application cache will continue to be used.
            cacheStatusValues[5] = 'obsolete';

            var log = function(s) {
                console.log(s);
            };
            var start = function(func) {
                if(typeof(func) === "function") {
                    log = func;
                }
                var message;
                if(document.getElementsByTagName("HTML")[0].hasAttribute('manifest')) {
                    message = "using: " + document.getElementsByTagName("HTML")[0].manifest;
                } else {
                    message = "No manifest specified in HTML tag";
                }

                log("AC: - logging started -");
                log("AC: "  + message);

                for(var i=0; i < cacheEvents.length; i++) {
                    appCache.addEventListener(cacheEvents[i], logEvent, false);
                }
            };
            var stop = function() {
                log("AC: - logging stoped -");
                for(var i=0; i < cacheEvents.length; i++) {
                    appCache.removeEventListener(cacheEvents[i], null, false);
                }
            };
            var isOnline = function() {
                return navigator.onLine;
            };
            var logEvent = function(e) {
                var online, status, type, message;
                online = (isOnline()) ? 'yes' : 'no';
                status = cacheStatusValues[appCache.status];
                type = e.type;
                //message = 'o: ' + online;
                message=  type;
                //message+= ', s: ' + status;
                log('AC: '+ message);

                if (type == 'error' && navigator.onLine) {
                    message = ' There was an unknown error, check your Cache Manifest.';
                    log('AC: Error')
                    log("AC: " + message);
                }
            };
            return {
                start: start,
                stop: stop
            }
        })();
        return {
            log : log
        };
    } else {
        return {
            log : (function() {
                return {
                    start: function() {
                    }
                };
            })()
        };
    }
})();
ac.log.start();<commit_msg>changed text a little in the readme<commit_after>/******************************************************************
Copyright (c) 2011 Tom Blackmore
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************/
var ac = (function() {

    if(window.applicationCache) {
        var appCache = window.applicationCache;

        var log = (function() {
            var cacheEvents = [];
            /* event comments taken from
            http://dev.opera.com/articles/view/offline-applications-html5-appcache/ */

            // cached: This is fired when all the resources have finished downloading, and
            // application is cached.
            cacheEvents[0] = 'cached';
            // checking: This gets fired when browser is checking for attempting to download the
            // manifest for the first time, or is checking if there is an updated version of the
            // manifest file.
            cacheEvents[1] = 'checking';
            // downloading: If the browser is downloading the cache for the first time, or if is
            // downloading an updated cache, then this is fired.
            cacheEvents[2] = 'downloading';
            // error: This can be fired for a number of reasons. If the manifest file can't be
            // found, then the application cache download process has to be aborted, in which case
            // this event can be fired. It can also be fired in case the manifest file is present,
            // but any of the files mentioned in the manifest file can't be downloaded properly.
            // It can even be fired in case the manifest file changes while the update is being run
            // (in which case the browser will wait a while before trying again), or in any other
            // case where there is a fatal error.
            cacheEvents[3] = 'error';
            // noupdate: If there is no updated version of the manifest file on the server, then
            // noupdate is fired.
            cacheEvents[4] = 'noupdate';
            // obsolete: This is fired if the manifest file cannot be found (404 error or 410 error).
            cacheEvents[5] = 'obsolete';
            // progress: This is fired for each and every file which is downloaded as part of the
            // AppCache.
            cacheEvents[6] = 'progress';
            // updateready: Once resources have finished re-downloading for an updated cached file,
            // then updateready is called. Once this happens, then we can use swapCache() (as
            // explained later in the article) to make the browser to use this newly updated cache.
            cacheEvents[6] = 'updateready';

            var cacheStatusValues = [];
            /* status comments taken from
            http://dev.opera.com/articles/view/offline-applications-html5-appcache/ */

            // uncached: If the page is not linked to the application cache.
            // Also, the the very first time the application cache is being downloaded,
            // then during the time it is being downloaded, the AppCache will have a status of uncached.
            cacheStatusValues[0] = 'uncached';
            // idle: When the browser has the latest version of the AppCache,
            // and there aren no updated versions to download, then the status is set to Idle.
            cacheStatusValues[1] = 'idle';
            // checking: The duration of when the page is checking for an updated manifest file,
            // then the status is set to Checking.
            cacheStatusValues[2] = 'checking';
            // downloading: The duration of when the page is actually downloading a new cache
            // (if an updated manifest file has been detected), the status is set to downloading
            cacheStatusValues[3] = 'downloading';
            // updateready: Once the browser finishes downloading that new cache,
            // it is ready to be used (but still not being used yet).
            // During this time, the status is set as updateready
            cacheStatusValues[4] = 'updateready';
            // obsolete: In case the manifest file cannot be found, then the status is set to
            // obsolete and the application cache gets deleted. It is important to know, that
            // in case the manifest file (or any file mentioned in the manifest file except
            // those which have a fallback) fail to load, then it will be counted as an error
            // and the old application cache will continue to be used.
            cacheStatusValues[5] = 'obsolete';

            var log = function(s) {
                console.log(s);
            };
            var start = function(func) {
                if(typeof(func) === "function") {
                    log = func;
                }
                var message;
                if(document.getElementsByTagName("HTML")[0].hasAttribute('manifest')) {
                    message = "using: " + document.getElementsByTagName("HTML")[0].manifest;
                } else {
                    message = "No manifest specified in HTML tag";
                }

                log("AC: - logging started -");
                log("AC: "  + message);

                for(var i=0; i < cacheEvents.length; i++) {
                    appCache.addEventListener(cacheEvents[i], logEvent, false);
                }
            };
            var stop = function() {
                log("AC: - logging stoped -");
                for(var i=0; i < cacheEvents.length; i++) {
                    appCache.removeEventListener(cacheEvents[i], null, false);
                }
            };
            var isOnline = function() {
                return navigator.onLine;
            };
            var logEvent = function(e) {
                var online, status, type, message;
                online = (isOnline()) ? 'yes' : 'no';
                status = cacheStatusValues[appCache.status];
                type = e.type;
                message=  type;
                log('AC: '+ message);

                if (type == 'error' && navigator.onLine) {
                    message = ' There was an unknown error, check your Cache Manifest.';
                    log('AC: Error')
                    log("AC: " + message);
                }
            };
            return {
                start: start,
                stop: stop
            }
        })();
        return {
            log : log
        };
    } else {
        return {
            log : (function() {
                return {
                    start: function() {
                    }
                };
            })()
        };
    }
})();
ac.log.start();<|endoftext|>


<commit_before>

$(document).ready(function () {

    function cleanLines(text) {
        let lines = text.split(/\r|\n|;/).map(function (i) {
            return i.trim();
        }).filter(function (i) {
            return i.length > 0;
        }).sort();
        return lines.join("\n");
    }

    /**
     * ###################
     * Button definitions
     * ###################
     */

    /**
     * This button is used on /batch/distribute_visits/{segment}
     * and sends away all configurations as a big array
     *
     */
    $(".set-dates button#send").click(function () {
        let lists = [];
        $(Batch.listIdentifier).each(function (i, listobj) {
            let rows = [];
            $(listobj).find("li").each(function (i, itemobj) {
                rows.push($(itemobj).attr("data-id"));
            });
            lists.push(rows);
        });
        let data = {
            updateMethod: "distributeVisits",
            value: lists,
            onReturn: 'showStatus'
        };
        Update.send(data);
    });
    /**
     * This button is used on /batch/add_dates/{topic_id}
     * and "cleans" the textarea after inserting date rows using a method written in
     * google spreadsheets. It removes empty rows and trims and sorts the rows.
     */
    $(".add-dates button#clean").click(function () {
        let $textElement = $("textarea.date-lines");
        $textElement.val(cleanLines($textElement.val()));
    });

    $('.set-group-count button#clean').click(function () {
        let $textElement = $("#group-count-lines");
        $textElement.val(cleanLines($textElement.val()));
    });

    /**
     * This button is used on /batch/add_dates/{topic_id}
     * and sends the date array in the textarea as "value"
     * and the topic_id as "entity_id"
     */
    $(".add-dates button#add").click(function () {
        let textarea = $("textarea.date-lines");
        textarea.val(cleanLines(textarea.val()));
        let lines = textarea.val().split(/\r|\n/);
        let topic_id = $('select.date-lines').val();
        let update_method = (topic_id === 'multiple'
                ? 'addDatesForMultipleTopics'
                : 'addDates'
        );

        let data = {
            updateMethod: update_method,
            topic_id: topic_id,
            dates: lines,
            onReturn: 'datesAdded'
        };
        Update.send(data);
    });

    $('.set-group-count button#update').click(function () {
        let $textElement = $("#group-count-lines");
        $textElement.val(cleanLines($textElement.val()));

        let lines = $textElement.val().split(/\n/).map(function (line) {
            return line.split(',').map(function (item) {
                return item.trim()
            });
        });
        let data = {
            updateMethod: "batchSetGroupCount",
            group_numbers: lines,
            start_year: $('#start-year-selector').val(),
            onReturn: "showStatus"
        };
        Update.send(data);
    });

    /**
     * ###################
     * Click definitions
     * ###################
     */

    let toggleGroupNameField = function (event) {
        let h1 = $(event.target).closest('h1');
        let dataId = h1.closest(".group-container").attr("data-entity-id");
        let inputField = h1.children('input');
        if (event.type === 'click' || event.type === 'dblclick') {
            h1.children("span, i, svg").hide();
            inputField.val(h1.children('span').text());
            inputField.show().focus();

        } else if (event.type === 'focusout') {
            let newName = h1.children('input').hide().val();
            let data = {
                updateMethod: "changeGroupName",
                entity_id: dataId,
                value: newName,
                onReturn: "groupNameChanged"
            };
            Update.send(data);
            h1.children("span, i, svg").show();
        } else {
            console.log('The event.type ' + event.type + ' has no implementation');
        }
    };

    let addRow = function () {
        let oldRow = $(".editable tbody tr:last");
        let newRow = oldRow.clone(true);
        newRow.hide();
        let tempId = '#' + Math.random().toString(36).substring(2, 6);
        newRow.attr("data-id", tempId).data("id", tempId);
        newRow.find(":input").val('').removeAttr('value').removeAttr('id');
        newRow.data('properties', undefined).removeProp('data-properties');
        newRow.find(':input.datepicker').BSdatepicker("destroy").BSdatepicker(Settings.datepickerOptions);
        oldRow.after(newRow);
        if (!oldRow.is(':visible')) { // was only dummy row
            oldRow.remove();
        }
        newRow.removeAttr('hidden');
        newRow.show(1000);
    };

    $(".add-row-btn").click(addRow);
    $(".group-container h1").on('dblclick click', toggleGroupNameField);
    $(".group-container h1 i").click(toggleGroupNameField);
    $(".group-container input.group-name-input").focusout(toggleGroupNameField);

    $('#missingGroups button').click(function () {
        let data = {
            updateMethod: "createMissingGroups",
            segment: $('#missingGroups select[name="Segment"]').val(),
            onReturn: 'showAddedGroups'
        };
        Update.send(data);
    });

    $('#manager-mobilization button').click(function () {
        let options = {
            'url': 'admin/batch/send_manager_mobilization_mail',
            'method': 'POST',
            'complete': function (jqXHR, status) {
                Response.handler(jqXHR, 'showSentManagerMails', status);
            },
            'error': Response.logErrorsToConsole
        };
        $.ajax(options);
    });

    $('#cron-task-activation :checkbox').click(function () {
        let data = {
            updateMethod: "changeTaskActivation",
            task_name: $(this).attr('name'),
            status: $(this).is(':checked'),
            onReturn: 'lastChange'
        };
        Update.send(data);
    });

    /**
     * MODALS
     */

    let $login_modal_submit = $('#login_modal_submit');
    $login_modal_submit.click(function () {
        let data = {
            updateMethod: 'checkPassword',
            password: $("[name='password']").val(),
            school_id: $(".additional-information").data('default-properties').School,
            onReturn: 'checkPasswordResponse'
        };
        Update.send(data);
    });
    let predefined_pw = $('#login-modal input[name="password"]').val();
    if (typeof predefined_pw === "string" && predefined_pw !== '') {
        $login_modal_submit[0].click();
    }

    $('#forgot-pw-btn').click(function () {
        $('#login-modal').modal('hide');
        $('#password-modal').modal('show');

        $('#password-modal').show();
    });

    $('#forgotten_password_submit').click(function () {
        let modal_id = '#password-modal';
        let mail = $(modal_id + ' input[name="mailaddress"]').val();
        $.ajax({
            url: 'api/sendPasswordRecoverMail/' + mail,
            method: 'POST',
            success: function (data) {
                if (data.status === 'success') {
                    $(modal_id + ' .modal-header').html('
Vi har skickat ett mejl med en länk till din adress
');
                    $(modal_id + ' .modal-body').html('
Kolla både inkorg och spamkorg
');
                    $(modal_id + ' .modal-footer').html('<button class="close" data-dismiss="modal">X Stäng</button>');
                } else {
                    $(modal_id + ' .modal-header').html('
Vi kunde tyvärr inte hitta din adress
');
                    $(modal_id + ' .modal-body').html('
Tyvärr finns din adress inte med bland våra aktiva medlemmar. Kolla med din administratör eller be en registrerad kollega att ge dig lösenordet.
');
                    $(modal_id + ' .modal-footer').html('<button class="close" data-dismiss="modal" >X Stäng</button>');

                }
            }
        });

    });

    $('button.go-to-groups').click(function () {
        window.location.replace($(this).data('url'));
    });

    $('div#show-school-pw button').popover({
        html: true,
        trigger: 'hover click',
        placement: 'bottom',
        content: function () {
            let content_id = "content-id-" + $.now();

            $.ajax({
                url: 'api/getPasswordForSchool/' + $(this).data('school'),
                method: 'POST'
            }).done(function (data) {
                $('#' + content_id).html(data.password);
            });
            return '
Laddar...
';
        }
    });

    $('input[name="hide-password"]').click(function () {
        let $input = $(this);
        let $password_field = $('input[name="password"]');
        let $type = 'text';
        if ($input.is(':checked')) {
            $type = 'password';
        }
        $password_field.attr('type', $type);
    });

    $('div#send-question button[type="submit"]').click(function () {
        let $form = $('div#send-question');
        $.ajax({
            url: 'api/send_contact_mail',
            method: 'POST',
            data: {
                captcha: grecaptcha.getResponse(),
                input_email: $('input[name="input_email"]').val(),
                input_message: $('textarea[name="input_message"]').val()
            },
            success: function (data) {
                if(!data.captcha_success){
                    $form.prepend('
Din CAPTCHA blev tyvärr inte godkänt. Testa igen!
');
                    grecaptcha.reset();
                    return;
                } else if (!data.address_success){
                    $form.prepend('
Du har glömt att ange en mejladress.
');
                    return;
                } else if(!data.mail_success){
                    $form.prepend('
Det blev nåt fel. Ditt meddelande har tyvärr inte kunnat skickas. Testa igen eller kontakta oss via kontaktsidan ovan.
');
                    return;
                }
                $form.html('
Ditt meddelande har skickats!
');
            }
        });
    });

    $('.add-note-to-visit button').click(function () {
       $('.add-note-to-visit :button').removeClass('active');
       $(this).addClass('active');

       let prewritten = $('.add-note-to-visit .prewritten-notes').data('notes');
       $('.add-note-to-visit .editable').val(prewritten[$(this).data('user-id')]);
    });

    $('button.copy-to-clipboard').click(function(){
        $('textarea.area-to-copy').select();
        document.execCommand('copy');
    });

    $('button#send-user-removal-mail').click(() => {
        let $form = $('div#remove-user-form');
        let data = [];
        data.users = $('input:checkbox:checked', $form).map((i, el) => {
            return $(el).closest('tr').data('id');
        }).get();
        data.reason = $('select#reason-selector option:selected').text();
        data.reason_text = $('textarea', $form).val();

        console.log(data);
    });

});
<commit_msg>Continue more testing<commit_after>

$(document).ready(function () {

    function cleanLines(text) {
        let lines = text.split(/\r|\n|;/).map(function (i) {
            return i.trim();
        }).filter(function (i) {
            return i.length > 0;
        }).sort();
        return lines.join("\n");
    }

    /**
     * ###################
     * Button definitions
     * ###################
     */

    /**
     * This button is used on /batch/distribute_visits/{segment}
     * and sends away all configurations as a big array
     *
     */
    $(".set-dates button#send").click(function () {
        let lists = [];
        $(Batch.listIdentifier).each(function (i, listobj) {
            let rows = [];
            $(listobj).find("li").each(function (i, itemobj) {
                rows.push($(itemobj).attr("data-id"));
            });
            lists.push(rows);
        });
        let data = {
            updateMethod: "distributeVisits",
            value: lists,
            onReturn: 'showStatus'
        };
        Update.send(data);
    });
    /**
     * This button is used on /batch/add_dates/{topic_id}
     * and "cleans" the textarea after inserting date rows using a method written in
     * google spreadsheets. It removes empty rows and trims and sorts the rows.
     */
    $(".add-dates button#clean").click(function () {
        let $textElement = $("textarea.date-lines");
        $textElement.val(cleanLines($textElement.val()));
    });

    $('.set-group-count button#clean').click(function () {
        let $textElement = $("#group-count-lines");
        $textElement.val(cleanLines($textElement.val()));
    });

    /**
     * This button is used on /batch/add_dates/{topic_id}
     * and sends the date array in the textarea as "value"
     * and the topic_id as "entity_id"
     */
    $(".add-dates button#add").click(function () {
        let textarea = $("textarea.date-lines");
        textarea.val(cleanLines(textarea.val()));
        let lines = textarea.val().split(/\r|\n/);
        let topic_id = $('select.date-lines').val();
        let update_method = (topic_id === 'multiple'
                ? 'addDatesForMultipleTopics'
                : 'addDates'
        );

        let data = {
            updateMethod: update_method,
            topic_id: topic_id,
            dates: lines,
            onReturn: 'datesAdded'
        };
        Update.send(data);
    });

    $('.set-group-count button#update').click(function () {
        let $textElement = $("#group-count-lines");
        $textElement.val(cleanLines($textElement.val()));

        let lines = $textElement.val().split(/\n/).map(function (line) {
            return line.split(',').map(function (item) {
                return item.trim()
            });
        });
        let data = {
            updateMethod: "batchSetGroupCount",
            group_numbers: lines,
            start_year: $('#start-year-selector').val(),
            onReturn: "showStatus"
        };
        Update.send(data);
    });

    /**
     * ###################
     * Click definitions
     * ###################
     */

    let toggleGroupNameField = function (event) {
        let h1 = $(event.target).closest('h1');
        let dataId = h1.closest(".group-container").attr("data-entity-id");
        let inputField = h1.children('input');
        if (event.type === 'click' || event.type === 'dblclick') {
            h1.children("span, i, svg").hide();
            inputField.val(h1.children('span').text());
            inputField.show().focus();

        } else if (event.type === 'focusout') {
            let newName = h1.children('input').hide().val();
            let data = {
                updateMethod: "changeGroupName",
                entity_id: dataId,
                value: newName,
                onReturn: "groupNameChanged"
            };
            Update.send(data);
            h1.children("span, i, svg").show();
        } else {
            console.log('The event.type ' + event.type + ' has no implementation');
        }
    };

    let addRow = function () {
        let oldRow = $(".editable tbody tr:last");
        let newRow = oldRow.clone(true);
        newRow.hide();
        let tempId = '#' + Math.random().toString(36).substring(2, 6);
        newRow.attr("data-id", tempId).data("id", tempId);
        newRow.find(":input").val('').removeAttr('value').removeAttr('id');
        newRow.data('properties', undefined).removeProp('data-properties');
        newRow.find(':input.datepicker').BSdatepicker("destroy");
        oldRow.after(newRow);
        if (!oldRow.is(':visible')) { // was only dummy row
            oldRow.remove();
        }
        newRow.removeAttr('hidden');
        newRow.show(1000);
    };

    $(".add-row-btn").click(addRow);
    $(".group-container h1").on('dblclick click', toggleGroupNameField);
    $(".group-container h1 i").click(toggleGroupNameField);
    $(".group-container input.group-name-input").focusout(toggleGroupNameField);

    $('#missingGroups button').click(function () {
        let data = {
            updateMethod: "createMissingGroups",
            segment: $('#missingGroups select[name="Segment"]').val(),
            onReturn: 'showAddedGroups'
        };
        Update.send(data);
    });

    $('#manager-mobilization button').click(function () {
        let options = {
            'url': 'admin/batch/send_manager_mobilization_mail',
            'method': 'POST',
            'complete': function (jqXHR, status) {
                Response.handler(jqXHR, 'showSentManagerMails', status);
            },
            'error': Response.logErrorsToConsole
        };
        $.ajax(options);
    });

    $('#cron-task-activation :checkbox').click(function () {
        let data = {
            updateMethod: "changeTaskActivation",
            task_name: $(this).attr('name'),
            status: $(this).is(':checked'),
            onReturn: 'lastChange'
        };
        Update.send(data);
    });

    /**
     * MODALS
     */

    let $login_modal_submit = $('#login_modal_submit');
    $login_modal_submit.click(function () {
        let data = {
            updateMethod: 'checkPassword',
            password: $("[name='password']").val(),
            school_id: $(".additional-information").data('default-properties').School,
            onReturn: 'checkPasswordResponse'
        };
        Update.send(data);
    });
    let predefined_pw = $('#login-modal input[name="password"]').val();
    if (typeof predefined_pw === "string" && predefined_pw !== '') {
        $login_modal_submit[0].click();
    }

    $('#forgot-pw-btn').click(function () {
        $('#login-modal').modal('hide');
        $('#password-modal').modal('show');

        $('#password-modal').show();
    });

    $('#forgotten_password_submit').click(function () {
        let modal_id = '#password-modal';
        let mail = $(modal_id + ' input[name="mailaddress"]').val();
        $.ajax({
            url: 'api/sendPasswordRecoverMail/' + mail,
            method: 'POST',
            success: function (data) {
                if (data.status === 'success') {
                    $(modal_id + ' .modal-header').html('
Vi har skickat ett mejl med en länk till din adress
');
                    $(modal_id + ' .modal-body').html('
Kolla både inkorg och spamkorg
');
                    $(modal_id + ' .modal-footer').html('<button class="close" data-dismiss="modal">X Stäng</button>');
                } else {
                    $(modal_id + ' .modal-header').html('
Vi kunde tyvärr inte hitta din adress
');
                    $(modal_id + ' .modal-body').html('
Tyvärr finns din adress inte med bland våra aktiva medlemmar. Kolla med din administratör eller be en registrerad kollega att ge dig lösenordet.
');
                    $(modal_id + ' .modal-footer').html('<button class="close" data-dismiss="modal" >X Stäng</button>');

                }
            }
        });

    });

    $('button.go-to-groups').click(function () {
        window.location.replace($(this).data('url'));
    });

    $('div#show-school-pw button').popover({
        html: true,
        trigger: 'hover click',
        placement: 'bottom',
        content: function () {
            let content_id = "content-id-" + $.now();

            $.ajax({
                url: 'api/getPasswordForSchool/' + $(this).data('school'),
                method: 'POST'
            }).done(function (data) {
                $('#' + content_id).html(data.password);
            });
            return '
Laddar...
';
        }
    });

    $('input[name="hide-password"]').click(function () {
        let $input = $(this);
        let $password_field = $('input[name="password"]');
        let $type = 'text';
        if ($input.is(':checked')) {
            $type = 'password';
        }
        $password_field.attr('type', $type);
    });

    $('div#send-question button[type="submit"]').click(function () {
        let $form = $('div#send-question');
        $.ajax({
            url: 'api/send_contact_mail',
            method: 'POST',
            data: {
                captcha: grecaptcha.getResponse(),
                input_email: $('input[name="input_email"]').val(),
                input_message: $('textarea[name="input_message"]').val()
            },
            success: function (data) {
                if(!data.captcha_success){
                    $form.prepend('
Din CAPTCHA blev tyvärr inte godkänt. Testa igen!
');
                    grecaptcha.reset();
                    return;
                } else if (!data.address_success){
                    $form.prepend('
Du har glömt att ange en mejladress.
');
                    return;
                } else if(!data.mail_success){
                    $form.prepend('
Det blev nåt fel. Ditt meddelande har tyvärr inte kunnat skickas. Testa igen eller kontakta oss via kontaktsidan ovan.
');
                    return;
                }
                $form.html('
Ditt meddelande har skickats!
');
            }
        });
    });

    $('.add-note-to-visit button').click(function () {
       $('.add-note-to-visit :button').removeClass('active');
       $(this).addClass('active');

       let prewritten = $('.add-note-to-visit .prewritten-notes').data('notes');
       $('.add-note-to-visit .editable').val(prewritten[$(this).data('user-id')]);
    });

    $('button.copy-to-clipboard').click(function(){
        $('textarea.area-to-copy').select();
        document.execCommand('copy');
    });

    $('button#send-user-removal-mail').click(() => {
        let $form = $('div#remove-user-form');
        let data = [];
        data.users = $('input:checkbox:checked', $form).map((i, el) => {
            return $(el).closest('tr').data('id');
        }).get();
        data.reason = $('select#reason-selector option:selected').text();
        data.reason_text = $('textarea', $form).val();

        console.log(data);
    });

});
<|endoftext|>


<commit_before>import React from 'react'
import axios from 'axios'
import Header from './Header'
const { shape, string } = React.PropTypes

const Details = React.createClass({
  propTypes: {
    show: shape({
      title: string,
      year: string,
      poster: string,
      trailer: string,
      description: string,
      imdbID: string
    })
  },
  getInitialState () {
    return {
      omdbData: {}
    }
  },
  componentDidMount () {
    axios.get(`http://www.omdbapi.com/?=${this.props.show.imdbID}`)
          .then((response) => {
            this.setState({omdbData: response.data})
          })
          .catch((error) => console.error('axios error', error))
  },
  render () {
    const { title, description, year, poster, trailer } = this.props.show
    return (

{title}

({year})

          <img src={`/public/img/posters/${poster}`} alt='make web accessible' />

{description}

          <iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&controls=0&showinfo=0`} frameBorder='0' allowFullScreen />

    )
  }
})

export default Details
<commit_msg>added rating to Details component<commit_after>import React from 'react'
import axios from 'axios'
import Header from './Header'
const { shape, string } = React.PropTypes

const Details = React.createClass({
  propTypes: {
    show: shape({
      title: string,
      year: string,
      poster: string,
      trailer: string,
      description: string,
      imdbID: string
    })
  },
  getInitialState () {
    return {
      omdbData: {}
    }
  },
  componentDidMount () {
    axios.get(`http://www.omdbapi.com/?i=${this.props.show.imdbID}`)
          .then((response) => {
            this.setState({omdbData: response.data})
          })
          .catch((error) => console.error('axios error', error))
  },
  render () {
    const { title, description, year, poster, trailer } = this.props.show
    let rating
    if (this.state.omdbData.imdbRating) {
      rating =
{this.state.omdbData.imdbRating}

    } else {
      rating =
    }
    return (

{title}

({year})

          {rating}
          <img src={`/public/img/posters/${poster}`} alt='make web accessible' />

{description}

          <iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&controls=0&showinfo=0`} frameBorder='0' allowFullScreen />

    )
  }
})

export default Details
<|endoftext|>