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

    var app = angular.module('discussion', [
        'gettext',
        'discussion.controllers',
        'discussion.services',
        'discussion.directives',
        'discussion.filters',
        'core.services',
        'ngRoute',
        'ui.tinymce',
        'ui.bootstrap',
        'ngFileUpload',
        'ui.select',
        'ngSanitize',
        'ngAnimate',
        'duScroll',
        'LocalStorageModule',
        'shared',
        'djangular'
    ]);

    // Set new default values for 'duScroll'
    app.value('duScrollDuration', 1000);
    app.value('duScrollOffset', 100);

    angular.module('discussion').run(['gettextCatalog', 'UserLocalStorage', function (gettextCatalog, UserLocalStorage) {
        let defaultLanguage = UserLocalStorage.get('currentLanguage') || 'en';

        gettextCatalog.setCurrentLanguage(defaultLanguage);
        UserLocalStorage.set('currentLanguage', defaultLanguage);

        //UserLocalStorage.set('currentLanguage', 'en');
        gettextCatalog.setStrings('es', {"By":"Por","Courses":"Cursos","Date":"Fecha","Forums":"Foros","From":"De","Here you find a resumy of the most important things of the academy. Enjoy and have a fun learning ;D":"Aquí encontrará un resumen de las cosas más importantes de la academia. Disfruta y diviértete aprendiendo ;D","Last activity":"Última actividad","Learn how to use":"Aprender cómo usar","Announcements":"Notificaciones","See all announcements":"Ver todas las notificaciones","This forum doesn't have any topics yet.":"Este foro aún no tiene ningún tema.","View all forums":"Ver todos los foros","Welcome to the Academy!":"¡Bienvenidos a la Academia!","You have":"Tú tienes","categories":"categorias","hide":"esconder","latest posts":"últimas publicaciones","learn more practices":"aprender más prácticas","published by":"publicado por","reactions":"reacciones","see":"ver","tags":"tags","topic":"tema","unread announcement":"notificación no leída","unread announcements":"notificaciones no leídas", "Dashboard":"Panel","commented on the topic":"comentó sobre el tema","in the forum":"en el foro","ago":"atrás","comment":"comentario","liked":"gusta", "Courses":"Cursos","Loading courses...":"Cargando cursos...","START DATE":"FECHA DE INICIO","There are no courses.":"No hay cursos.","WHAT YOU LEARN AT THIS COURSE":"LO QUE APRENDES EN ESTE CURSO", "Administration":"Administración","Administração":"Administração","Back to the plataform":"De vuelta al plataform","Cancel":"Cancelar","Clean":"Limpiar","Contact":"Contacto","Courses":"Cursos","Hi":"Olá","Login":"Acceso","Logout":"Cerrar sesión","Profile":"Perfil","Register":"Registrarse","Send":"Enviar","Suport":"Apoyo","Latest topics":"Últimos temas","Load more":"Carga más","Create new topic":"Crear nuevo tema","Assign TAGs to the topic":"Asignar TAGs al tema","Attach file":"Adjuntar archivo","Choose a category":"Elige una categoría","Choose the forum":"Elige el foro","Forum is required field":"El foro es un campo obligatorio","Post new topic":"Nuevo tema","Required fields":"Campos requeridos","Topic cannot be empty":"El tema no puede estar vacío","Topic text":"Texto del tema","Topic title is required field":"El título del tema es un campo obligatorio","What is the category of your topic?":"¿Cuál es la categoría de su tema?","What is the title of the new topic?":"¿Cuál es el título del nuevo tema?","Which forum should the new topic be in?":"¿En qué foro debería estar el nuevo tema?","New Topic":"Nuevo tema","Edit topic":"Editar tema","by":"por","Like":"Gusta","Comment":"Comentario","Edit":"Editar","Comments":"Comentarios", "last edition":"última edición","discard":"descarte","attach":"adjuntar"});
        gettextCatalog.setStrings('pt_br', {"By":"Por","Courses":"Cursos","Date":"Data","Forums":"Fóruns","From":"De","Here you find a resumy of the most important things of the academy. Enjoy and have a fun learning ;D":"Aqui você encontra um resumo das coisas mais importantes da academia. Aproveite e divirta-se aprendendo ;D","Last activity":"Última atividade","Learn how to use":"Aprenda a usar","Announcements":"Avisos","See all announcements":"Ver todos os avisos","This forum doesn't have any topics yet.":"Este fórum ainda não tem nenhum tópico.","View all forums":"Ver todos os fóruns","Welcome to the Academy!":"Bem-vindo à Academia!","You have":"Você tem","categories":"categorias","hide":"ocultar","latest posts":"últimas postagens","learn more practices":"aprender mais práticas","published by":"publicado por","reactions":"reações","see":"ver","tags":"tags","topic":"tópico", "Dashboard": "Painel","commented on the topic":"comentou no tópico","in the forum":"no fórum","ago":"atrás","comment":"comentário","liked":"gostou", "Courses":"Cursos","Loading courses...":"Carregando cursos...","START DATE":"DATA DE INÍCIO","There are no courses.":"Não há cursos.","WHAT YOU LEARN AT THIS COURSE":"O QUE VOCÊ APRENDE NESTE CURSO", "Administration":"Administração","Back to the plataform":"Voltar para a plataforma","Cancel":"Cancelar","Clean":"Limpar","Contact":"Contato","Courses":"Cursos","Hi":"Olá","Login":"Acessar","Logout":"Sair","Profile":"Perfil","Register":"Registrar","Send":"Enviar","Suport":"Suporte","Latest topics":"Últimos tópicos","Load more":"Carregar mais","Create new topic":"Criar novo tópico","Assign TAGs to the topic":"Atribuir TAGs ao tópico","Attach file":"Anexar arquivo","Choose a category":"Escolha uma categoria","Choose the forum":"Escolha o fórum","Forum is required field":"O fórum é um campo obrigatório","New Topic":"Novo topico","Post new topic":"Postar novo tópico","Required fields":"Campos obrigatórios","Topic cannot be empty":"O tópico não pode estar vazio","Topic text":"Texto do tópico","Topic title is required field":"O título do tópico é um campo obrigatório","What is the category of your topic?":"Qual é a categoria do seu tópico?","What is the title of the new topic?":"Qual é o título do novo tópico?","Which forum should the new topic be in?":"Em qual fórum o novo tópico deve estar?","Edit topic":"Editar tópico","by":"por","Like":"Gostar","Comment":"Comentar","Edit":"Editar","Comments":"Comentários","last edition":"última edição","discard":"descartar","attach":"anexar","unread announcement":"aviso não lido","unread announcements":"avisos não lidos"});
    }]);

    app.config(['$locationProvider', '$routeProvider', 'localStorageServiceProvider',
        function config($locationProvider, $routeProvider,
            localStorageServiceProvider) {
            localStorageServiceProvider.setPrefix('');
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/topic/new/', {
                    templateUrl: 'topic-new.html',
                    controller: 'NewTopicCtrl'
                }).
                when('/topic/:topicId/', {
                    templateUrl: 'topic-detail.html',
                    controller: 'TopicCtrl'
                }).
                when('/forum/embed/', {
                    templateUrl: 'forum-embed.html',
                    controller: 'ForumEmbedCtrl',
                    reloadOnSearch: false
                }).
                when('/forum/:forumId', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                when('/', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                otherwise('/');
        }
    ]);
})(angular);
<commit_msg>Insert new terms in translation<commit_after>(function(angular){
    'use strict';

    var app = angular.module('discussion', [
        'gettext',
        'discussion.controllers',
        'discussion.services',
        'discussion.directives',
        'discussion.filters',
        'core.services',
        'ngRoute',
        'ui.tinymce',
        'ui.bootstrap',
        'ngFileUpload',
        'ui.select',
        'ngSanitize',
        'ngAnimate',
        'duScroll',
        'LocalStorageModule',
        'shared',
        'djangular'
    ]);

    // Set new default values for 'duScroll'
    app.value('duScrollDuration', 1000);
    app.value('duScrollOffset', 100);

    angular.module('discussion').run(['gettextCatalog', 'UserLocalStorage', function (gettextCatalog, UserLocalStorage) {
        let defaultLanguage = UserLocalStorage.get('currentLanguage') || 'en';

        gettextCatalog.setCurrentLanguage(defaultLanguage);
        UserLocalStorage.set('currentLanguage', defaultLanguage);

        //UserLocalStorage.set('currentLanguage', 'en');
        gettextCatalog.setStrings('es', {"By":"Por","Courses":"Cursos","Date":"Fecha","Forums":"Foros","From":"De","Here you find a resumy of the most important things of the academy. Enjoy and have a fun learning ;D":"Aquí encontrará un resumen de las cosas más importantes de la academia. Disfruta y diviértete aprendiendo ;D","Last activity":"Última actividad","Learn how to use":"Aprender cómo usar","Announcements":"Notificaciones","See all announcements":"Ver todas las notificaciones","This forum doesn't have any topics yet.":"Este foro aún no tiene ningún tema.","View all forums":"Ver todos los foros","Welcome to the Academy!":"¡Bienvenidos a la Academia!","You have":"Tú tienes","categories":"categorias","hide":"esconder","latest posts":"últimas publicaciones","learn more practices":"aprender más prácticas","published by":"publicado por","reactions":"reacciones","see":"ver","tags":"tags","topic":"tema","unread announcement":"notificación no leída","unread announcements":"notificaciones no leídas", "Dashboard":"Panel","commented on the topic":"comentó sobre el tema","in the forum":"en el foro","ago":"atrás","comment":"comentario","liked":"gustos", "Courses":"Cursos","Loading courses...":"Cargando cursos...","START DATE":"FECHA DE INICIO","There are no courses.":"No hay cursos.","WHAT YOU LEARN AT THIS COURSE":"LO QUE APRENDES EN ESTE CURSO", "Administration":"Administración","Administração":"Administração","Back to the plataform":"De vuelta al plataform","Cancel":"Cancelar","Clean":"Limpiar","Contact":"Contacto","Courses":"Cursos","Hi":"Olá","Login":"Acceso","Logout":"Cerrar sesión","Profile":"Perfil","Register":"Registrarse","Send":"Enviar","Suport":"Apoyo","Latest topics":"Últimos temas","Load more":"Carga más","Create new topic":"Crear nuevo tema","Assign TAGs to the topic":"Asignar TAGs al tema","Attach file":"Adjuntar archivo","Choose a category":"Elige una categoría","Choose the forum":"Elige el foro","Forum is required field":"El foro es un campo obligatorio","Post new topic":"Nuevo tema","Required fields":"Campos requeridos","Topic cannot be empty":"El tema no puede estar vacío","Topic text":"Texto del tema","Topic title is required field":"El título del tema es un campo obligatorio","What is the category of your topic?":"¿Cuál es la categoría de su tema?","What is the title of the new topic?":"¿Cuál es el título del nuevo tema?","Which forum should the new topic be in?":"¿En qué foro debería estar el nuevo tema?","New Topic":"Nuevo tema","Edit topic":"Editar tema","by":"por","Like":"Gusta","Comment":"Comentario","Edit":"Editar","Comments":"Comentarios", "last edition":"última edición","discard":"descarte","attach":"adjuntar","comments":"comentarios","Latest Posts":"Últimas publicaciones","View all topics in this forum":"Ver todos los temas de este foro","No results found":"No se han encontrado resultados","A place for people chat and interact.":"Un lugar para que la gente charle e interactúe.","CATEGORY": "CATEGORÍA","Select...": "Seleccione...","Clear filters": "Eliminar filtros","Topics": "Temas","Back":"Volver","Filter result":"Filtrar resultados","Displaying":"Visualización","of":"de","topics": "temas"});
        gettextCatalog.setStrings('pt_br', {"By":"Por","Courses":"Cursos","Date":"Data","Forums":"Fóruns","From":"De","Here you find a resumy of the most important things of the academy. Enjoy and have a fun learning ;D":"Aqui você encontra um resumo das coisas mais importantes da academia. Aproveite e divirta-se aprendendo ;D","Last activity":"Última atividade","Learn how to use":"Aprenda a usar","Announcements":"Avisos","See all announcements":"Ver todos os avisos","This forum doesn't have any topics yet.":"Este fórum ainda não tem nenhum tópico.","View all forums":"Ver todos os fóruns","Welcome to the Academy!":"Bem-vindo à Academia!","You have":"Você tem","categories":"categorias","hide":"ocultar","latest posts":"últimas postagens","learn more practices":"aprender mais práticas","published by":"publicado por","reactions":"reações","see":"ver","tags":"tags","topic":"tópico", "Dashboard": "Painel","commented on the topic":"comentou no tópico","in the forum":"no fórum","ago":"atrás","comment":"comentário","liked":"gostaram", "Courses":"Cursos","Loading courses...":"Carregando cursos...","START DATE":"DATA DE INÍCIO","There are no courses.":"Não há cursos.","WHAT YOU LEARN AT THIS COURSE":"O QUE VOCÊ APRENDE NESTE CURSO", "Administration":"Administração","Back to the plataform":"Voltar para a plataforma","Cancel":"Cancelar","Clean":"Limpar","Contact":"Contato","Courses":"Cursos","Hi":"Olá","Login":"Acessar","Logout":"Sair","Profile":"Perfil","Register":"Registrar","Send":"Enviar","Suport":"Suporte","Latest topics":"Últimos tópicos","Load more":"Carregar mais","Create new topic":"Criar novo tópico","Assign TAGs to the topic":"Atribuir TAGs ao tópico","Attach file":"Anexar arquivo","Choose a category":"Escolha uma categoria","Choose the forum":"Escolha o fórum","Forum is required field":"O fórum é um campo obrigatório","New Topic":"Novo topico","Post new topic":"Postar novo tópico","Required fields":"Campos obrigatórios","Topic cannot be empty":"O tópico não pode estar vazio","Topic text":"Texto do tópico","Topic title is required field":"O título do tópico é um campo obrigatório","What is the category of your topic?":"Qual é a categoria do seu tópico?","What is the title of the new topic?":"Qual é o título do novo tópico?","Which forum should the new topic be in?":"Em qual fórum o novo tópico deve estar?","Edit topic":"Editar tópico","by":"por","Like":"Gostar","Comment":"Comentar","Edit":"Editar","Comments":"Comentários","last edition":"última edição","discard":"descartar","attach":"anexar","unread announcement":"aviso não lido","unread announcements":"avisos não lidos","comments":"comentários","Latest Posts":"Últimas postagens","View all topics in this forum":"Ver todos os tópicos deste fórum","No results found":"Nenhum resultado encontrado","A place for people chat and interact.":"Um lugar para as pessoas conversarem e interagirem.","CATEGORY": "CATEGORIA","Select...": "Selecionar...","Clear filters": "Limpar filtros","Topics": "Tópicos","Back":"Voltar","Filter result":"Filtrar resultados","Displaying":"Exibindo","of":"de","topics": "tópicos"});
    }]);

    app.config(['$locationProvider', '$routeProvider', 'localStorageServiceProvider',
        function config($locationProvider, $routeProvider,
            localStorageServiceProvider) {
            localStorageServiceProvider.setPrefix('');
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/topic/new/', {
                    templateUrl: 'topic-new.html',
                    controller: 'NewTopicCtrl'
                }).
                when('/topic/:topicId/', {
                    templateUrl: 'topic-detail.html',
                    controller: 'TopicCtrl'
                }).
                when('/forum/embed/', {
                    templateUrl: 'forum-embed.html',
                    controller: 'ForumEmbedCtrl',
                    reloadOnSearch: false
                }).
                when('/forum/:forumId', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                when('/', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                otherwise('/');
        }
    ]);
})(angular);
<|endoftext|>


<commit_before>(function($) {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */

  module('jQuery#takeout', {
    // This will run before each test in this module.
    setup: function() {
      this.$fixture = $('#qunit-fixture');
      this.$block = $('

').appendTo(this.$fixture);
    }
  });

  test('is a function', function () {
    expect(1);
    // Can't hurt to make sure the function exists.
    strictEqual(typeof this.$block.takeout, 'function', 'should be a function');
  });

  test('is chainable', function() {
    expect(1);
    // Not a bad test to run on collection methods.
    strictEqual(this.$block.takeout(), this.$block, 'should be chainable');
  });

  test('removes element from its place in the DOM', function () {
    expect(1);
    this.$block.takeout();
    notEqual(this.$block.parent().attr('id'), 'qunit-fixture', 'should not be a child of #qunit-fixture');
  });

  test('creates a placeholder for the element', function () {
		this.$block.takeout();
    var $placeholder = this.$fixture.children().not('#block');
    ok($placeholder.length, 'should create a new child of #qunit-fixture');
    ok($placeholder.hasClass('takeout-placeholder'), 'placeholder should have default class of "takeout-placeholder"');
  });

}(jQuery));
<commit_msg>test: expect 2 assertions in placeholder test<commit_after>(function($) {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */

  module('jQuery#takeout', {
    // This will run before each test in this module.
    setup: function() {
      this.$fixture = $('#qunit-fixture');
      this.$block = $('

').appendTo(this.$fixture);
    }
  });

  test('is a function', function () {
    expect(1);
    // Can't hurt to make sure the function exists.
    strictEqual(typeof this.$block.takeout, 'function', 'should be a function');
  });

  test('is chainable', function() {
    expect(1);
    // Not a bad test to run on collection methods.
    strictEqual(this.$block.takeout(), this.$block, 'should be chainable');
  });

  test('removes element from its place in the DOM', function () {
    expect(1);
    this.$block.takeout();
    notEqual(this.$block.parent().attr('id'), 'qunit-fixture', 'should not be a child of #qunit-fixture');
  });

  test('creates a placeholder for the element', function () {
    expect(2);
		this.$block.takeout();
    var $placeholder = this.$fixture.children().not('#block');
    ok($placeholder.length, 'should create a new child of #qunit-fixture');
    ok($placeholder.hasClass('takeout-placeholder'), 'placeholder should have default class of "takeout-placeholder"');
  });

}(jQuery));
<|endoftext|>


<commit_before>$(function () {

    // Initialize prompt buttons.
    $('[data-toggle="prompt"]').click(function (e) {

        e.preventDefault();

        bootbox.prompt($(this).data('message'), function (result) {

            var match = $(e.target).data('match') || 'yes';

            if (result === match) {
                $(e.target).unbind('click')[0].click();
            } else if (typeof result == 'string') {
                $('.bootbox.modal')
                    .find('.modal-dialog')
                    .addClass('animated shake');

                setTimeout(function () {
                    $('.bootbox.modal')
                        .find('.modal-dialog')
                        .removeClass('shake')
                        .removeClass('animated')
                }, 1000);

                return false;
            }
        });
    });
});
<commit_msg>Fix issue where matcher was not being replaced correctly<commit_after>$(function () {

    // Initialize prompt buttons.
    $('[data-toggle="prompt"]').click(function (e) {

        e.preventDefault();

        var match = $(e.target).data('match') || 'yes';

        bootbox.prompt($(this).data('message').replace(':match:', match), function (result) {

            if (result === match) {
                $(e.target).unbind('click')[0].click();
            } else if (typeof result == 'string') {
                $('.bootbox.modal')
                    .find('.modal-dialog')
                    .addClass('animated shake');

                setTimeout(function () {
                    $('.bootbox.modal')
                        .find('.modal-dialog')
                        .removeClass('shake')
                        .removeClass('animated')
                }, 1000);

                return false;
            }
        });
    });
});
<|endoftext|>


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

    var app = angular.module('discussion', [
        'discussion.controllers',
        'discussion.services',
        'discussion.directives',
        'discussion.filters',
        'core.services',
        'ngRoute',
        'ui.tinymce',
        'ui.bootstrap',
        'ngFileUpload',
        'ui.select',
        'ngSanitize',
        'ngAnimate',
        'duScroll',
        'LocalStorageModule',
        'shared',
        'djangular'
    ]);

    // Set new default values for 'duScroll'
    app.value('duScrollDuration', 1000);
    app.value('duScrollOffset', 100);

    app.config(['$locationProvider', '$routeProvider', 'localStorageServiceProvider',
        function config($locationProvider, $routeProvider,
            localStorageServiceProvider) {
            localStorageServiceProvider.setPrefix('');
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/topic/new/', {
                    templateUrl: 'topic-new.html',
                    controller: 'NewTopicCtrl'
                }).
                when('/topic/:topicId/', {
                    templateUrl: 'topic-detail.html',
                    controller: 'TopicCtrl'
                }).
                when('/forum/embed/', {
                    templateUrl: 'forum-embed.html',
                    controller: 'ForumEmbedCtrl',
                    reloadOnSearch: false
                }).
                when('/forum/:forumId', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                when('/', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                otherwise('/');
        }
    ]);
})(angular);
<commit_msg>Insert translation<commit_after>(function(angular){
    'use strict';

    var app = angular.module('discussion', [
        'gettext',
        'discussion.controllers',
        'discussion.services',
        'discussion.directives',
        'discussion.filters',
        'core.services',
        'ngRoute',
        'ui.tinymce',
        'ui.bootstrap',
        'ngFileUpload',
        'ui.select',
        'ngSanitize',
        'ngAnimate',
        'duScroll',
        'LocalStorageModule',
        'shared',
        'djangular'
    ]);

    // Set new default values for 'duScroll'
    app.value('duScrollDuration', 1000);
    app.value('duScrollOffset', 100);

    angular.module('discussion').run(['gettextCatalog', 'UserLocalStorage', function (gettextCatalog, UserLocalStorage) {
        let defaultLanguage = UserLocalStorage.get('currentLanguage') || 'en';

        gettextCatalog.setCurrentLanguage(defaultLanguage);
        UserLocalStorage.set('currentLanguage', defaultLanguage);

        //UserLocalStorage.set('currentLanguage', 'en');
        gettextCatalog.setStrings('es', {"By":"Por","Courses":"Cursos","Date":"Fecha","Forums":"Foros","From":"De","Here you find a resumy of the most important things of the academy. Enjoy and have a fun learning ;D":"Aquí encontrará un resumen de las cosas más importantes de la academia. Disfruta y diviértete aprendiendo ;D","Last activity":"Última actividad","Learn how to use":"Aprender cómo usar","Notifications":"Notificaciones","See all notifications":"Ver todas las notificaciones","This forum doesn't have any topics yet.":"Este foro aún no tiene ningún tema.","View all forums":"Ver todos los foros","Welcome to the Academy!":"¡Bienvenidos a la Academia!","You have":"Tú tienes","categories":"categorias","hide":"esconder","latest posts":"últimas publicaciones","learn more practices":"aprender más prácticas","published by":"publicado por","reactions":"reacciones","see":"ver","tags":"tags","topic":"tema","unread notification":"notificación no leída","unread notifications":"notificaciones no leídas", "Dashboard":"Panel","commented on the topic":"comentó sobre el tema","in the forum":"en el foro","ago":"atrás","comment":"comentario","liked":"gusta", "Courses":"Cursos","Loading courses...":"Cargando cursos...","START DATE":"FECHA DE INICIO","There are no courses.":"No hay cursos.","WHAT YOU LEARN AT THIS COURSE":"LO QUE APRENDES EN ESTE CURSO", "Administration":"Administración","Administração":"Administração","Back to the plataform":"De vuelta al plataform","Cancel":"Cancelar","Clean":"Limpiar","Contact":"Contacto","Courses":"Cursos","Hi":"Olá","Login":"Acceso","Logout":"Cerrar sesión","Profile":"Perfil","Register":"Registrarse","Send":"Enviar","Suport":"Apoyo","Latest topics":"Últimos temas","Load more":"Carga más","Create new topic":"Crear nuevo tema","Assign TAGs to the topic":"Asignar TAGs al tema","Attach file":"Adjuntar archivo","Choose a category":"Elige una categoría","Choose the forum":"Elige el foro","Forum is required field":"El foro es un campo obligatorio","Post new topic":"Nuevo tema","Required fields":"Campos requeridos","Topic cannot be empty":"El tema no puede estar vacío","Topic text":"Texto del tema","Topic title is required field":"El título del tema es un campo obligatorio","What is the category of your topic?":"¿Cuál es la categoría de su tema?","What is the title of the new topic?":"¿Cuál es el título del nuevo tema?","Which forum should the new topic be in?":"¿En qué foro debería estar el nuevo tema?","New Topic":"Nuevo tema","Edit topic":"Editar tema","by":"por","Like":"Gusta","Comment":"Comentario","Edit":"Editar","Comments":"Comentarios", "last edition":"última edición","discard":"descarte","attach":"adjuntar"});
        gettextCatalog.setStrings('pt_br', {"By":"Por","Courses":"Cursos","Date":"Data","Forums":"Fóruns","From":"De","Here you find a resumy of the most important things of the academy. Enjoy and have a fun learning ;D":"Aqui você encontra um resumo das coisas mais importantes da academia. Aproveite e divirta-se aprendendo ;D","Last activity":"Última atividade","Learn how to use":"Aprenda a usar","Notifications":"Avisos","See all notifications":"Ver todos os avisos","This forum doesn't have any topics yet.":"Este fórum ainda não tem nenhum tópico.","View all forums":"Ver todos os fóruns","Welcome to the Academy!":"Bem-vindo à Academia!","You have":"Você tem","categories":"categorias","hide":"ocultar","latest posts":"últimas postagens","learn more practices":"aprender mais práticas","published by":"publicado por","reactions":"reações","see":"ver","tags":"tags","topic":"tópico", "Dashboard": "Painel","commented on the topic":"comentou no tópico","in the forum":"no fórum","ago":"atrás","comment":"comentário","liked":"gostou", "Courses":"Cursos","Loading courses...":"Carregando cursos...","START DATE":"DATA DE INÍCIO","There are no courses.":"Não há cursos.","WHAT YOU LEARN AT THIS COURSE":"O QUE VOCÊ APRENDE NESTE CURSO", "Administration":"Administração","Back to the plataform":"Voltar para a plataforma","Cancel":"Cancelar","Clean":"Limpar","Contact":"Contato","Courses":"Cursos","Hi":"Olá","Login":"Acessar","Logout":"Sair","Profile":"Perfil","Register":"Registrar","Send":"Enviar","Suport":"Suporte","Latest topics":"Últimos tópicos","Load more":"Carregar mais","Create new topic":"Criar novo tópico","Assign TAGs to the topic":"Atribuir TAGs ao tópico","Attach file":"Anexar arquivo","Choose a category":"Escolha uma categoria","Choose the forum":"Escolha o fórum","Forum is required field":"O fórum é um campo obrigatório","New Topic":"Novo topico","Post new topic":"Postar novo tópico","Required fields":"Campos obrigatórios","Topic cannot be empty":"O tópico não pode estar vazio","Topic text":"Texto do tópico","Topic title is required field":"O título do tópico é um campo obrigatório","What is the category of your topic?":"Qual é a categoria do seu tópico?","What is the title of the new topic?":"Qual é o título do novo tópico?","Which forum should the new topic be in?":"Em qual fórum o novo tópico deve estar?","Edit topic":"Editar tópico","by":"por","Like":"Gostar","Comment":"Comentar","Edit":"Editar","Comments":"Comentários","last edition":"última edição","discard":"descartar","attach":"anexar"});
    }]);

    app.config(['$locationProvider', '$routeProvider', 'localStorageServiceProvider',
        function config($locationProvider, $routeProvider,
            localStorageServiceProvider) {
            localStorageServiceProvider.setPrefix('');
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/topic/new/', {
                    templateUrl: 'topic-new.html',
                    controller: 'NewTopicCtrl'
                }).
                when('/topic/:topicId/', {
                    templateUrl: 'topic-detail.html',
                    controller: 'TopicCtrl'
                }).
                when('/forum/embed/', {
                    templateUrl: 'forum-embed.html',
                    controller: 'ForumEmbedCtrl',
                    reloadOnSearch: false
                }).
                when('/forum/:forumId', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                when('/', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                otherwise('/');
        }
    ]);
})(angular);
<|endoftext|>


<commit_before>export { Base };

import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as Weights from "../Unpacker/Weights.js";
import * as ReturnOrClone_Activation from "./ReturnOrClone_Activation.js";

/**
 * Handle depthwise convolution, bias and activation.
 *
 * @member {number} byteOffsetBegin
 *   The position which is started (inclusive) to extract from inputFloat32Array.buffer by init().
 *
 * @member {number} byteOffsetEnd
 *   The position which is ended to (non-inclusive) extract from inputFloat32Array.buffer by init(). Where to extract next weights.
 * Only meaningful when ( this.bInitOk == true ).
 *
 * @member {boolean} bExisted
 *   If true, this pointwise convolution exist.
 *
 * @member {boolean} bInitOk
 *   If true, the init() is successful.
 *
 * @member {function} pfnOperation
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensor may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Avg_and_destroy(), Avg_and_keep(), Max_and_destroy(), Max_and_keep(),
 * Conv_and_destroy(), Conv_and_keep() according to the parameters.
 *
 * @member {function} pfnOperationBiasActivation
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensors may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Operation_and_destroy_or_keep(), OperationBias_and_destroy_or_keep(),
 * OperationActivation_and_destroy_or_keep(), OperationBiasActivation_and_destroy_or_keep() according to the parameters.
 */
class Base extends ReturnOrClone_Activation.Base {

  constructor(
    inputChannelCount,
    AvgMax_Or_ChannelMultiplier, filterHeight, stridesPad, bBias, nActivationId,
    inputFloat32Array, byteOffsetBegin ) {

    this.inputChannelCount = inputChannelCount;
    this.AvgMax_Or_ChannelMultiplier = AvgMax_Or_ChannelMultiplier;
    this.filterHeight = filterHeight;
    this.stridesPad = stridesPad;
    this.bBias = bBias;
    this.nActivationId = nActivationId;
    this.inputFloat32Array = inputFloat32Array;
    this.byteOffsetBegin = byteOffsetBegin;
  }

  init() {
    this.disposeTensors();

    this.bDepthwise = this.bDepthwiseAvg = this.bDepthwiseMax = this.bDepthwiseConv = false; // Assume no depthwise.
    this.outputChannelCount = this.inputChannelCount; // Assume no channel multiplier.

    this.filterWidth = this.filterHeight;  // Assume depthwise filter's width equals its height.

    if ( this.AvgMax_Or_ChannelMultiplier < 0 ) { // Depthwise by AVG or MAX pooling (so no channel multiplier).

      // if 1x1 AVG pooling, or 1x1 MAX pooling, or illegal pooling type (i.e. not AVG, not MAX):
      //   - As no depthwise operation (i.e. ( this.bDepthwise == true ) )
      //   - Just return input (i.e. ( this.pfnOperation == Base.return_input_directly ) )

      if ( ( 1 == this.filterHeight ) && ( 1 == this.filterWidth ) ) {
        this.pfnOperation = Base.return_input_directly; // Do nothing, because the result of 1x1 AVG or MAX pooling is just the same as input.
      } else {
        switch ( this.AvgMax_Or_ChannelMultiplier ) {
          case ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG:
            this.bDepthwise = this.bDepthwiseAvg = true;
            this.pfnOperation = Base.Avg_and_destroy;
            break;

          case ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX:
            this.bDepthwise = this.bDepthwiseMax = true;
            this.pfnOperation = Base.Max_and_destroy;
            break;
        }
      }

    } else {
      if ( this.AvgMax_Or_ChannelMultiplier >= 1 ) { // Depthwise by convolution (with channel multiplier).
        this.bDepthwise = this.bDepthwiseConv = true;

        this.outputChannelCount = this.inputChannelCount * this.AvgMax_Or_ChannelMultiplier;

        this.filtersShape = [ this.filterHeight, this.filterWidth, this.inputChannelCount, this.AvgMax_Or_ChannelMultiplier ];

        this.filtersWeights = new Weights.Base( this.inputFloat32Array, this.byteOffsetEnd, this.filtersShape );
        if ( !this.filtersWeights.extract() )
          return false;  // e.g. input array does not have enough data.

        this.byteOffsetEnd = this.filtersWeights.defaultByteOffsetEnd;

        this.filtersTensor4d = tf.tensor4d( this.filtersWeights.weights, this.filtersShape );
        this.pfnOperation = Base.Conv_and_destroy; // will dispose inputTensor.

      } else { // No depthwise (e.g. zero or negative number) (so no channel multiplier).
      }
    }

    switch ( this.stridesPad ) {
      case 0:  this.strides = 1; this.pad = "valid"; break;
      default:
      case 1:  this.strides = 1; this.pad = "same";  break;
      case 2:  this.strides = 2; this.pad = "same";  break;
    }

    this.pfnActivation = Base.getActivationFunction( this.nActivationId );

    this.filterHeightWidth = [ this.filterHeight, this.filterWidth ];
    this.biasesShape =       [ 1, 1, this.outputChannelCount ];

    if ( this.bDepthwise ) {

      if ( this.bBias ) {
        this.biasesWeights = new Weights.Base( this.inputFloat32Array, this.byteOffsetEnd, this.biasesShape );
        if ( !this.biasesWeights.extract() )
          return false;  // e.g. input array does not have enough data.
        this.byteOffsetEnd = this.biasesWeights.defaultByteOffsetEnd;

        this.biasesTensor3d = tf.tensor3d( this.biasesWeights.weights, this.biasesShape );

        if ( this.pfnActivation )
          this.pfnOperationBiasActivation = Base.OperationBiasActivation_and_destroy_or_keep;
        else
          this.pfnOperationBiasActivation = Base.OperationBias_and_destroy_or_keep;

      } else {

        if ( this.pfnActivation )
          this.pfnOperationBiasActivation = Base.OperationActivation_and_destroy_or_keep;
         else
          this.pfnOperationBiasActivation = Base.Operation_and_destroy_or_keep;

      }

    } else {
      // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
      this.pfnOperationBiasActivation = this.pfnOperation = Base.return_input_directly;
    }

    this.bInitOk = true;
  }

  disposeTensors() {
    if ( this.filtersTensor4d ) {
      this.filtersTensor4d.dispose();
      this.filtersTensor4d = null;
    }

    if ( this.biasesTensor3d ) {
      this.biasesTensor3d.dispose();
      this.biasesTensor3d = null;
    }

    this.filtersWeights = this.biasesWeights = this.pfnOperationBiasActivation = this.pfnOperation = this.pfnActivation = null;
    this.byteOffsetEnd = -1;
    this.bKeepInputTensor = false;  // Default will dispose input tensor.
    this.bInitOk = false;
  }

  /**
   * Adjust this.pfnOperation (and this.pfnOperationBiasActivation if need) so that this.pfnOperation() and this.pfnOperationBiasActivation()
   * will or will not dispose its inputTensor.
   */
  setKeepInputTensor( bKeepInputTensor ) {
    this.bKeepInputTensor = bKeepInputTensor;

    if ( bKeepInputTensor ) {

      switch ( this.pfnOperation ) {

        // Just clone input if 1x1 AVG/MAX pooling or illegal pooling type (i.e. not AVG, not MAX).
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        case Base.return_input_directly: this.pfnOperation = this.pfnOperationBiasActivation = Base.keep_input_return_copy; break;

        case Base.Avg_and_destroy:       this.pfnOperation = Base.Avg_and_keep;  break;
        case Base.Max_and_destroy:       this.pfnOperation = Base.Max_and_keep;  break;
        case Base.Conv_and_destroy:      this.pfnOperation = Base.Conv_and_keep; break;

        // Just clone input if unknown depthwise operation.
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        default:                         this.pfnOperation = this.pfnOperationBiasActivation = Base.keep_input_return_copy;
          tf.util.assert( false, `Unknown depthwise operation. (${this.pfnOperation}) when setKeepInputTensor( ${bKeepInputTensor} )` );
          break;
      }

    } else {

      switch ( this.pfnOperation ) {

        // Just return input if 1x1 AVG/MAX pooling or illegal pooling type (i.e. not AVG, not MAX).
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        case Base.keep_input_return_copy: this.pfnOperation = this.pfnOperationBiasActivation = Base.return_input_directly; break;

        case Base.Avg_and_keep:           this.pfnOperation = Base.Avg_and_destroy;  break;
        case Base.Max_and_keep:           this.pfnOperation = Base.Max_and_destroy;  break;
        case Base.Conv_and_keep:          this.pfnOperation = Base.Conv_and_destroy; break;

        // Just return input if unknown depthwise operation.
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        default:                          this.pfnOperation = this.pfnOperationBiasActivation = Base.return_input_directly;
          tf.util.assert( false, `Unknown depthwise operation. (${this.pfnOperation}) when setKeepInputTensor( ${bKeepInputTensor} )` );
          break;
      }

    }
  }

  /** Depthwise Average Pooling. */
  static Avg_and_keep( inputTensor ) {
    return tf.pool( inputTensor, this.filterHeightWidth, "avg", this.pad, 1, this.strides ); // dilations = 1
  }

  static Avg_and_destroy( inputTensor ) {
    let t = tf.pool( inputTensor, this.filterHeightWidth, "avg", this.pad, 1, this.strides ); // dilations = 1
    inputTensor.dispose();
    return t;
  }

  /** Depthwise Max Pooling. */
  static Max_and_keep( inputTensor ) {
    return tf.pool( inputTensor, this.filterHeightWidth, "max", this.pad, 1, this.strides ); // dilations = 1
  }

  static Max_and_destroy( inputTensor ) {
    let t = tf.pool( inputTensor, this.filterHeightWidth, "max", this.pad, 1, this.strides ); // dilations = 1
    inputTensor.dispose();
    return t;
  }

  /** Depthwise Convolution. */
  static Conv_and_keep( inputTensor ) {
    return tf.depthwiseConv2d( inputTensor, this.filtersTensor4d, this.strides, this.pad );
  }

  static Conv_and_destroy( inputTensor ) {
    let t = tf.depthwiseConv2d( inputTensor, this.filtersTensor4d, this.strides, this.pad );
    inputTensor.dispose();
    return t;
  }

  /** Depthwise Operation, Bias and Activation. */
  static Operation_and_destroy_or_keep( inputTensor ) {
    return this.pfnOperation( inputTensor ); // may destroy or keep.
  }

  static OperationBias_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnOperation( inputTensor ); // may destroy or keep.

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    return t1;
  }

  static OperationActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnOperation( inputTensor ); // may destroy or keep.

    let t1 = this.pfnActivation( t0 );
    t0.dispose();

    return t1;
  }

  static OperationBiasActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnOperation( inputTensor ); // may destroy or keep.

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    t0 = this.pfnActivation( t1 );
    t1.dispose();

    return t0;
  }

}
<commit_msg>Update Depthwise.js<commit_after>export { Base };

import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as Weights from "../Unpacker/Weights.js";
import * as ReturnOrClone_Activation from "./ReturnOrClone_Activation.js";

/**
 * Handle depthwise convolution, bias and activation.
 *
 * @member {number} byteOffsetBegin
 *   The position which is started (inclusive) to extract from inputFloat32Array.buffer by init().
 *
 * @member {number} byteOffsetEnd
 *   The position which is ended to (non-inclusive) extract from inputFloat32Array.buffer by init(). Where to extract next weights.
 * Only meaningful when ( this.bInitOk == true ).
 *
 * @member {boolean} bExisted
 *   If true, this depthwise convolution exist.
 *
 * @member {boolean} bInitOk
 *   If true, the init() is successful.
 *
 * @member {function} pfnOperation
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensor may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Avg_and_destroy(), Avg_and_keep(), Max_and_destroy(), Max_and_keep(),
 * Conv_and_destroy(), Conv_and_keep() according to the parameters.
 *
 * @member {function} pfnOperationBiasActivation
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensors may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Operation_and_destroy_or_keep(), OperationBias_and_destroy_or_keep(),
 * OperationActivation_and_destroy_or_keep(), OperationBiasActivation_and_destroy_or_keep() according to the parameters.
 */
class Base extends ReturnOrClone_Activation.Base {

  constructor(
    inputChannelCount,
    AvgMax_Or_ChannelMultiplier, filterHeight, stridesPad, bBias, nActivationId,
    inputFloat32Array, byteOffsetBegin ) {

    this.inputChannelCount = inputChannelCount;
    this.AvgMax_Or_ChannelMultiplier = AvgMax_Or_ChannelMultiplier;
    this.filterHeight = filterHeight;
    this.stridesPad = stridesPad;
    this.bBias = bBias;
    this.nActivationId = nActivationId;
    this.inputFloat32Array = inputFloat32Array;
    this.byteOffsetBegin = byteOffsetBegin;
  }

  init() {
    this.disposeTensors();

    this.bDepthwise = this.bDepthwiseAvg = this.bDepthwiseMax = this.bDepthwiseConv = false; // Assume no depthwise.
    this.outputChannelCount = this.inputChannelCount; // Assume no channel multiplier.

    this.filterWidth = this.filterHeight;  // Assume depthwise filter's width equals its height.

    if ( this.AvgMax_Or_ChannelMultiplier < 0 ) { // Depthwise by AVG or MAX pooling (so no channel multiplier).

      // if 1x1 AVG pooling, or 1x1 MAX pooling, or illegal pooling type (i.e. not AVG, not MAX):
      //   - As no depthwise operation (i.e. ( this.bDepthwise == true ) )
      //   - Just return input (i.e. ( this.pfnOperation == Base.return_input_directly ) )

      if ( ( 1 == this.filterHeight ) && ( 1 == this.filterWidth ) ) {
        this.pfnOperation = Base.return_input_directly; // Do nothing, because the result of 1x1 AVG or MAX pooling is just the same as input.
      } else {
        switch ( this.AvgMax_Or_ChannelMultiplier ) {
          case ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG:
            this.bDepthwise = this.bDepthwiseAvg = true;
            this.pfnOperation = Base.Avg_and_destroy;
            break;

          case ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX:
            this.bDepthwise = this.bDepthwiseMax = true;
            this.pfnOperation = Base.Max_and_destroy;
            break;
        }
      }

    } else {
      if ( this.AvgMax_Or_ChannelMultiplier >= 1 ) { // Depthwise by convolution (with channel multiplier).
        this.bDepthwise = this.bDepthwiseConv = true;

        this.outputChannelCount = this.inputChannelCount * this.AvgMax_Or_ChannelMultiplier;

        this.filtersShape = [ this.filterHeight, this.filterWidth, this.inputChannelCount, this.AvgMax_Or_ChannelMultiplier ];

        this.filtersWeights = new Weights.Base( this.inputFloat32Array, this.byteOffsetEnd, this.filtersShape );
        if ( !this.filtersWeights.extract() )
          return false;  // e.g. input array does not have enough data.

        this.byteOffsetEnd = this.filtersWeights.defaultByteOffsetEnd;

        this.filtersTensor4d = tf.tensor4d( this.filtersWeights.weights, this.filtersShape );
        this.pfnOperation = Base.Conv_and_destroy; // will dispose inputTensor.

      } else { // No depthwise (e.g. zero or negative number) (so no channel multiplier).
      }
    }

    switch ( this.stridesPad ) {
      case 0:  this.strides = 1; this.pad = "valid"; break;
      default:
      case 1:  this.strides = 1; this.pad = "same";  break;
      case 2:  this.strides = 2; this.pad = "same";  break;
    }

    this.pfnActivation = Base.getActivationFunction( this.nActivationId );

    this.filterHeightWidth = [ this.filterHeight, this.filterWidth ];
    this.biasesShape =       [ 1, 1, this.outputChannelCount ];

    if ( this.bDepthwise ) {

      if ( this.bBias ) {
        this.biasesWeights = new Weights.Base( this.inputFloat32Array, this.byteOffsetEnd, this.biasesShape );
        if ( !this.biasesWeights.extract() )
          return false;  // e.g. input array does not have enough data.
        this.byteOffsetEnd = this.biasesWeights.defaultByteOffsetEnd;

        this.biasesTensor3d = tf.tensor3d( this.biasesWeights.weights, this.biasesShape );

        if ( this.pfnActivation )
          this.pfnOperationBiasActivation = Base.OperationBiasActivation_and_destroy_or_keep;
        else
          this.pfnOperationBiasActivation = Base.OperationBias_and_destroy_or_keep;

      } else {

        if ( this.pfnActivation )
          this.pfnOperationBiasActivation = Base.OperationActivation_and_destroy_or_keep;
         else
          this.pfnOperationBiasActivation = Base.Operation_and_destroy_or_keep;

      }

    } else {
      // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
      this.pfnOperationBiasActivation = this.pfnOperation = Base.return_input_directly;
    }

    this.bInitOk = true;
  }

  disposeTensors() {
    if ( this.filtersTensor4d ) {
      this.filtersTensor4d.dispose();
      this.filtersTensor4d = null;
    }

    if ( this.biasesTensor3d ) {
      this.biasesTensor3d.dispose();
      this.biasesTensor3d = null;
    }

    this.filtersWeights = this.biasesWeights = this.pfnOperationBiasActivation = this.pfnOperation = this.pfnActivation = null;
    this.byteOffsetEnd = -1;
    this.bKeepInputTensor = false;  // Default will dispose input tensor.
    this.bInitOk = false;
  }

  /**
   * Adjust this.pfnOperation (and this.pfnOperationBiasActivation if need) so that this.pfnOperation() and this.pfnOperationBiasActivation()
   * will or will not dispose its inputTensor.
   */
  setKeepInputTensor( bKeepInputTensor ) {
    this.bKeepInputTensor = bKeepInputTensor;

    if ( bKeepInputTensor ) {

      switch ( this.pfnOperation ) {

        // Just clone input if 1x1 AVG/MAX pooling or illegal pooling type (i.e. not AVG, not MAX).
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        case Base.return_input_directly: this.pfnOperation = this.pfnOperationBiasActivation = Base.keep_input_return_copy; break;

        case Base.Avg_and_destroy:       this.pfnOperation = Base.Avg_and_keep;  break;
        case Base.Max_and_destroy:       this.pfnOperation = Base.Max_and_keep;  break;
        case Base.Conv_and_destroy:      this.pfnOperation = Base.Conv_and_keep; break;

        // Just clone input if unknown depthwise operation.
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        default:                         this.pfnOperation = this.pfnOperationBiasActivation = Base.keep_input_return_copy;
          tf.util.assert( false, `Unknown depthwise operation. (${this.pfnOperation}) when setKeepInputTensor( ${bKeepInputTensor} )` );
          break;
      }

    } else {

      switch ( this.pfnOperation ) {

        // Just return input if 1x1 AVG/MAX pooling or illegal pooling type (i.e. not AVG, not MAX).
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        case Base.keep_input_return_copy: this.pfnOperation = this.pfnOperationBiasActivation = Base.return_input_directly; break;

        case Base.Avg_and_keep:           this.pfnOperation = Base.Avg_and_destroy;  break;
        case Base.Max_and_keep:           this.pfnOperation = Base.Max_and_destroy;  break;
        case Base.Conv_and_keep:          this.pfnOperation = Base.Conv_and_destroy; break;

        // Just return input if unknown depthwise operation.
        // Since there is no operation at all, let pfnOperationBiasActivation ignore pfnOperation completely.
        default:                          this.pfnOperation = this.pfnOperationBiasActivation = Base.return_input_directly;
          tf.util.assert( false, `Unknown depthwise operation. (${this.pfnOperation}) when setKeepInputTensor( ${bKeepInputTensor} )` );
          break;
      }

    }
  }

  /** Depthwise Average Pooling. */
  static Avg_and_keep( inputTensor ) {
    return tf.pool( inputTensor, this.filterHeightWidth, "avg", this.pad, 1, this.strides ); // dilations = 1
  }

  static Avg_and_destroy( inputTensor ) {
    let t = tf.pool( inputTensor, this.filterHeightWidth, "avg", this.pad, 1, this.strides ); // dilations = 1
    inputTensor.dispose();
    return t;
  }

  /** Depthwise Max Pooling. */
  static Max_and_keep( inputTensor ) {
    return tf.pool( inputTensor, this.filterHeightWidth, "max", this.pad, 1, this.strides ); // dilations = 1
  }

  static Max_and_destroy( inputTensor ) {
    let t = tf.pool( inputTensor, this.filterHeightWidth, "max", this.pad, 1, this.strides ); // dilations = 1
    inputTensor.dispose();
    return t;
  }

  /** Depthwise Convolution. */
  static Conv_and_keep( inputTensor ) {
    return tf.depthwiseConv2d( inputTensor, this.filtersTensor4d, this.strides, this.pad );
  }

  static Conv_and_destroy( inputTensor ) {
    let t = tf.depthwiseConv2d( inputTensor, this.filtersTensor4d, this.strides, this.pad );
    inputTensor.dispose();
    return t;
  }

  /** Depthwise Operation, Bias and Activation. */
  static Operation_and_destroy_or_keep( inputTensor ) {
    return this.pfnOperation( inputTensor ); // may destroy or keep.
  }

  static OperationBias_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnOperation( inputTensor ); // may destroy or keep.

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    return t1;
  }

  static OperationActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnOperation( inputTensor ); // may destroy or keep.

    let t1 = this.pfnActivation( t0 );
    t0.dispose();

    return t1;
  }

  static OperationBiasActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnOperation( inputTensor ); // may destroy or keep.

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    t0 = this.pfnActivation( t1 );
    t1.dispose();

    return t0;
  }

}
<|endoftext|>


<commit_before>// Run all the tests in the `npm-registry-couchapp` suite
// This verifies that the server-side stuff still works.

var test = require("tap").test

var spawn = require("child_process").spawn
var npmExec = require.resolve("../../bin/npm-cli.js")
var path = require("path")
var ca = path.resolve(__dirname, "../../node_modules/npm-registry-couchapp")

var which = require("which")
var hasCouch = false

which("couchdb", function(er, couch) {
  if (er) {
    return test("need couchdb", function (t) {
      t.fail("need couch to run test: " + er.message)
      t.end()
    })
  } else {
    runTests()
  }
})

function runTests () {
  spawn(process.execPath, [
    npmExec, "install"
  ], {
    cwd: ca,
    stdio: "inherit"
  }).on("close", function (code, sig) {
    if (code || sig) {
      return test("need install to work", function (t) {
        t.fail("install failed with: " (code || sig))
        t.end()
      })

    } else {
      var env = {}
      for (var i in process.env) env[i] = process.env[i]
      env.npm = npmExec

      spawn(process.execPath, [
        npmExec, "test"
      ], {
        cwd: ca,
        env: env,
        stdio: "inherit"
      }).on("close", function (code, sig) {
        process.exit(code || sig)
      })
    }

  })
}
<commit_msg>test: prune in npm-registry-couchapp after test<commit_after>// Run all the tests in the `npm-registry-couchapp` suite
// This verifies that the server-side stuff still works.

var test = require("tap").test

var spawn = require("child_process").spawn
var npmExec = require.resolve("../../bin/npm-cli.js")
var path = require("path")
var ca = path.resolve(__dirname, "../../node_modules/npm-registry-couchapp")

var which = require("which")
var hasCouch = false

which("couchdb", function(er, couch) {
  if (er) {
    return test("need couchdb", function (t) {
      t.fail("need couch to run test: " + er.message)
      t.end()
    })
  } else {
    runTests()
  }
})

function runTests () {
  var env = {}
  for (var i in process.env) env[i] = process.env[i]
  env.npm = npmExec

  spawn(process.execPath, [
    npmExec, "install"
  ], {
    cwd: ca,
    stdio: "inherit"
  }).on("close", function (code, sig) {
    if (code || sig) {
      return test("need install to work", function (t) {
        t.fail("install failed with: " (code || sig))
        t.end()
      })

    } else {

      spawn(process.execPath, [
        npmExec, "test"
      ], {
        cwd: ca,
        env: env,
        stdio: "inherit"
      }).on("close", function (code, sig) {
        spawn(process.execPath, [
          npmExec, "prune", "--production"
        ], {
          cwd: ca,
          env: env,
          stdio: "inherit"
        }).on("close", function (code2, sig2) {
          process.exit(code || code2 || 0)
        })
      })
    }

  })
}
<|endoftext|>


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

    var app = angular.module('discussion', [
        'discussion.controllers',
        'discussion.services',
        'discussion.directives',
        'discussion.filters',
        'ngRoute',
        'ui.tinymce',
        'ui.bootstrap',
        'ngFileUpload',
        'ui.select',
        'ngSanitize',
        'ngAnimate',
        'duScroll',
        'LocalStorageModule',
        'shared'
    ]);

    // Set new default values for 'duScroll'
    app.value('duScrollDuration', 1000);
    app.value('duScrollOffset', 100);

    app.config(['$locationProvider', '$routeProvider', 'localStorageServiceProvider',
        function config($locationProvider, $routeProvider,
            localStorageServiceProvider) {
            localStorageServiceProvider.setPrefix('');
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/topic/new/', {
                    templateUrl: 'topic-new.html',
                    controller: 'NewTopicCtrl'
                }).
                when('/topic/:topicId/', {
                    templateUrl: 'topic-detail.html',
                    controller: 'TopicCtrl'
                }).
                when('/forum/embed/', {
                    templateUrl: 'forum-embed.html',
                    controller: 'ForumEmbedCtrl',
                    reloadOnSearch: false
                }).
                when('/forum/:forumId', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                when('/', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                otherwise('/');
        }
    ]);

    app.run(function($http, localStorageService) {
        $http.defaults.headers.common.Authorization = 'Token ' + localStorageService.get('ujs-ocupa|token');
    });

    app.service('CurrentUser', ['localStorageService', function (localStorageService) {
        console.log(localStorageService.get('ujs-ocupa|currentProfile'));
        return localStorageService.get('ujs-ocupa|currentProfile');
    }]);

})(angular);
<commit_msg>Fix: add djangular in discussion-app<commit_after>(function(angular){
    'use strict';

    var app = angular.module('discussion', [
        'discussion.controllers',
        'discussion.services',
        'discussion.directives',
        'discussion.filters',
        'ngRoute',
        'ui.tinymce',
        'ui.bootstrap',
        'ngFileUpload',
        'ui.select',
        'ngSanitize',
        'ngAnimate',
        'duScroll',
        'LocalStorageModule',
        'shared',
        'djangular'
    ]);

    // Set new default values for 'duScroll'
    app.value('duScrollDuration', 1000);
    app.value('duScrollOffset', 100);

    app.config(['$locationProvider', '$routeProvider', 'localStorageServiceProvider',
        function config($locationProvider, $routeProvider,
            localStorageServiceProvider) {
            localStorageServiceProvider.setPrefix('');
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/topic/new/', {
                    templateUrl: 'topic-new.html',
                    controller: 'NewTopicCtrl'
                }).
                when('/topic/:topicId/', {
                    templateUrl: 'topic-detail.html',
                    controller: 'TopicCtrl'
                }).
                when('/forum/embed/', {
                    templateUrl: 'forum-embed.html',
                    controller: 'ForumEmbedCtrl',
                    reloadOnSearch: false
                }).
                when('/forum/:forumId', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                when('/', {
                    templateUrl: 'forum.html',
                    controller: 'ForumCtrl',
                    reloadOnSearch: false
                }).
                otherwise('/');
        }
    ]);
})(angular);
<|endoftext|>


<commit_before>const asyncFn = require('asyncawait/async');
const awaitFn = require('asyncawait/await');
const test = require('tape');

const app = require('../server');
const terence = require('../bot/terence');
const BotController = require('../api/controllers/BotController');

const botData = {
	twitterID: '12345',
	money: 0,
};

const coinTypes = ['💰', '💵', '💶', '💷', '💴', '💸', '💳'];

const {
	cleanup,
} = require('./helper');

test('Clean up', cleanup);

test('Ask Terence for a status report', asyncFn(t => {
	const tweet = {
		user: {
			screen_name: 'vnglst',
		},
	};
	const result = awaitFn(terence.__tests.handleStatus(tweet));
	t.ok(result, 'A status reply should be tweeted');
	const tweetId = result.data.id_str;
	t.ok(tweetId, 'A tweet id should be found');
	terence.bot.destroy(tweetId)
		.then(delResult => {
			t.ok(delResult, 'Status tweet should be deleted');
			t.end();
		});
}));

test('Donate Terence some money', asyncFn(t => {
	const dbBot = awaitFn(BotController.createOrFindBot(botData));
	t.ok(dbBot, 'A bot should be created in the database');
	const tweet = {
		text: 'here some 💰💰💰💵💶💷💴💸💳',
		user: {
			screen_name: 'vnglst',
		},
	};
	const result = awaitFn(terence.__tests.handleDonation(tweet, coinTypes));
	t.ok(result, 'A thank you tweet should be created');
	const tweetId = result.data.id_str;
	t.ok(tweetId, 'A tweet id should be found');
	const tweetText = result.data.text;
	t.ok(tweetText.includes('9 monies'),
		'Tweet text should include 9 monies');
	terence.bot.destroy(tweetId)
		.then(delResult => {
			t.ok(delResult, 'Thank you tweet should be deleted');
			t.end();
		});
}));

test('Let @vnglst donate Terence some money again', asyncFn(t => {
	const dbBot = awaitFn(BotController.createOrFindBot(botData));
	t.ok(dbBot, 'A bot should be created in the database');
	const tweet = {
		text: '💵',
		user: {
			screen_name: 'vnglst',
		},
	};
	const result = awaitFn(terence.__tests.handleDonation(tweet, coinTypes));

	const tweetId = result.data.id_str;
	const tweetText = result.data.text;
	t.ok(tweetText.includes('already donated'),
		'Should be a already donated tweet');
	terence.bot.destroy(tweetId)
		.then(delResult => {
			t.ok(delResult, 'Already donated tweet should be deleted');
			t.end();
		});
}));

test('Clean up', cleanup);

test.onFinish(() => process.exit(0));
<commit_msg>updates tests<commit_after>const asyncFn = require('asyncawait/async');
const awaitFn = require('asyncawait/await');
const test = require('tape');

const app = require('../server');
const terence = require('../bot/terence');
const BotController = require('../api/controllers/BotController');

const botData = {
	twitterID: '12345',
	money: 0,
};

const coinTypes = ['💰', '💵', '💶', '💷', '💴', '💸', '💳'];

const {
	cleanup,
} = require('./helper');

test('Clean up', cleanup);

test('Ask Terence for a status report', asyncFn(t => {
	const tweet = {
		user: {
			screen_name: 'vnglst',
		},
	};
	const result = awaitFn(terence.__tests.handleStatus(tweet));
	t.ok(result, 'A status reply should be tweeted');
	const tweetId = result.data.id_str;
	t.ok(tweetId, 'A tweet id should be found');
	terence.bot.destroy(tweetId)
		.then(delResult => {
			t.ok(delResult, 'Status tweet should be deleted');
			t.end();
		});
}));

test('Donate Terence some money', asyncFn(t => {
	const dbBot = awaitFn(BotController.createOrFindBot(botData));
	t.ok(dbBot, 'A bot should be created in the database');
	const tweet = {
		text: 'here some 💰💰💰💵💶💷💴💸💳',
		user: {
			screen_name: 'vnglst',
		},
	};
	const result = awaitFn(terence.__tests.handleDonation(tweet, coinTypes));
	t.ok(result, 'A thank you tweet should be created');
	const tweetId = result.data.id_str;
	t.ok(tweetId, 'A tweet id should be found');
	const tweetText = result.data.text;
	t.comment(tweetText);
	t.ok(tweetText.includes('9'),
		'Tweet text should include number 9');
	terence.bot.destroy(tweetId)
		.then(delResult => {
			t.ok(delResult, 'Thank you tweet should be deleted');
			t.end();
		});
}));

test('Let @vnglst donate Terence some money again', asyncFn(t => {
	const dbBot = awaitFn(BotController.createOrFindBot(botData));
	t.ok(dbBot, 'A bot should be created in the database');
	const tweet = {
		text: '💵',
		user: {
			screen_name: 'vnglst',
		},
	};
	const result = awaitFn(terence.__tests.handleDonation(tweet, coinTypes));

	const tweetId = result.data.id_str;
	const tweetText = result.data.text;
	t.ok(tweetText.includes('already donated'),
		'Should be a already donated tweet');
	terence.bot.destroy(tweetId)
		.then(delResult => {
			t.ok(delResult, 'Already donated tweet should be deleted');
			t.end();
		});
}));

test('Clean up', cleanup);

test.onFinish(() => process.exit(0));
<|endoftext|>


<commit_before>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";

            for (var i = 0; gamesData.games.length; i++) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[i].id;
                var threadurl = gamesData.games[i].url;
                gamesToHtml +=  '' + gamesData.games[i].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[i].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = {
                "27ninjabunnies": ["27nb", "nb", "ninja", "bunnies", "ninjabunnies"],
                "Alakaslam": ["slam"],
                "Artanis[Xp]": ["art", "artanis"],
                "batsnacks": ["bat", "bats"],
                "Bill Murray": ["bm", "bill", "murray"],
                "Blazinghand": ["bh", "blazing"],
                "boxerfred": ["bf", "boxer"],
                "Chezinu": ["che", "chez"],
                "Clarity_nl": ["clarity"],
                "Damdred": ["damd", "damdy"],
                "EdgarAllanPoE": ["edgar", "allan", "poe", "edgarallenpoe"],
                "Fecalfeast": ["ff", "fecal"],
                "Fidei86": ["fidei"],
                "FirmTofu": ["ft", "firm", "tofu"],
                "GlowingBear": ["gb", "glowing", "bear"],
                "Half the Sky": ["hts", "sky"],
                "Hapahauli": ["hapa"],
                "Holyflare": ["hf"],
                "IAmRobik": ["robik"],
                "JudgeJudy": ["jj", "judge", "judy"],
                "justanothertownie": ["jat"],
                "Keirathi": ["kei", "keir"],
                "LightningStrike": ["ls", "lightning"],
                "marvellosity": ["marv", "marvy", "marvel", "marvelocity", "marshmallow"],
                "Oatsmaster": ["oat", "oats"],
                "ObiWanShinobi": ["ows", "obi", "obiwan", "shinobi"],
                "Onegu": ["o", "oneg"],
                "raynpelikoneet": ["ray", "rayn", "raypelikoneet"],
                "rsoultin": ["rs", "rsou", "rsoul"],
                "sandroba": ["sand", "roba"],
                "[UoN]Sentinel": ["sent", "sentinel"],
                "scott31337": ["scott"],
                "Stutters695": ["stutters"],
                "The Shining": ["shining"],
                "Tubesock": ["ts", "tube"],
                "VayneAuthority": ["va", "vayne"],
                "VisceraEyes": ["ve", "viscera"],
                "WaveofShadow": ["wos", "wave"],
                "Xatalos": ["xat", "xata"],
                "yamato77": ["yam", "yama", "yamato"]
            };

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target.toLowerCase()) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = targets.length - 1; i >= 0; i--) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < gameData.votes.length; j++) {
                        if (currentDay == gameData.votes[j].day && gameData.votes[j].target.toLowerCase() == targets[i].toLowerCase()) {
                            if(voters.hasOwnProperty(targets[i]) || activeVoters.hasOwnProperty(targets[i])){
                                continue;
                            }
                            // add a new key (property) to the object for every vote target during the current day
                            voters[targets[i]] = [];
                            activeVoters[targets[i]] = [];
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]];
                            for (var z = remainingVoters.length - 1; z >= 0; z--) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous ACTIVE vote from the voters
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var activesList = activeVoters[targets[i]];
                    for (var j = 0; j < activesList.length; j++) {
                        for (var z = nonvoters.length - 1; z >= 0; z--) {
                            if (activesList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var mainVotersList = activeVoters[targets[i]];
                    for (var j = 0; j < mainVotersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(mainVotersList[j]) == -1 && mainVotersList[j].indexOf("<s>") == -1) {
                                mainVotersList[j] = "<s>" + mainVotersList[j] + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + mainVotersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]];
                    for (var j = 0; j < votersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(votersList[j]) == -1 && votersList[j].indexOf("[s]") == -1) {
                                votersList[j] = "[s]" + votersList[j] + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            console.log(voters[targets[0]]);
            console.log(activeVoters[targets[0]]);

            var propValue;
            for(var propName in voters) {
                propValue = voters[propName]
                console.log(propName);
            }

            var propValue;
            for(var propName in activeVoters) {
                propValue = voters[propName]
                console.log(propName, propValue);
            }

            var propValue;
            for(var propName in voters) {
                propValue = voters[propName]
                console.log(propName, propValue);
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<commit_msg>fixed the main menu<commit_after>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var x = 0;

            for (key in gamesData.games) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = {
                "27ninjabunnies": ["27nb", "nb", "ninja", "bunnies", "ninjabunnies"],
                "Alakaslam": ["slam"],
                "Artanis[Xp]": ["art", "artanis"],
                "batsnacks": ["bat", "bats"],
                "Bill Murray": ["bm", "bill", "murray"],
                "Blazinghand": ["bh", "blazing"],
                "boxerfred": ["bf", "boxer"],
                "Chezinu": ["che", "chez"],
                "Clarity_nl": ["clarity"],
                "Damdred": ["damd", "damdy"],
                "EdgarAllanPoE": ["edgar", "allan", "poe", "edgarallenpoe"],
                "Fecalfeast": ["ff", "fecal"],
                "Fidei86": ["fidei"],
                "FirmTofu": ["ft", "firm", "tofu"],
                "GlowingBear": ["gb", "glowing", "bear"],
                "Half the Sky": ["hts", "sky"],
                "Hapahauli": ["hapa"],
                "Holyflare": ["hf"],
                "IAmRobik": ["robik"],
                "JudgeJudy": ["jj", "judge", "judy"],
                "justanothertownie": ["jat"],
                "Keirathi": ["kei", "keir"],
                "LightningStrike": ["ls", "lightning"],
                "marvellosity": ["marv", "marvy", "marvel", "marvelocity", "marshmallow"],
                "Oatsmaster": ["oat", "oats"],
                "ObiWanShinobi": ["ows", "obi", "obiwan", "shinobi"],
                "Onegu": ["o", "oneg"],
                "raynpelikoneet": ["ray", "rayn", "raypelikoneet"],
                "rsoultin": ["rs", "rsou", "rsoul"],
                "sandroba": ["sand", "roba"],
                "[UoN]Sentinel": ["sent", "sentinel"],
                "scott31337": ["scott"],
                "Stutters695": ["stutters"],
                "The Shining": ["shining"],
                "Tubesock": ["ts", "tube"],
                "VayneAuthority": ["va", "vayne"],
                "VisceraEyes": ["ve", "viscera"],
                "WaveofShadow": ["wos", "wave"],
                "Xatalos": ["xat", "xata"],
                "yamato77": ["yam", "yama", "yamato"]
            };

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target.toLowerCase()) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = targets.length - 1; i >= 0; i--) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < gameData.votes.length; j++) {
                        if (currentDay == gameData.votes[j].day && gameData.votes[j].target.toLowerCase() == targets[i].toLowerCase()) {
                            if(voters.hasOwnProperty(targets[i]) || activeVoters.hasOwnProperty(targets[i])){
                                continue;
                            }
                            // add a new key (property) to the object for every vote target during the current day
                            voters[targets[i]] = [];
                            activeVoters[targets[i]] = [];
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]];
                            for (var z = remainingVoters.length - 1; z >= 0; z--) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous ACTIVE vote from the voters
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var activesList = activeVoters[targets[i]];
                    for (var j = 0; j < activesList.length; j++) {
                        for (var z = nonvoters.length - 1; z >= 0; z--) {
                            if (activesList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var mainVotersList = activeVoters[targets[i]];
                    for (var j = 0; j < mainVotersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(mainVotersList[j]) == -1 && mainVotersList[j].indexOf("<s>") == -1) {
                                mainVotersList[j] = "<s>" + mainVotersList[j] + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + mainVotersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]];
                    for (var j = 0; j < votersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(votersList[j]) == -1 && votersList[j].indexOf("[s]") == -1) {
                                votersList[j] = "[s]" + votersList[j] + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            console.log(voters[targets[0]]);
            console.log(activeVoters[targets[0]]);

            var propValue;
            for(var propName in voters) {
                propValue = voters[propName]
                console.log(propName);
            }

            var propValue;
            for(var propName in activeVoters) {
                propValue = voters[propName]
                console.log(propName, propValue);
            }

            var propValue;
            for(var propName in voters) {
                propValue = voters[propName]
                console.log(propName, propValue);
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<|endoftext|>