<commit_before>angular.module('myApp').directive('demo', ['$routeParams', function ($routeParams) {
    return {
        restrict: 'E',
        templateUrl: 'components/demo/demo.html',

        scope: {},
        controller: function ($scope, $log, $rootScope, $location, $http, $timeout) {

            $scope.backendErrors = false;

            var container = $("#flot-moving-line-chart");

            var maximumPoints = 300;

            $scope.fitnessPlot = {};
            $scope.fitnessPlot.ys = [];
            for (var i = 0; i < maximumPoints; i++) {
                $scope.fitnessPlot.ys.push(0);
            }

            // zip the generated y values with the x values

            var res = [];
            for (var i = 0; i < $scope.fitnessPlot.ys.length; i++) {
                res.push([i, $scope.fitnessPlot.ys[i]])
            }

            $scope.fitnessPlot.series = [{
                data: res,
                lines: {
                    fill: true
                }
            }];

            //

            $scope.fitnessPlot.plot = $.plot(container, $scope.fitnessPlot.series, {
                grid: {
                    borderWidth: 1,
                    minBorderMargin: 20,
                    labelMargin: 10,
                    backgroundColor: {
                        colors: ["#fff", "#e4f4f4"]
                    },
                    margin: {
                        top: 8,
                        bottom: 20,
                        left: 20
                    },
                    markings: function (axes) {
                        var markings = [];
                        var xaxis = axes.xaxis;
                        for (var x = Math.floor(xaxis.min); x < xaxis.max; x += xaxis.tickSize * 2) {
                            markings.push({
                                xaxis: {
                                    from: x,
                                    to: x + xaxis.tickSize
                                },
                                color: "rgba(232, 232, 255, 0.2)"
                            });
                        }
                        return markings;
                    }
                },
                xaxis: {
                    tickFormatter: function () {
                        return "";
                    }
                },
                yaxis: {
                    min: 0,
                    max: 25000
                },
                legend: {
                    show: true
                }
            });

            $scope.algorithmStillRunning = false;
            $scope.settings = {};
            $scope.settings.selectedOption = {
                id: 1,
                name: "low",
                settings: {
                    "mutationProbability": 25,
                    "populationSize": 500,
                    "nrOfGenerations": 5000,
                    "fitnessThreshold": 11000,
                    "parentSelectionSize": 60,
                    "parentPoolSize": 100
                }
            };
            $scope.settings.availableOptions = [
                {
                    id: 0,
                    name: "none",
                    settings: $scope.settings.selectedOption.settings
                },
                {
                    id: 1,
                    name: "low",
                    settings: {
                        "mutationProbability": 25,
                        "populationSize": 500,
                        "nrOfGenerations": 5000,
                        "fitnessThreshold": 11000,
                        "parentSelectionSize": 60,
                        "parentPoolSize": 100
                    }
                },
                {
                    id: 2,
                    name: "medium",
                    settings: {
                        "mutationProbability": 50,
                        "populationSize": 75,
                        "nrOfGenerations": 10000,
                        "fitnessThreshold": 11000,
                        "parentSelectionSize": 30,
                        "parentPoolSize": 50
                    }
                },
                {
                    id: 3,
                    name: "high",
                    settings: {
                        "mutationProbability": 90,
                        "populationSize": 1000,
                        "nrOfGenerations": 20000,
                        "fitnessThreshold": 11000,
                        "parentSelectionSize": 6,
                        "parentPoolSize": 10
                    }
                }
            ];
            $scope.setPresetToNone = function () {
                $scope.settings.selectedOption = {
                    id: 0,
                    name: "none",
                    settings: $scope.settings.selectedOption.settings
                }
            },

                $scope.run = {"generation": 0, "bestFitness": 0};

            function setNewValues(response) {
                $scope.areas = response.data.route;
                $scope.run.bestFitness = response.data.fitness;
                $scope.run.generation = response.data.generation;

                $scope.fitnessPlot.ys = $scope.fitnessPlot.ys.slice(1);
                $scope.fitnessPlot.ys.push($scope.run.bestFitness);

                // zip the generated y values with the x values

                var res = [];
                for (var i = 0; i < $scope.fitnessPlot.ys.length; i++) {
                    res.push([i, $scope.fitnessPlot.ys[i]])
                }

                $scope.fitnessPlot.series[0].data = res;
                $scope.fitnessPlot.plot.setData($scope.fitnessPlot.series);
                $scope.fitnessPlot.plot.draw();
            }

            $scope.getBest = function () {
                return $http.get('http://localhost:8080/api/currentBest').then(function (response) {
                    setNewValues(response);
                }, function (response) {
                    $scope.algorithmStillRunning = false;

                    // try to get the last rating
                    $http.get('http://localhost:8080/api/latestBest').then(function (response) {
                        setNewValues(response);
                    });
                });
            };

            $scope.start = function () {
                var body = $scope.settings.selectedOption.settings;

                $scope.startAlgorithm(body).then(function () {
                    $scope.algorithmStillRunning = true;
                    $scope.updateCurrentBest();
                });

            };

            $scope.stop = function () {
                $http.post('http://localhost:8080/api/stopAlgorithm').
                    then(function (response) {
                        // we're good!
                    });
            }

            $scope.updateCurrentBest = function () {
                if ($scope.algorithmStillRunning) {
                    $scope.getBest().then(function (response) {
                        var route = $scope.updateRoute();

                        if ($scope.flightPath) {
                            $scope.flightPath.setMap(null);
                        }

                        $scope.flightPath = new google.maps.Polyline({
                            path: route,
                            geodesic: true,
                            strokeColor: '#FFFF66',
                            strokeOpacity: 1.0,
                            strokeWeight: 2
                        });

                        $scope.flightPath.setMap($scope.map);

                        $timeout($scope.updateCurrentBest, 250);
                    });
                }
            };

            $scope.updateRoute = function () {
                var route = [];
                for (var j = 0; j < $scope.areas.length; j++) {

                    var city = $scope.areas[j];

                    city.location = new google.maps.LatLng(city.latitude, city.longitude);
                    var marker = new google.maps.Marker({
                        position: city.location,
                        map: $scope.map,
                        title: city.name,

                    });

                    route.push({lat: city.latitude, lng: city.longitude})
                }
                return route;
            }

            $scope.startAlgorithm = function (body) {
                return $http.post('http://localhost:8080/api/startAlgorithm', body).
                    then(function (response) {
                        $scope.backendErrors = false;
                        return response;
                    }, function (response) {
                        if (response.status === -1) {
                            $scope.backendErrors = true;
                        }
                    });
            }

            $scope.stillRunning = function () {
                return $http.get('http://localhost:8080/api/stillRunning').then(function (response) {
                    return response.data;
                });
            };

            $scope.initialize = function () {
                $scope.backendErrors = false;
                if ($scope.algorithmStillRunning) {
                    $scope.stopAlgorithm;
                }
                $scope.algorithmStillRunning = false;
                $scope.run = {"generation": 0, "bestFitness": 0};
                var mapOptions = {
                    center: new google.maps.LatLng(50.521401, 9.623885),
                    zoom: 5,
                    mapTypeId: google.maps.MapTypeId.SATELLITE
                };
                $scope.map = new google.maps.Map(document.getElementById("map-canvas"),
                    mapOptions);

                $scope.fitnessPlot.ys = [];
                for (var i = 0; i < maximumPoints; i++) {
                    $scope.fitnessPlot.ys.push(0);
                }

                // zip the generated y values with the x values

                var res = [];
                for (var i = 0; i < $scope.fitnessPlot.ys.length; i++) {
                    res.push([i, $scope.fitnessPlot.ys[i]])
                }
                $scope.fitnessPlot.series[0].data = res;
                $scope.fitnessPlot.plot.setData($scope.fitnessPlot.series);
                $scope.fitnessPlot.plot.draw();

                return $http.get('http://localhost:8080/api/getCities').then(function (response) {
                    $scope.areas = response.data;
                    $scope.updateRoute();
                });

            };
            google.maps.event.addDomListener(window, 'load', $scope.initialize);
            $scope.initialize();
        }
    };
}]);<commit_msg>parallling: Improved frontend robustness regarding empty data<commit_after>angular.module('myApp').directive('demo', ['$routeParams', function ($routeParams) {
    return {
        restrict: 'E',
        templateUrl: 'components/demo/demo.html',

        scope: {},
        controller: function ($scope, $log, $rootScope, $location, $http, $timeout) {

            $scope.backendErrors = false;

            var container = $("#flot-moving-line-chart");

            var maximumPoints = 300;

            $scope.fitnessPlot = {};
            $scope.fitnessPlot.ys = [];
            for (var i = 0; i < maximumPoints; i++) {
                $scope.fitnessPlot.ys.push(0);
            }

            // zip the generated y values with the x values

            var res = [];
            for (var i = 0; i < $scope.fitnessPlot.ys.length; i++) {
                res.push([i, $scope.fitnessPlot.ys[i]])
            }

            $scope.fitnessPlot.series = [{
                data: res,
                lines: {
                    fill: true
                }
            }];

            //

            $scope.fitnessPlot.plot = $.plot(container, $scope.fitnessPlot.series, {
                grid: {
                    borderWidth: 1,
                    minBorderMargin: 20,
                    labelMargin: 10,
                    backgroundColor: {
                        colors: ["#fff", "#e4f4f4"]
                    },
                    margin: {
                        top: 8,
                        bottom: 20,
                        left: 20
                    },
                    markings: function (axes) {
                        var markings = [];
                        var xaxis = axes.xaxis;
                        for (var x = Math.floor(xaxis.min); x < xaxis.max; x += xaxis.tickSize * 2) {
                            markings.push({
                                xaxis: {
                                    from: x,
                                    to: x + xaxis.tickSize
                                },
                                color: "rgba(232, 232, 255, 0.2)"
                            });
                        }
                        return markings;
                    }
                },
                xaxis: {
                    tickFormatter: function () {
                        return "";
                    }
                },
                yaxis: {
                    min: 0,
                    max: 25000
                },
                legend: {
                    show: true
                }
            });

            $scope.algorithmStillRunning = false;
            $scope.settings = {};
            $scope.settings.selectedOption = {
                id: 1,
                name: "low",
                settings: {
                    "mutationProbability": 25,
                    "populationSize": 500,
                    "nrOfGenerations": 5000,
                    "fitnessThreshold": 11000,
                    "parentSelectionSize": 60,
                    "parentPoolSize": 100
                }
            };
            $scope.settings.availableOptions = [
                {
                    id: 0,
                    name: "none",
                    settings: $scope.settings.selectedOption.settings
                },
                {
                    id: 1,
                    name: "low",
                    settings: {
                        "mutationProbability": 25,
                        "populationSize": 500,
                        "nrOfGenerations": 5000,
                        "fitnessThreshold": 11000,
                        "parentSelectionSize": 60,
                        "parentPoolSize": 100
                    }
                },
                {
                    id: 2,
                    name: "medium",
                    settings: {
                        "mutationProbability": 50,
                        "populationSize": 75,
                        "nrOfGenerations": 10000,
                        "fitnessThreshold": 11000,
                        "parentSelectionSize": 30,
                        "parentPoolSize": 50
                    }
                },
                {
                    id: 3,
                    name: "high",
                    settings: {
                        "mutationProbability": 90,
                        "populationSize": 1000,
                        "nrOfGenerations": 20000,
                        "fitnessThreshold": 11000,
                        "parentSelectionSize": 6,
                        "parentPoolSize": 10
                    }
                }
            ];
            $scope.setPresetToNone = function () {
                $scope.settings.selectedOption = {
                    id: 0,
                    name: "none",
                    settings: $scope.settings.selectedOption.settings
                }
            },

                $scope.run = {"generation": 0, "bestFitness": 0};

            function setNewValues(response) {
                if(!response.data) {
                    return;
                }

                $scope.areas = response.data.route;
                $scope.run.bestFitness = response.data.fitness;
                $scope.run.generation = response.data.generation;

                $scope.fitnessPlot.ys = $scope.fitnessPlot.ys.slice(1);
                $scope.fitnessPlot.ys.push($scope.run.bestFitness);

                // zip the generated y values with the x values

                var res = [];
                for (var i = 0; i < $scope.fitnessPlot.ys.length; i++) {
                    res.push([i, $scope.fitnessPlot.ys[i]])
                }

                $scope.fitnessPlot.series[0].data = res;
                $scope.fitnessPlot.plot.setData($scope.fitnessPlot.series);
                $scope.fitnessPlot.plot.draw();
            }

            $scope.getBest = function () {
                return $http.get('http://localhost:8080/api/currentBest').then(function (response) {
                    setNewValues(response);
                }, function (response) {
                    $scope.algorithmStillRunning = false;

                    // try to get the last rating
                    $http.get('http://localhost:8080/api/latestBest').then(function (response) {
                        setNewValues(response);
                    });
                });
            };

            $scope.start = function () {
                var body = $scope.settings.selectedOption.settings;

                $scope.startAlgorithm(body).then(function () {
                    $scope.algorithmStillRunning = true;
                    $scope.updateCurrentBest();
                });

            };

            $scope.stop = function () {
                $http.post('http://localhost:8080/api/stopAlgorithm').
                    then(function (response) {
                        // we're good!
                    });
            }

            $scope.updateCurrentBest = function () {
                if ($scope.algorithmStillRunning) {
                    $scope.getBest().then(function (response) {
                        var route = $scope.updateRoute();

                        if ($scope.flightPath) {
                            $scope.flightPath.setMap(null);
                        }

                        $scope.flightPath = new google.maps.Polyline({
                            path: route,
                            geodesic: true,
                            strokeColor: '#FFFF66',
                            strokeOpacity: 1.0,
                            strokeWeight: 2
                        });

                        $scope.flightPath.setMap($scope.map);

                        $timeout($scope.updateCurrentBest, 250);
                    });
                }
            };

            $scope.updateRoute = function () {
                var route = [];
                for (var j = 0; j < $scope.areas.length; j++) {

                    var city = $scope.areas[j];

                    city.location = new google.maps.LatLng(city.latitude, city.longitude);
                    var marker = new google.maps.Marker({
                        position: city.location,
                        map: $scope.map,
                        title: city.name,

                    });

                    route.push({lat: city.latitude, lng: city.longitude})
                }
                return route;
            }

            $scope.startAlgorithm = function (body) {
                return $http.post('http://localhost:8080/api/startAlgorithm', body).
                    then(function (response) {
                        $scope.backendErrors = false;
                        return response;
                    }, function (response) {
                        if (response.status === -1) {
                            $scope.backendErrors = true;
                        }
                    });
            }

            $scope.stillRunning = function () {
                return $http.get('http://localhost:8080/api/stillRunning').then(function (response) {
                    return response.data;
                });
            };

            $scope.initialize = function () {
                $scope.backendErrors = false;
                if ($scope.algorithmStillRunning) {
                    $scope.stopAlgorithm;
                }
                $scope.algorithmStillRunning = false;
                $scope.run = {"generation": 0, "bestFitness": 0};
                var mapOptions = {
                    center: new google.maps.LatLng(50.521401, 9.623885),
                    zoom: 5,
                    mapTypeId: google.maps.MapTypeId.SATELLITE
                };
                $scope.map = new google.maps.Map(document.getElementById("map-canvas"),
                    mapOptions);

                $scope.fitnessPlot.ys = [];
                for (var i = 0; i < maximumPoints; i++) {
                    $scope.fitnessPlot.ys.push(0);
                }

                // zip the generated y values with the x values

                var res = [];
                for (var i = 0; i < $scope.fitnessPlot.ys.length; i++) {
                    res.push([i, $scope.fitnessPlot.ys[i]])
                }
                $scope.fitnessPlot.series[0].data = res;
                $scope.fitnessPlot.plot.setData($scope.fitnessPlot.series);
                $scope.fitnessPlot.plot.draw();

                return $http.get('http://localhost:8080/api/getCities').then(function (response) {
                    $scope.areas = response.data;
                    $scope.updateRoute();
                });

            };
            google.maps.event.addDomListener(window, 'load', $scope.initialize);
            $scope.initialize();
        }
    };
}]);<|endoftext|>


<commit_before>export const nl = {
  auth: {
    login: {
      connectingToGitHub: 'Verbinding maken met GitHub ...', // google translate
      preparingGitPoint: 'GitPoint voorbereiden ...', // google translate
      cancel: 'ANNULEER', // google translate
      welcomeTitle: 'Welkom bij GitPoint',
      welcomeMessage: 'De meest complete GitHub client die geen geld kost',
      notificationsTitle: 'Beheer notificaties',
      notificationsMessage:
        'Bekijk en beheer al je ongelezen en deelnemende notificaties',
      reposTitle: 'Repositories en Gebruikers',
      reposMessage:
        'Verkrijg snel repoisitory, gebruiker en organisatie informatie',
      issuesTitle: 'Issues en Pull Requests',
      issuesMessage: 'Neem deel aan conversaties, merge pull requests en meer',
      signInButton: 'AANMELDEN',
    },
    welcome: {
      welcomeTitle: 'Welbij bij GitPoint',
    },
    events: {
      welcomeMessage:
        'Welkom! Dit is je nieuws tijdlijn - dit helpt je up to date te blijven bij repositories en gebruikers die je volgt.',
      commitCommentEvent: 'heeft een reactie geplaatst op commit',
      createEvent: '{{object}} aangemaakt',
      deleteEvent: '{{object}} verwijderd',
      issueCommentEvent: '{{action}} op {{type}}',
      issueEditedEvent: 'heeft een opmerking {{action}} op {{type}}',
      issueRemovedEvent: 'heeft een opmerking {{action}} bij {{type}}',
      issuesEvent: '{{action}} issue',
      publicEvent: {
        action: 'heeft',
        connector: 'openbaar gemaakt',
      },
      pullRequestEvent: 'heeft pull request {{action}}',
      pullRequestReviewEvent: 'pull request review {{action}} ',
      pullRequestReviewCommentEvent: '{{action}} op pull request',
      pullRequestReviewEditedEvent:
        'heeft een opmerking {{action}} op pull request',
      pullRequestReviewDeletedEvent:
        'heeft een opmerking {{action}} op pull request',
      releaseEvent: '{{action}} release',
      atConnector: 'op',
      toConnector: 'bij',
      types: {
        pullRequest: 'pull request',
        issue: 'issue',
      },
      objects: {
        repository: 'repository',
        branch: 'branch',
        tag: 'tag',
      },
      actions: {
        added: 'toegevoegd',
        created: 'aangemaakt',
        edited: 'bijgewerkt',
        deleted: 'verwijderd',
        assigned: 'toegewezen',
        unassigned: 'niet-toegewezen',
        labeled: 'labeled',
        unlabeled: 'unlabeled',
        opened: 'geopend',
        milestoned: 'milestoned',
        demilestoned: 'demilestoned',
        closed: 'gesloten',
        reopened: 'heropend',
        review_requested: 'review aangevraagd',
        review_request_removed: 'review aangevraag verwijderd',
        submitted: 'ingediend',
        dismissed: 'ontslagen',
        published: 'gepubliceerd',
        publicized: 'publicized',
        privatized: 'privatized',
        starred: 'heeft een ster gegeven aan',
        pushedTo: 'pushed to',
        forked: 'forked',
        commented: 'heeft een opmerking gemaakt',
        removed: 'verwijderd',
      },
    },
    profile: {
      orgsRequestApprovalTop: 'Kan je niet al je organisaites zien?',
      orgsRequestApprovalBottom: 'Je moet misschien om toestemming vragen.',
      codePushCheck: 'Controleer op updates',
      codePushChecking: 'Controleren als er updates zijn...',
      codePushUpdated: 'App is bijgewerkt',
      codePushAvailable: 'Update beschikbaar!',
      codePushNotApplicable: 'Niet beschikbaar in debug mode',
    },
    userOptions: {
      donate: 'Doe een donatie',
      title: 'Opties',
      language: 'Taal',
      privacyPolicy: 'Privacybeleid',
      signOut: 'Uitloggen',
    },
    privacyPolicy: {
      title: 'Privacybeleid',
      effectiveDate: 'Laats ge-updated op: July 15, 2017',
      introduction:
        'We zijn blij dat je voor GitPoint hebt gekozen. Dit privacybeleid is hier om u te informeren over wat wij doen - en niet doen - met de gegevens van onze gebruikers.',
      userDataTitle: 'GEBRUIKERS INFORMATIE',
      userData1:
        'We doen niets met uw GitHub informatie. Na de authenticatie wordt de OAuth-token van de gebruiker rechtstreeks op hun apparaatopslag opgeslagen. Het is niet mogelijk voor ons om die informatie te verkrijgen. Wij zien nooit de toegangscode van een gebruiker en slaan het ook niet op.',
      userData2:
        'Dit betekent dat wij op geen enkele wijze de GitHub-gegevens van een gebruiker ooit kunnen inzien, gebruiken of delen. Als privégegevens ooit zichtbaar worden, zullen we het niet opnemen of bekijken. Als het per ongeluk wordt opgenomen, zullen wij het onmiddellijk verwijderen met veilige verwijderingsmethoden. Nogmaals, wij hebben authentificatie speciaal ingesteld zodat dit nooit gebeurt.',
      analyticsInfoTitle: 'ANALYTICS INFORMATIE',
      analyticsInfo1:
        'We gebruiken op dit moment Google Analytics en iTunes App Analytics om ons te helpen met het meten van verkeer en gebruikstendensen voor het GitPoint. Deze tools verzamelen informatie die door uw apparaat wordt verzonden, inclusief apparaat- en platformversie, regio en verwijzer. Deze informatie kan niet worden gebruikt om een bepaalde individuele gebruiker te identificeren en er worden geen persoonlijke gegevens geëxtraheerd.',
      analyticsInfo2:
        'Als wij een ander platform van derden opnemen om problemen, fouten of meer analytische informatie te verzamelen, zullen wij ervoor zorgen dat de gebruikersgegevens geanonimiseerd en gecodeerd zijn.',
      openSourceTitle: 'OPEN SOURCE',
      openSource1:
        'GitPoint is open source en de geschiedenis van de bijdragen aan het platform is altijd zichtbaar voor het publiek.',
      openSource2:
        'Bij elke bijdrage aan de app wordt er een code review uitgevoerd om te voorkomen dat iemand schadelijke codes toevoegd.',
      contactTitle: 'CONTACT',
      contact1:
        'Bedankt voor het lezen van ons privacybeleid. Wij hopen dat u het leuk vindt om GitPoint te gebruiken net zoals wij het leuk vinden om het te bouwen.',
      contact2:
        'Als u vragen heeft over dit Privacybeleid of GitPoint in het algemeen, gelieve een probleem in de',
      contactLink: 'GitPoint repository',
    },
  },
  notifications: {
    main: {
      unread: 'ongelezen',
      participating: 'deelnemend',
      all: 'Alles',
      unreadButton: 'Ongelezen',
      participatingButton: 'Deelnemend',
      allButton: 'Alles',
      retrievingMessage: 'Notificaties ophalen',
      noneMessage: 'Je hebt geen notificaties met dit type',
      markAllAsRead: 'Alles als gelezen markeren', // google translate
    },
  },
  search: {
    main: {
      repositoryButton: 'Repositories',
      userButton: 'Gebruikers',
      searchingMessage: 'Zoeken naar {{query}}',
      searchMessage: 'Zoeken naar {{type}}',
      repository: 'repository',
      user: 'gebruiker',
    },
  },
  user: {
    profile: {
      userActions: 'Gebruiker Acties',
      unfollow: 'Ontvolgen',
      follow: 'Volgen',
    },
    repositoryList: {
      title: 'Repositories',
    },
    followers: {
      title: 'Volgers',
      text: 'Volgers',
      followsYou: 'Volgt jou',
    },
    following: {
      title: 'Volgen',
      text: 'Volgen',
      followingYou: 'Volgen',
    },
  },
  repository: {
    main: {
      shareRepositoryTitle: 'Delen {{repoName}}',
      shareRepositoryMessage: 'Bekijk {{repoName}} op GitHub. {{repoUrl}}',
      repoActions: 'Repository Acties',
      forkAction: 'Fork',
      starAction: 'Star',
      unstarAction: 'Unstar',
      shareAction: 'Delen',
      unwatchAction: 'Unwatch',
      watchAction: 'Watch',
      ownerTitle: 'EIGENAAR',
      contributorsTitle: 'MEDEWERKERS',
      noContributorsMessage: 'Geen medewerkers gevonden',
      sourceTitle: 'BRON',
      readMe: 'README',
      viewSource: 'Bekijk Code',
      issuesTitle: 'ISSUES',
      noIssuesMessage: 'Geen issues',
      noOpenIssuesMessage: 'Geen open issues',
      viewAllButton: 'Bekijk Alles',
      newIssueButton: 'Nieuw Issue',
      pullRequestTitle: 'PULL REQUESTS',
      noPullRequestsMessage: 'Geen pull requests',
      noOpenPullRequestsMessage: 'Geen open pull requests',
      starsTitle: 'Stars',
      forksTitle: 'Forks',
      forkedFromMessage: 'forked from',
    },
    codeList: {
      title: 'Code',
    },
    issueList: {
      title: 'Issues',
      openButton: 'Open',
      closedButton: 'Gesloten',
      searchingMessage: 'Zoeken naar {{query}}',
      noOpenIssues: 'Geen open issues gevonden!',
      noClosedIssues: 'Geen gesloten issues gevonden!',
    },
    pullList: {
      title: 'Pull Requests',
      openButton: 'Open',
      closedButton: 'Gesloten',
      searchingMessage: 'Zoeken naar {{query}}',
      noOpenPulls: 'Geen open pull requests gevonden!',
      noClosedPulls: 'Geen gesloten pull requests gevonden!',
    },
    pullDiff: {
      title: 'Diff',
      numFilesChanged: '{{numFilesChanged}} files',
      new: 'NIEW',
      deleted: 'VERWIJDERD',
      fileRenamed: 'Bestand hernoemd zonder veranderingen',
    },
    readMe: {
      readMeActions: 'README Actions',
    },
  },
  organization: {
    main: {
      membersTitle: 'LEDEN',
      descriptionTitle: 'BESCHRIJVING',
    },
    organizationActions: 'Organization Actions',
  },
  issue: {
    settings: {
      title: 'Instellingen',
      pullRequestType: 'Pull Request',
      issueType: 'Issue',
      applyLabelButton: 'Voeg label toe',
      noneMessage: 'geen',
      labelsTitle: 'LABELS',
      assignYourselfButton: 'Assign jezelf',
      assigneesTitle: 'ASSIGNEES',
      actionsTitle: 'ACTIES',
      unlockIssue: 'Ontgrendel {{issueType}}',
      lockIssue: 'Vergrendel {{issueType}}',
      closeIssue: 'Sluit {{issueType}}',
      reopenIssue: 'Heropen {{issueType}}',
      areYouSurePrompt: 'Weet je het zeker?',
      applyLabelTitle: 'Voeg een label toe aan deze issue',
    },
    comment: {
      commentActions: 'Commentaaracties', // google translate
      editCommentTitle: 'Bewerk commentaar', // google translate
      editAction: 'Bewerk', // google translate
      deleteAction: 'Verwijder', // google translate
    },
    main: {
      assignees: 'Assignees',
      mergeButton: 'Merge Pull Request',
      noDescription: 'Niet voorzien van een beschrijving.',
      lockedCommentInput: 'Gesloten maar je kan nog opmerkingen maken...',
      commentInput: 'Plaats opmerking...',
      lockedIssue: 'Issue is gesloten',
      states: {
        open: 'Open',
        closed: 'Gesloten',
        merged: 'Merged',
      },
      screenTitles: {
        issue: 'Issue',
        pullRequest: 'Pull Request',
      },
      openIssueSubTitle: '#{{number}} opened {{time}} ago by {{user}}',
      closedIssueSubTitle: '#{{number}} by {{user}} was closed {{time}} ago',
      issueActions: 'Issue Actions',
    },
    newIssue: {
      title: 'Niew Issue',
      missingTitleAlert: 'Een titel is verplicht!',
      issueTitle: 'Issue title',
      writeATitle: 'Schrijf een titel voor je issue hier',
      issueComment: 'Issue omschrijving',
      writeAComment: 'Schrijf een omschrijving voor je issue hier',
    },
    pullMerge: {
      title: 'Merge Pull Request',
      createMergeCommit: 'Maak een merge commit',
      squashAndMerge: 'Squash en merge',
      merge: 'merge',
      squash: 'squash',
      missingTitleAlert: 'Een commit titel is verplicht!',
      commitTitle: 'Commit Title',
      writeATitle: 'Schrijf een titel voor je commit hier',
      commitMessage: 'Commit samenvatting',
      writeAMessage: 'Schrijf een samenvatting voor je commit hier',
      mergeType: 'Merge Type',
      changeMergeType: 'Verander Merge Type',
    },
  },
  common: {
    bio: 'BIO',
    stars: 'Sterren',
    orgs: 'ORGANISATIES',
    noOrgsMessage: 'Geen organizations',
    info: 'INFO',
    company: 'Bedrijf',
    location: 'Locatie',
    email: 'Email',
    website: 'Website',
    repositories: 'Repositories',
    cancel: 'Annuleren',
    yes: 'Ja',
    ok: 'OKE',
    submit: 'Versturen',
    relativeTime: {
      past: '%s',
      s: '%ds',
      m: '%dm',
      mm: '%dm',
      h: '%dh',
      hh: '%dh',
      d: '%dd',
      dd: '%dd',
      M: '%dmo',
      MM: '%dmo',
      y: '%dy',
      yy: '%dy',
    },
    abbreviations: {
      thousand: 'k',
    },
    openInBrowser: 'Open in Browser',
  },
};
<commit_msg>Update nl.js (#451)<commit_after>export const nl = {
  auth: {
    login: {
      connectingToGitHub: 'Verbinding maken met GitHub ...', // google translate
      preparingGitPoint: 'GitPoint voorbereiden ...', // google translate
      cancel: 'ANNULEER', // google translate
      welcomeTitle: 'Welkom bij GitPoint',
      welcomeMessage: 'De meest complete GitHub client die geen geld kost',
      notificationsTitle: 'Beheer notificaties',
      notificationsMessage:
        'Bekijk en beheer al uw ongelezen en deelnemende notificaties',
      reposTitle: 'Repositories en Gebruikers',
      reposMessage:
        'Verkrijg snel de informatie van uw repositories, gebruikers en organisaties',
      issuesTitle: 'Issues en Pull Requests',
      issuesMessage: 'Neem deel aan conversaties, merge pull requests en meer',
      signInButton: 'AANMELDEN',
    },
    welcome: {
      welcomeTitle: 'Welkom bij GitPoint',
    },
    events: {
      welcomeMessage:
        'Welkom! Dit is uw nieuwe tijdlijn - dit helpt u up to date te blijven bij repositories en gebruikers die je volgt.',
      commitCommentEvent: 'heeft een reactie geplaatst op commit',
      createEvent: '{{object}} aangemaakt',
      deleteEvent: '{{object}} verwijderd',
      issueCommentEvent: '{{action}} op {{type}}',
      issueEditedEvent: 'heeft een opmerking {{action}} op {{type}}',
      issueRemovedEvent: 'heeft een opmerking {{action}} bij {{type}}',
      issuesEvent: '{{action}} issue',
      publicEvent: {
        action: 'heeft',
        connector: 'openbaar gemaakt',
      },
      pullRequestEvent: 'heeft pull request {{action}}',
      pullRequestReviewEvent: 'pull request review {{action}} ',
      pullRequestReviewCommentEvent: '{{action}} op pull request',
      pullRequestReviewEditedEvent:
        'heeft een opmerking {{action}} op pull request',
      pullRequestReviewDeletedEvent:
        'heeft een opmerking {{action}} op pull request',
      releaseEvent: '{{action}} release',
      atConnector: 'op',
      toConnector: 'bij',
      types: {
        pullRequest: 'pull request',
        issue: 'issue',
      },
      objects: {
        repository: 'repository',
        branch: 'branch',
        tag: 'tag',
      },
      actions: {
        added: 'toegevoegd',
        created: 'aangemaakt',
        edited: 'bijgewerkt',
        deleted: 'verwijderd',
        assigned: 'toegewezen',
        unassigned: 'niet-toegewezen',
        labeled: 'labeled',
        unlabeled: 'unlabeled',
        opened: 'geopend',
        milestoned: 'milestoned',
        demilestoned: 'demilestoned',
        closed: 'gesloten',
        reopened: 'heropend',
        review_requested: 'review aangevraagd',
        review_request_removed: 'review aangevraag verwijderd',
        submitted: 'ingediend',
        dismissed: 'ontslagen',
        published: 'gepubliceerd',
        publicized: 'publiek gemaakt',
        privatized: 'prive gemaakt',
        starred: 'heeft een ster gegeven aan',
        pushedTo: 'pushed to',
        forked: 'forked',
        commented: 'heeft een opmerking gemaakt',
        removed: 'verwijderd',
      },
    },
    profile: {
      orgsRequestApprovalTop: 'Kunt u niet al uw organisaites zien?',
      orgsRequestApprovalBottom: 'U moet misschien om toestemming vragen.',
      codePushCheck: 'Controleer op updates',
      codePushChecking: 'Controleren op updates...',
      codePushUpdated: 'App is bijgewerkt',
      codePushAvailable: 'Update beschikbaar!',
      codePushNotApplicable: 'Niet beschikbaar in debug',
    },
    userOptions: {
      donate: 'Doneren',
      title: 'Opties',
      language: 'Taal',
      privacyPolicy: 'Privacybeleid',
      signOut: 'Uitloggen',
    },
    privacyPolicy: {
      title: 'Privacybeleid',
      effectiveDate: 'Laatst ge-updated op: 15 Juli 2017',
      introduction:
        'We zijn blij dat u voor GitPoint heeft gekozen. Dit privacybeleid is hier om u te informeren over wat wij doen - en niet doen - met de gegevens van onze gebruikers.',
      userDataTitle: 'GEBRUIKERS INFORMATIE',
      userData1:
        'We doen niets met uw GitHub informatie. Na de authenticatie wordt uw OAuth-token rechtstreeks op uw apparaatopslag opgeslagen. Het is niet mogelijk voor ons om die informatie te verkrijgen. Wij zien nooit de toegangscode van een gebruiker en slaan het ook niet op.',
      userData2:
        'Dit betekent dat wij op geen enkele wijze de GitHub-gegevens van een gebruiker kunnen inzien, gebruiken of delen. Als privégegevens ooit zichtbaar worden, zullen we het niet opnemen of bekijken. Als het per ongeluk wordt opgenomen, zullen wij het onmiddellijk verwijderen met veilige verwijderingsmethoden. Nogmaals, wij hebben authentificatie speciaal ingesteld zodat dit nooit zou gebeuren.',
      analyticsInfoTitle: 'ANALYTICS INFORMATIE',
      analyticsInfo1:
        'We gebruiken op dit moment Google Analytics en iTunes App Analytics om ons te helpen met het meten van verkeer en gebruikstendensen van GitPoint. Deze tools verzamelen informatie die door uw apparaat wordt verzonden, inclusief apparaat- en platformversie, regio en verwijzer. Deze informatie kan niet worden gebruikt om een bepaalde individuele gebruiker te identificeren en er worden geen persoonlijke gegevens geëxtraheerd.',
      analyticsInfo2:
        'Als wij een ander platform van derden opnemen om problemen, fouten of meer analytische informatie te verzamelen, zullen wij ervoor zorgen dat de gebruikersgegevens geanonimiseerd en gecodeerd zijn.',
      openSourceTitle: 'OPEN SOURCE',
      openSource1:
        'GitPoint is open source en de geschiedenis van de bijdragen aan het platform is altijd zichtbaar voor het publiek.',
      openSource2:
        'Bij elke bijdrage aan de app wordt er een code review uitgevoerd om te voorkomen dat iemand schadelijke codes toevoegd.',
      contactTitle: 'CONTACT',
      contact1:
        'Bedankt voor het lezen van ons privacybeleid. Wij hopen dat u het leuk vindt om GitPoint te gebruiken net zoals wij het leuk vinden om het te bouwen.',
      contact2:
        'Als u vragen heeft over dit Privacybeleid of GitPoint in het algemeen, gelieve een probleem in de',
      contactLink: 'GitPoint repository ',
    },
  },
  notifications: {
    main: {
      unread: 'ongelezen',
      participating: 'deelnemend',
      all: 'Alles',
      unreadButton: 'Ongelezen',
      participatingButton: 'Deelnemend',
      allButton: 'Alles',
      retrievingMessage: 'Notificaties ophalen',
      noneMessage: 'Je hebt geen notificaties van dit type',
      markAllAsRead: 'Alles markeren als gelezen',
    },
  },
  search: {
    main: {
      repositoryButton: 'Repositories',
      userButton: 'Gebruikers',
      searchingMessage: 'Zoeken naar {{query}}',
      searchMessage: 'Zoeken naar {{type}}',
      repository: 'repository',
      user: 'gebruiker',
    },
  },
  user: {
    profile: {
      userActions: 'Gebruiker Acties',
      unfollow: 'Ontvolgen',
      follow: 'Volgen',
    },
    repositoryList: {
      title: 'Repositories',
    },
    followers: {
      title: 'Volgers',
      text: 'Volgers',
      followsYou: 'Volgt u',
    },
    following: {
      title: 'Volgen',
      text: 'Volgen',
      followingYou: 'Volgen',
    },
  },
  repository: {
    main: {
      shareRepositoryTitle: 'Deel {{repoName}}',
      shareRepositoryMessage: 'Bekijk {{repoName}} op GitHub. {{repoUrl}}',
      repoActions: 'Repository Acties',
      forkAction: 'Fork',
      starAction: 'Ster',
      unstarAction: 'Ster verwijderen',
      shareAction: 'Delen',
      unwatchAction: 'Unwatch',
      watchAction: 'Bekijken',
      ownerTitle: 'EIGENAAR',
      contributorsTitle: 'MEDEWERKERS',
      noContributorsMessage: 'Geen medewerkers',
      sourceTitle: 'BRON',
      readMe: 'README',
      viewSource: 'Bekijk Code',
      issuesTitle: 'ISSUES',
      noIssuesMessage: 'Geen issues',
      noOpenIssuesMessage: 'Geen open issues',
      viewAllButton: 'Bekijk Alles',
      newIssueButton: 'Nieuw Issue',
      pullRequestTitle: 'PULL REQUESTS',
      noPullRequestsMessage: 'Geen pull requests',
      noOpenPullRequestsMessage: 'Geen open pull requests',
      starsTitle: 'Sterren',
      forksTitle: 'Forks',
      forkedFromMessage: 'forked from',
    },
    codeList: {
      title: 'Code',
    },
    issueList: {
      title: 'Issues',
      openButton: 'Open',
      closedButton: 'Gesloten',
      searchingMessage: 'Zoeken naar {{query}}',
      noOpenIssues: 'Geen open issues gevonden!',
      noClosedIssues: 'Geen gesloten issues!',
    },
    pullList: {
      title: 'Pull Requests',
      openButton: 'Open',
      closedButton: 'Gesloten',
      searchingMessage: 'Zoeken naar {{query}}',
      noOpenPulls: 'Geen open pull requests gevonden!',
      noClosedPulls: 'Geen gesloten pull requests gevonden!',
    },
    pullDiff: {
      title: 'Diff',
      numFilesChanged: '{{numFilesChanged}} bestanden',
      new: 'NIEUW',
      deleted: 'VERWIJDERD',
      fileRenamed: 'Bestand hernoemd zonder veranderingen',
    },
    readMe: {
      readMeActions: 'README Acties',
    },
  },
  organization: {
    main: {
      membersTitle: 'LEDEN',
      descriptionTitle: 'BESCHRIJVING',
    },
    organizationActions: 'Organisatie Actions',
  },
  issue: {
    settings: {
      title: 'Instellingen',
      pullRequestType: 'Pull Request',
      issueType: 'Issue',
      applyLabelButton: 'Voeg label toe',
      noneMessage: 'geen',
      labelsTitle: 'LABELS',
      assignYourselfButton: 'Assign jezelf',
      assigneesTitle: 'ASSIGNEES',
      actionsTitle: 'ACTIES',
      unlockIssue: 'Ontgrendel {{issueType}}',
      lockIssue: 'Vergrendel {{issueType}}',
      closeIssue: 'Sluit {{issueType}}',
      reopenIssue: 'Heropen {{issueType}}',
      areYouSurePrompt: 'Weet u het zeker?',
      applyLabelTitle: 'Voeg een label toe aan deze issue',
    },
    comment: {
      commentActions: 'Acties voor commentaar',
      editCommentTitle: 'Bewerk commentaar',
      editAction: 'Bewerk',
      deleteAction: 'Verwijder',
    },
    main: {
      assignees: 'Assignees',
      mergeButton: 'Merge Pull Request',
      noDescription: 'Niet voorzien van een beschrijving.',
      lockedCommentInput: 'Gesloten maar u kan nog een opmerkingen maken...',
      commentInput: 'Plaats opmerking...',
      lockedIssue: 'Issue is gesloten',
      states: {
        open: 'Open',
        closed: 'Gesloten',
        merged: 'Merged',
      },
      screenTitles: {
        issue: 'Issue',
        pullRequest: 'Pull Request',
      },
      openIssueSubTitle: '#{{number}} geopend {{time}} geleden door {{user}}',
      closedIssueSubTitle: '#{{number}} door {{user}} was gesloten, {{time}} geleden',
      issueActions: 'Issue Acties',
    },
    newIssue: {
      title: 'Nieuw Issue',
      missingTitleAlert: 'Titel is verplicht!',
      issueTitle: 'Issue title',
      writeATitle: 'Schrijf de titel voor uw issue hier',
      issueComment: 'Issue omschrijving',
      writeAComment: 'Schrijf de omschrijving van uw issue hier',
    },
    pullMerge: {
      title: 'Merge Pull Request',
      createMergeCommit: 'Maak een merge commit',
      squashAndMerge: 'Squash en merge',
      merge: 'merge',
      squash: 'squash',
      missingTitleAlert: 'Een commit titel is verplicht!',
      commitTitle: 'Commit Title',
      writeATitle: 'Schrijf een titel voor uw commit hier',
      commitMessage: 'Commit samenvatting',
      writeAMessage: 'Schrijf een samenvatting voor uw commit hier',
      mergeType: 'Merge Type',
      changeMergeType: 'Verander Merge Type',
    },
  },
  common: {
    bio: 'BIO',
    stars: 'Sterren',
    orgs: 'ORGANISATIES',
    noOrgsMessage: 'Geen organisaties',
    info: 'INFO',
    company: 'Bedrijf',
    location: 'Locatie',
    email: 'Email',
    website: 'Website',
    repositories: 'Repositories',
    cancel: 'Annuleren',
    yes: 'Ja',
    ok: 'OKE',
    submit: 'Versturen',
    relativeTime: {
      past: '%s',
      s: '%ds',
      m: '%dm',
      mm: '%dm',
      h: '%dh',
      hh: '%dh',
      d: '%dd',
      dd: '%dd',
      M: '%dmo',
      MM: '%dmo',
      y: '%dy',
      yy: '%dy',
    },
    abbreviations: {
      thousand: 'k',
    },
    openInBrowser: 'Open in Browser',
  },
};
<|endoftext|>


<commit_before>const path = require('path')

module.exports = {
  input: {
    candidatesByFile: require('../../find-candidates/base').output,
    intelliByFile: require('../../intelli/extract/base').output,
    config: {
      stack: 'LESS',
      fileExtension: '.less'
    }
  },
  output: {
    "suggestionData": [
      {
        "propertyDefinitions": [
          {
            "lineNumber": 3,
            "property": "background",
            "value": "white",
            "suggestions": [
              {
                "dirPath": path.resolve("test/fixtures/pipeline/intelli/extract/has-variables.less"),
                "suggestions": [
                  {
                    "variable": "global-background",
                    "value": "#fff",
                    "lineNumber": 12
                  }
                ]
              },
              {
                "dirPath": path.resolve("test/fixtures/pipeline/intelli/extract/no-variables.less"),
                "suggestions": []
              }
            ]
          },
          {
            "lineNumber": 4,
            "property": "color",
            "value": "#fff",
            "suggestions": [
              {
                "dirPath": path.resolve("test/fixtures/pipeline/intelli/extract/has-variables.less"),
                "suggestions": []
              },
              {
                "dirPath": path.resolve("test/fixtures/pipeline/intelli/extract/no-variables.less"),
                "suggestions": []
              }
            ]
          },
          {
            "lineNumber": 8,
            "property": "color",
            "value": "#ddd",
            "suggestions": [
              {
                "dirPath": path.resolve("test/fixtures/pipeline/intelli/extract/has-variables.less"),
                "suggestions": []
              },
              {
                "dirPath": path.resolve("test/fixtures/pipeline/intelli/extract/no-variables.less"),
                "suggestions": []
              }
            ]
          }
        ],
        "filePath": path.resolve("/test/fixtures/typical-stylesheet.less")
      }
    ]
}
}
<commit_msg>Fix test fixture.<commit_after>const path = require('path')

module.exports = {
  input: {
    candidatesByFile: require('../../find-candidates/base').output,
    intelliByFile: require('../../intelli/extract/base').output,
    config: {
      stack: 'less',
      fileExtension: '.less'
    }
  },
  output: {
    "suggestionData": [
      {
        "propertyDefinitions": [
          {
            "lineNumber": 3,
            "property": "background",
            "value": "white",
            "suggestions": [
              {
                "filePath": path.resolve("test/fixtures/pipeline/intelli/extract/has-variables.less"),
                "suggestions": [
                  {
                    "variable": "global-background",
                    "value": "#fff",
                    "lineNumber": 12
                  }
                ]
              },
              {
                "filePath": path.resolve("test/fixtures/pipeline/intelli/extract/no-variables.less"),
                "suggestions": []
              }
            ]
          },
          {
            "lineNumber": 4,
            "property": "color",
            "value": "#fff",
            "suggestions": [
              {
                "filePath": path.resolve("test/fixtures/pipeline/intelli/extract/has-variables.less"),
                "suggestions": []
              },
              {
                "filePath": path.resolve("test/fixtures/pipeline/intelli/extract/no-variables.less"),
                "suggestions": []
              }
            ]
          },
          {
            "lineNumber": 8,
            "property": "color",
            "value": "#ddd",
            "suggestions": [
              {
                "filePath": path.resolve("test/fixtures/pipeline/intelli/extract/has-variables.less"),
                "suggestions": []
              },
              {
                "filePath": path.resolve("test/fixtures/pipeline/intelli/extract/no-variables.less"),
                "suggestions": []
              }
            ]
          }
        ],
        "filePath": path.resolve("/test/fixtures/typical-stylesheet.less")
      }
    ]
}
}
<|endoftext|>


<commit_before>/* @flow */

type EventBufferMode = 'idle' | 'timeout'
type FlushCallback<EventType> = (EventType[]) => void

// An event buffer.
// Needs a flush callback to be called everytime the buffer is flushed.
//
// In *idle* mode (default), the buffer will only store pushed events and
// you'll have to flush it manually.
// In *timeout* mode, the buffer flushes stored events by itself when nothing
// happens during `timeoutInMs`.
//
// The buffer will also flush automatically when switching from one mode to
// another.
//
// Right now this class is in the local/ namespace because this is where it is
// used, but it could be anywhere else since it doesn't have any dependency.
export default class EventBuffer<EventType> {
  events: EventType[]
  mode: EventBufferMode
  timeoutInMs: number
  timeout: *
  flushed: FlushCallback<EventType>

  constructor (timeoutInMs: number, flushed: FlushCallback<EventType>) {
    this.events = []
    this.mode = 'idle'
    this.timeoutInMs = timeoutInMs
    this.timeout = null
    this.flushed = flushed
  }

  push (event: EventType): void {
    this.events.push(event)
    this.shiftTimeout()
  }

  shiftTimeout (): void {
    if (this.mode === 'timeout') {
      this.clearTimeout()
      this.timeout = setTimeout(this.flush, this.timeoutInMs)
    }
  }

  clearTimeout (): void {
    if (this.timeout != null) {
      clearTimeout(this.timeout)
      delete this.timeout
    }
  }

  flush (): void {
    this.clearTimeout()
    if (this.events.length > 0) {
      const flushedEvents = this.events
      this.events = []
      this.flushed(flushedEvents)
    }
  }

  switchMode (mode: EventBufferMode): void {
    this.flush()
    this.mode = mode
  }
}
<commit_msg>Allow FlushCallback to return a result (whatever its type)<commit_after>/* @flow */

type EventBufferMode = 'idle' | 'timeout'
type FlushCallback<EventType> = (EventType[]) => any

// An event buffer.
// Needs a flush callback to be called everytime the buffer is flushed.
//
// In *idle* mode (default), the buffer will only store pushed events and
// you'll have to flush it manually.
// In *timeout* mode, the buffer flushes stored events by itself when nothing
// happens during `timeoutInMs`.
//
// The buffer will also flush automatically when switching from one mode to
// another.
//
// Right now this class is in the local/ namespace because this is where it is
// used, but it could be anywhere else since it doesn't have any dependency.
export default class EventBuffer<EventType> {
  events: EventType[]
  mode: EventBufferMode
  timeoutInMs: number
  timeout: *
  flushed: FlushCallback<EventType>

  constructor (timeoutInMs: number, flushed: FlushCallback<EventType>) {
    this.events = []
    this.mode = 'idle'
    this.timeoutInMs = timeoutInMs
    this.timeout = null
    this.flushed = flushed
  }

  push (event: EventType): void {
    this.events.push(event)
    this.shiftTimeout()
  }

  shiftTimeout (): void {
    if (this.mode === 'timeout') {
      this.clearTimeout()
      this.timeout = setTimeout(this.flush, this.timeoutInMs)
    }
  }

  clearTimeout (): void {
    if (this.timeout != null) {
      clearTimeout(this.timeout)
      delete this.timeout
    }
  }

  flush (): void {
    this.clearTimeout()
    if (this.events.length > 0) {
      const flushedEvents = this.events
      this.events = []
      this.flushed(flushedEvents)
    }
  }

  switchMode (mode: EventBufferMode): void {
    this.flush()
    this.mode = mode
  }
}
<|endoftext|>


<commit_before>// Generators - Yield Statements
// To do: make all tests pass, leave the assert lines unchanged!

describe('generator instance', () => {

  function* generator() {
    yield 'hello';
    yield 'world';
  }

  // create instance
  let genInstance = generator();

  it('should have an undefined value property after initialisation', () => {
    let value = genInstance.value;
    assert.equal(value, undefined);
  });

  it('should have value of "hello" after first next() call', () => {
    let thisStep = genInstance.next();
    let [value, done] = [thisStep.value, thisStep.done];
    assert.equal(value, 'hello');
    assert.equal(done, false);
  });

  it('should have value of "world" after second next() call', () => {
    let thisStep = genInstance.next();
    let [value, done] = [thisStep.value, thisStep.done];
    assert.equal(value, 'world');
    assert.equal(done, false);
  });

  it('done property = true after stepping past all yield statements', () => {
    let done = genInstance.next().done;
    assert.equal(done, true);
  });

});<commit_msg>break kata to make all tests red<commit_after>// Generators - Yield Statements
// To do: make all tests pass, leave the assert lines unchanged!

describe('generator instance', () => {

  function* generator() {
    yield 'hello';
    yield 'world';
  }

  // create instance
  let genInstance = generator();

  it('should have an undefined value property after initialisation', () => {
    let value = genInstance;
    assert.equal(value, undefined);
  });

  it('should have value of "hello" after first next() call', () => {
    let thisStep = genInstance.next;
    let [value, done] = [thisStep.value, thisStep.done];
    assert.equal(value, 'hello');
    assert.equal(done, false);
  });

  it('should have value of "world" after second next() call', () => {
    let thisStep = genInstance;
    let [value, done] = [thisStep.value, thisStep.done];
    assert.equal(value, 'world');
    assert.equal(done, false);
  });

  it('done property = true after stepping past all yield statements', () => {
    let done = genInstance.done;
    assert.equal(done, true);
  });

});<|endoftext|>


<commit_before>// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0
"use strict";
/* jshint globalstrict: true */

function show_password(ev) {
	var button = ev.target;
	var passwordField = document.getElementById(button.getAttribute('data-toggle'));
	passwordField.setAttribute('type', 'text');
	button.className += ' active';
	return false;
}
function hide_password(ev) {
	var button = ev.target;
	var passwordField = document.getElementById(button.getAttribute('data-toggle'));
	passwordField.setAttribute('type', 'password');
	button.className = button.className.replace(/(?:^|\s)active(?!\S)/g , '');
	return false;
}
var toggles = document.getElementsByClassName('toggle-password');
for (var i = 0 ; i < toggles.length ; i++) {
	toggles[i].addEventListener('mousedown', show_password);
	toggles[i].addEventListener('mouseup', hide_password);
}

function auth_type_change() {
	var auth_type = document.getElementById('auth_type');
	if (auth_type) {
		var auth_value = auth_type.value,
			password_input = document.getElementById('passwordPlain');

		if (auth_value === 'form') {
			password_input.required = true;
		} else {
			password_input.required = false;
		}
	}
}
var auth_type = document.getElementById('auth_type');
if (auth_type) {
	auth_type_change();
	auth_type.addEventListener('change', auth_type_change);
}

function mySqlShowHide() {
	var mysql = document.getElementById('mysql');
	if (mysql) {
		if (document.getElementById('type').value === 'sqlite') {
			document.getElementById('host').value = '';
			document.getElementById('user').value = '';
			document.getElementById('pass').value = '';
			document.getElementById('base').value = '';
			document.getElementById('prefix').value = '';
			mysql.style.display = 'none';
		} else {
			mysql.style.display = 'block';
		}
	}
}
var bd_type = document.getElementById('type');
if (bd_type) {
	mySqlShowHide();
	bd_type.addEventListener('change', mySqlShowHide);
}

function ask_confirmation(ev) {
	var str_confirmation = ev.target.getAttribute('data-str-confirm');
	if (!confirm(str_confirmation)) {
		ev.preventDefault();
	}
}
var confirms = document.getElementsByClassName('confirm');
for (var i = 0 ; i < confirms.length ; i++) {
	confirms[i].addEventListener('click', ask_confirmation);
}
// @license-end
<commit_msg>Fix JS show password in install (#2999)<commit_after>// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0
"use strict";
/* jshint esversion:6, strict:global */

function show_password(ev) {
	const button = ev.currentTarget;
	const passwordField = document.getElementById(button.getAttribute('data-toggle'));
	passwordField.setAttribute('type', 'text');
	button.className += ' active';
	return false;
}
function hide_password(ev) {
	const button = ev.currentTarget;
	const passwordField = document.getElementById(button.getAttribute('data-toggle'));
	passwordField.setAttribute('type', 'password');
	button.className = button.className.replace(/(?:^|\s)active(?!\S)/g , '');
	return false;
}
const toggles = document.getElementsByClassName('toggle-password');
for (let i = 0 ; i < toggles.length ; i++) {
	toggles[i].addEventListener('mousedown', show_password);
	toggles[i].addEventListener('mouseup', hide_password);
}

const auth_type = document.getElementById('auth_type');
function auth_type_change() {
	if (auth_type) {
		const auth_value = auth_type.value,
			password_input = document.getElementById('passwordPlain');

		if (auth_value === 'form') {
			password_input.required = true;
		} else {
			password_input.required = false;
		}
	}
}
if (auth_type) {
	auth_type_change();
	auth_type.addEventListener('change', auth_type_change);
}

function mySqlShowHide() {
	const mysql = document.getElementById('mysql');
	if (mysql) {
		if (document.getElementById('type').value === 'sqlite') {
			document.getElementById('host').value = '';
			document.getElementById('user').value = '';
			document.getElementById('pass').value = '';
			document.getElementById('base').value = '';
			document.getElementById('prefix').value = '';
			mysql.style.display = 'none';
		} else {
			mysql.style.display = 'block';
		}
	}
}
const bd_type = document.getElementById('type');
if (bd_type) {
	mySqlShowHide();
	bd_type.addEventListener('change', mySqlShowHide);
}

function ask_confirmation(ev) {
	const str_confirmation = ev.target.getAttribute('data-str-confirm');
	if (!confirm(str_confirmation)) {
		ev.preventDefault();
	}
}
const confirms = document.getElementsByClassName('confirm');
for (let i = 0 ; i < confirms.length ; i++) {
	confirms[i].addEventListener('click', ask_confirmation);
}
// @license-end
<|endoftext|>


<commit_before>(function (window) {
    var propertySeperator = "_",
    userAction = "$direct",
    cloneObject = function(params){
        try{
            // Clone Object
            return JSON.parse(JSON.stringify(params));
        }catch(err){
            return {};
        }
    },
    _track = function (params) {
        var prms = cloneObject(params);
        return new _constructor(prms);
    },
    _constructor = function (params) {
        var date = new Date(),
        sP = this.superProperties = params.superProperties || {};

        // Add date and time to superproperty object
        sP.date = date.toLocaleDateString();
        sP.timeStr = date.toLocaleTimeString();

        // Initialize mixpanel with token
        mixpanel.init(this.token = params.token);

        //Register Superproperties
        mixpanel.register(sP);

        // Set status property which will be used to check the state of tracking event whether "ON" or "OFF"
        this.status = params.status || {};

        // Set propertySeperator if passed by params
        if(params.seperator!==undefined){
            propertySeperator = params.seperator;
        }

        //Return object with associated properties and methods
        return this;
    };

    // Methods to track action
    _contructor.prototype.setAction = function(action){
        userAction = action;
    };

    _constructor.prototype.getAction = function(){
        return userAction;
    };

    // Methods for superproperties
    _constructor.prototype.getSuperProperty = function(super_property_name){
        // Return superproperty value
        return this.superProperties[super_property_name];
    };

    _constructor.prototype.setSuperProperty = function(obj){
        var registerSuperProperties = undefined;

        for(var a in obj){
            if(a!=="date" && a!=="timeStr"){
                // Update superProperty with new value
                this.superProperties[a] = obj[a];
                if(registerSuperProperties===undefined){
                    registerSuperProperties = function(){
                        // Re-register changed superproperty
                        mixpanel.register(obj);
                    }
                }
            }else{
                delete obj[a];
            }
        }

        // Execute registerSuperProperties to register superProperties if updated
        try{
            registerSuperProperties();
        }catch(err){}
    };

    _constructor.prototype.updateDateTime = function(){
        var date = new Date(),
        sP = this.superProperties;

        // Update date and time of superproperty object
        sP.date = date.toLocaleDateString();
        sP.timeStr = date.toLocaleTimeString();

        // Re-register superproperties
        mixpanel.register({"date":sP.date,"timeStr":sP.timeStr});
    };

    //Methods for settings
    _constructor.prototype.getOptionState = function(track_name){
        // Return current state in the settings of the tracking event
        return this.status[track_name];
    };

    _constructor.prototype.setOptionState = function(obj){
        for(var a in obj){
            this.status[a] = obj[a];
        }
    };

    // Methods to execute directly on objects
    _constructor.prototype.toFlatObject = function(param){
        // { tempObj } Object in which single-level prperty object will be stored and sent to mixpanel
        var tempObj = {};

        // Check if the object received by worker is an object ELSE directly respond the data
        if(typeof param === "object" && Object.prototype.toString.call(param) === "[object Object]"){
            var turnNestedToSingleLevel = function(){
                var hasSubRexecuteFunction = undefined;
                for(var a in param){
                    var currentProp = param[a];

                    // Check if the subproperty is an object ELSE delete property and store it in { tempObj }
                    if(typeof currentProp === "object" && Object.prototype.toString.call(currentProp) === "[object Object]"){
                        // If subproperty is an object loop through object and store them as single level properties on object
                        for(var b in currentProp){
                            param[a+propertySeperator+b] = currentProp[b];
                        }

                        // Initialize "hasSubRexecuteFunction" with the function reference to call recursively
                        if(hasSubRexecuteFunction===undefined){
                            hasSubRexecuteFunction = turnNestedToSingleLevel;
                        }

                        // Delete the property
                        delete currentProp;
                    }else{
                        // Delete the property after storing it to { tempObj }
                        delete currentProp;
                        tempObj[a] = currentProp;
                    }
                }

                try{
                    // Make recursive call to function if subproperties containing object exits
                    hasSubRexecuteFunction();
                }catch(err){}
            };

            // Make initial call to function which will flatten object to single level properties and store it to { tempObj }
            turnNestedToSingleLevel();

            // Return with the flat object
            return tempObj;
        }
        // Return with the data without any change if data received by worker is not an object
        return param;
    };

    // Assign properties that will be shared between instances
    _constructor.prototype.selectTrackOption = function (options) {
        // Initialize all properties which are sent to this function which is required for tracking.
        var track_name = options.name,
            track_details = options.details;

        // If the property is OFF in settings passed then don't execute
        if(this.status[track_name] === "OFF"){
            return;
        }

        mixpanel.track(track_name, this.toFlatObject(track_details));

        // Reset action for next track till another action is recorded
        userAction = "$direct";
    };

    // If there isn't any "_track" property on window then assign it.
    if (!window._track) {
        window._track = _track;
    }
})(window);<commit_msg>Updated tracking.js<commit_after>(function (window) {
    var propertySeperator = "_",
    userAction = "$direct",
    cloneObject = function(params){
        try{
            // Clone Object
            return JSON.parse(JSON.stringify(params));
        }catch(err){
            return {};
        }
    },
    _track = function (params) {
        var prms = cloneObject(params);
        return new _constructor(prms);
    },
    _constructor = function (params) {
        var date = new Date(),
        sP = this.superProperties = params.superProperties || {};

        // Add date and time to superproperty object
        sP.date = date.toLocaleDateString();
        sP.timeStr = date.toLocaleTimeString();

        // Initialize mixpanel with token
        mixpanel.init(this.token = params.token);

        //Register Superproperties
        mixpanel.register(sP);

        // Set status property which will be used to check the state of tracking event whether "ON" or "OFF"
        this.status = params.status || {};

        // Set propertySeperator if passed by params
        if(params.seperator!==undefined){
            propertySeperator = params.seperator;
        }

        //Return object with associated properties and methods
        return this;
    };

    // Methods to track action
    _constructor.prototype.setAction = function(action){
        userAction = action;
    };

    _constructor.prototype.getAction = function(){
        var uA = userAction;
        userAction = "$direct";
        return uA;
    };

    // Methods for superproperties
    _constructor.prototype.getSuperProperty = function(super_property_name){
        // Return superproperty value
        return this.superProperties[super_property_name];
    };

    _constructor.prototype.setSuperProperty = function(obj){
        var registerSuperProperties = undefined;

        for(var a in obj){
            if(a!=="date" && a!=="timeStr"){
                // Update superProperty with new value
                this.superProperties[a] = obj[a];
                if(registerSuperProperties===undefined){
                    registerSuperProperties = function(){
                        // Re-register changed superproperty
                        mixpanel.register(obj);
                    }
                }
            }else{
                delete obj[a];
            }
        }

        // Execute registerSuperProperties to register superProperties if updated
        try{
            registerSuperProperties();
        }catch(err){}
    };

    _constructor.prototype.updateDateTime = function(){
        var date = new Date(),
        sP = this.superProperties;

        // Update date and time of superproperty object
        sP.date = date.toLocaleDateString();
        sP.timeStr = date.toLocaleTimeString();

        // Re-register superproperties
        mixpanel.register({"date":sP.date,"timeStr":sP.timeStr});
    };

    //Methods for settings
    _constructor.prototype.getOptionState = function(track_name){
        // Return current state in the settings of the tracking event
        return this.status[track_name];
    };

    _constructor.prototype.setOptionState = function(obj){
        for(var a in obj){
            this.status[a] = obj[a];
        }
    };

    // Methods to execute directly on objects
    _constructor.prototype.toFlatObject = function(param){
        // { tempObj } Object in which single-level prperty object will be stored and sent to mixpanel
        var tempObj = {};

        // Check if the object received by worker is an object ELSE directly respond the data
        if(typeof param === "object" && Object.prototype.toString.call(param) === "[object Object]"){
            var turnNestedToSingleLevel = function(){
                var hasSubRexecuteFunction = undefined;
                for(var a in param){
                    var currentProp = param[a];

                    // Check if the subproperty is an object ELSE delete property and store it in { tempObj }
                    if(typeof currentProp === "object" && Object.prototype.toString.call(currentProp) === "[object Object]"){
                        // If subproperty is an object loop through object and store them as single level properties on object
                        for(var b in currentProp){
                            param[a+propertySeperator+b] = currentProp[b];
                        }

                        // Initialize "hasSubRexecuteFunction" with the function reference to call recursively
                        if(hasSubRexecuteFunction===undefined){
                            hasSubRexecuteFunction = turnNestedToSingleLevel;
                        }

                        // Delete the property
                        delete currentProp;
                    }else{
                        // Delete the property after storing it to { tempObj }
                        delete currentProp;
                        tempObj[a] = currentProp;
                    }
                }

                try{
                    // Make recursive call to function if subproperties containing object exits
                    hasSubRexecuteFunction();
                }catch(err){}
            };

            // Make initial call to function which will flatten object to single level properties and store it to { tempObj }
            turnNestedToSingleLevel();

            // Return with the flat object
            return tempObj;
        }
        // Return with the data without any change if data received by worker is not an object
        return param;
    };

    // Assign properties that will be shared between instances
    _constructor.prototype.selectTrackOption = function (options) {
        // Initialize all properties which are sent to this function which is required for tracking.
        var track_name = options.name,
            track_details = options.details;

        // If the property is OFF in settings passed then don't execute
        if(this.status[track_name] === "OFF"){
            return;
        }

        mixpanel.track(track_name, this.toFlatObject(track_details));

        // Reset action for next track till another action is recorded
        userAction = "$direct";
    };

    // If there isn't any "_track" property on window then assign it.
    if (!window._track) {
        window._track = _track;
    }
})(window);
<|endoftext|>


<commit_before>var github = require('./github');
var executor = require('./scriptExecutor');
var voxelEngine = require('../voxelEngine');
var blocks = require('../../shared/blocks');
var expandGists = require('../../shared/coding/expandGists');
var auth = require('../auth');
var io = require('socket.io-client');

var blocksWithCode;
var socket;

module.exports = {
  init: function() {
    var self = this;
    socket = io.connect(location.host + '/coding');
    return new Promise(function(resolve, reject) {
      socket.emit('requestAllCode', auth.getAccessToken(), function(err, response) {
        if(err) {
          throw new Error('Error fetching code. ' + err);
        }

        if(auth.isLogged()) {
          blocksWithCode = response;
          resolve();
        } else {
          expandGists(response, github.getGist).then(function(result) {
            blocksWithCode = result;
            resolve();
          });
        }
      });
      socket.on('codeChanged', function(position, codeObj) {
        console.log('codeChanged')
        blocksWithCode[position] = codeObj;
        executor.update(position, codeObj.code);
        voxelEngine.setBlock(position, blocks.types.CODE.number);
      });
      socket.on('codeRemoved', function(position) {
        delete blocksWithCode[position];
        executor.remove(position);
      });
    });
  },
  getBlocksWithCode: function() {
    var result = [];
    Object.keys(blocksWithCode).forEach(function(pos) {
      result.push({
        position: pos.split(','),
        codeObj: blocksWithCode[pos]
      });
    });
    return result;
  },
  getCode: function(position) {
    return blocksWithCode[position];
  },
  hasCode: function(position) {
    return !!blocksWithCode[position];
  },
  storeCode: function(position, code) {
    var self = this;
    return new Promise(function(resolve, reject) {
      socket.emit('codeChanged', position, code, auth.getAccessToken(), function(err, codeObj) {
        if(err) {
          reject(err);
        } else {
          blocksWithCode[position] = codeObj;
          resolve(codeObj);
        }
      });
    });
  },
  removeCode: function(position) {
    delete blocksWithCode[position];
    socket.emit('codeRemoved', position);
  }
};
<commit_msg>removing unnecessary self = this<commit_after>var github = require('./github');
var executor = require('./scriptExecutor');
var voxelEngine = require('../voxelEngine');
var blocks = require('../../shared/blocks');
var expandGists = require('../../shared/coding/expandGists');
var auth = require('../auth');
var io = require('socket.io-client');

var blocksWithCode;
var socket;

module.exports = {
  init: function() {
    socket = io.connect(location.host + '/coding');
    return new Promise(function(resolve, reject) {
      socket.emit('requestAllCode', auth.getAccessToken(), function(err, response) {
        if(err) {
          throw new Error('Error fetching code. ' + err);
        }

        if(auth.isLogged()) {
          blocksWithCode = response;
          resolve();
        } else {
          expandGists(response, github.getGist).then(function(result) {
            blocksWithCode = result;
            resolve();
          });
        }
      });
      socket.on('codeChanged', function(position, codeObj) {
        console.log('codeChanged')
        blocksWithCode[position] = codeObj;
        executor.update(position, codeObj.code);
        voxelEngine.setBlock(position, blocks.types.CODE.number);
      });
      socket.on('codeRemoved', function(position) {
        delete blocksWithCode[position];
        executor.remove(position);
      });
    });
  },
  getBlocksWithCode: function() {
    var result = [];
    Object.keys(blocksWithCode).forEach(function(pos) {
      result.push({
        position: pos.split(','),
        codeObj: blocksWithCode[pos]
      });
    });
    return result;
  },
  getCode: function(position) {
    return blocksWithCode[position];
  },
  hasCode: function(position) {
    return !!blocksWithCode[position];
  },
  storeCode: function(position, code) {
    return new Promise(function(resolve, reject) {
      socket.emit('codeChanged', position, code, auth.getAccessToken(), function(err, codeObj) {
        if(err) {
          reject(err);
        } else {
          blocksWithCode[position] = codeObj;
          resolve(codeObj);
        }
      });
    });
  },
  removeCode: function(position) {
    delete blocksWithCode[position];
    socket.emit('codeRemoved', position);
  }
};
<|endoftext|>


<commit_before>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */
      function areMushrooms(ingredient){
        return ingredient === "mushrooms"
      }

      productsICanEat = _(products).filter(function(x){return !x.containsNuts && !_(x.ingredients).any(areMushrooms)})

      expect(productsICanEat.length).toBe(1);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = _.chain(_.range(1000))
              .reduce(function(total, x){return total+(x%3==0 || x%5==0 ? x : 0)}, 0)
              .value();    /* try chaining range() and reduce() */

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */
    var ingredientCount = _(products).chain()
                          .map(function(x){return x.ingredients})
                          .flatten()
                          .reduce(function(ingredients, ingredient){
                            ingredients[ingredient] = (ingredients[ingredient]||0)+1;
                            return ingredients;
                          }, {})
                          .value();

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */

  it("should find the largest prime factor of a composite number", function () {

    function isPrime(num){
      if (num<4){
        return true;
      }
      for (var i=2; i<Math.sqrt(num)+1; i++){
        if (num%i==0){
          return false;
        }
      }
      return true;
    }

    function largestPrimeFactor(compositeNumber){
      for(var i=2; i<compositeNumber; i++){
        if(compositeNumber%i==0 && isPrime(compositeNumber/i)){
          return compositeNumber/i;
        }
      }
    }

    largestPrimeFactor(26454);

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

    function isPalindrome(num){
      var number = num.toString();
      for (var i=0; i<number.length/2; i++){
        if (number[i] !== number[number.length-1-i]){
          return false;
        }
      }
      return true;
    }

    function hasFactorWithDigits(num, max){
      var max = max;
      var min = max/9;
      for (var i=max; i>=min; i--){
        if(num%i===0){
          if ((num/i).toString().length === max.toString().length){
            return true;
          }
        }
      }
    }

    function largestPalindrome(num1, num2){
      for (var i=num1*num2; i>(num1/9)*(num2/9); i--){
        if (isPalindrome(i)){
          if (hasFactorWithDigits(i,num1)){
            return i;
          }
        }
      }
    }

    largestPalindrome(999,999);

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

    function isPrime(num){
      if (num<4){
        return true;
      }
      for (var i=2; i<Math.sqrt(num)+1; i++){
        if (num%i===0){
          return false;
        }
      }
      return true;
    }

    function primeFactors(num, primes){
      var factors = {};
      while(num!==1){
        for (var i=0; i<primes.length; i++){
          if (num%primes[i]===0){
            factors[primes[i]] = (factors[primes[i]] || 0)+1;
            num = num/primes[i];
          }
        }
      }
      return factors;
    }

    function lcm(numbersObj){
      for (var x in numbersObj) {
        if (!lcmFactors[x] || (numbersObj[x] > lcmFactors[x])){
          lcmFactors[x] = numbersObj[x];
        }
      }
    }

    var lcmFactors = {};
    var lcmResult = 1;

    var primes = _(_.range(2,21)).filter(isPrime);

    _.range(2,21)
    .map(function(value){return primeFactors(value, primes)})
    .forEach(lcm)

    for (var x in lcmFactors){
      if (Number(x)){
        lcmResult = lcmResult*Math.pow(Number(x),lcmFactors[x]);
      }
    }

    lcmResult;

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

    function differenceSquares(array){
      var sumOfSquare = 0;
      var squareOfSums = 0;

      for (var i=0; i<array.length; i++){
        sumOfSquare += Math.pow(array[i],2);
      }

      for (var i=0; i<array.length; i++){
        squareOfSums += array[i];
      }
      squareOfSums = Math.pow(squareOfSums,2);

      return sumOfSquare-squareOfSums;
    }

  });

  it("should find the 10001st prime", function () {

    function isPrime(num){
      if (num<4){
        return true;
      }
      for (var i=2; i<Math.sqrt(num)+1; i++){
        if (num%i===0){
          return false;
        }
      }
      return true;
    }

    function nthPrime(n){
      var primeNum = 0;
      for (var i=2; i<Math.pow(n,2); i++){
        if (isPrime(i)){
          primeNum += 1;
        }
        if (primeNum === n){
          return i;
        }
      }
    }

    nthPrime(1001);

  });

});
<commit_msg>nthPrime function missed case of n=1.<commit_after>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */
      function areMushrooms(ingredient){
        return ingredient === "mushrooms"
      }

      productsICanEat = _(products).filter(function(x){return !x.containsNuts && !_(x.ingredients).any(areMushrooms)})

      expect(productsICanEat.length).toBe(1);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = _.chain(_.range(1000))
              .reduce(function(total, x){return total+(x%3==0 || x%5==0 ? x : 0)}, 0)
              .value();    /* try chaining range() and reduce() */

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */
    var ingredientCount = _(products).chain()
                          .map(function(x){return x.ingredients})
                          .flatten()
                          .reduce(function(ingredients, ingredient){
                            ingredients[ingredient] = (ingredients[ingredient]||0)+1;
                            return ingredients;
                          }, {})
                          .value();

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */

  it("should find the largest prime factor of a composite number", function () {

    function isPrime(num){
      if (num<4){
        return true;
      }
      for (var i=2; i<Math.sqrt(num)+1; i++){
        if (num%i==0){
          return false;
        }
      }
      return true;
    }

    function largestPrimeFactor(compositeNumber){
      for(var i=2; i<compositeNumber; i++){
        if(compositeNumber%i==0 && isPrime(compositeNumber/i)){
          return compositeNumber/i;
        }
      }
    }

    largestPrimeFactor(26454);

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

    function isPalindrome(num){
      var number = num.toString();
      for (var i=0; i<number.length/2; i++){
        if (number[i] !== number[number.length-1-i]){
          return false;
        }
      }
      return true;
    }

    function hasFactorWithDigits(num, max){
      var max = max;
      var min = max/9;
      for (var i=max; i>=min; i--){
        if(num%i===0){
          if ((num/i).toString().length === max.toString().length){
            return true;
          }
        }
      }
    }

    function largestPalindrome(num1, num2){
      for (var i=num1*num2; i>(num1/9)*(num2/9); i--){
        if (isPalindrome(i)){
          if (hasFactorWithDigits(i,num1)){
            return i;
          }
        }
      }
    }

    largestPalindrome(999,999);

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

    function isPrime(num){
      if (num<4){
        return true;
      }
      for (var i=2; i<Math.sqrt(num)+1; i++){
        if (num%i===0){
          return false;
        }
      }
      return true;
    }

    function primeFactors(num, primes){
      var factors = {};
      while(num!==1){
        for (var i=0; i<primes.length; i++){
          if (num%primes[i]===0){
            factors[primes[i]] = (factors[primes[i]] || 0)+1;
            num = num/primes[i];
          }
        }
      }
      return factors;
    }

    function lcm(numbersObj){
      for (var x in numbersObj) {
        if (!lcmFactors[x] || (numbersObj[x] > lcmFactors[x])){
          lcmFactors[x] = numbersObj[x];
        }
      }
    }

    var lcmFactors = {};
    var lcmResult = 1;

    var primes = _(_.range(2,21)).filter(isPrime);

    _.range(2,21)
    .map(function(value){return primeFactors(value, primes)})
    .forEach(lcm)

    for (var x in lcmFactors){
      if (Number(x)){
        lcmResult = lcmResult*Math.pow(Number(x),lcmFactors[x]);
      }
    }

    lcmResult;

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

    function differenceSquares(array){
      var sumOfSquare = 0;
      var squareOfSums = 0;

      for (var i=0; i<array.length; i++){
        sumOfSquare += Math.pow(array[i],2);
      }

      for (var i=0; i<array.length; i++){
        squareOfSums += array[i];
      }
      squareOfSums = Math.pow(squareOfSums,2);

      return sumOfSquare-squareOfSums;
    }

  });

  it("should find the 10001st prime", function () {

    function isPrime(num){
      if (num<4){
        return true;
      }
      for (var i=2; i<Math.sqrt(num)+1; i++){
        if (num%i===0){
          return false;
        }
      }
      return true;
    }

    function nthPrime(n){
      var primeNum = 0;
      if (n === 1){
        return 2;
      }
      for (var i=2; i<Math.pow(n,2); i++){
        if (isPrime(i)){
          primeNum += 1;
        }
        if (primeNum === n){
          return i;
        }
      }
    }

    nthPrime(1001);

  });

});
<|endoftext|>


<commit_before>Template.tweetsList.helpers({
  tweets: getTweets
});

function getTweets () {
  if (Meteor.userId()) {
    var tweets = Tweets.find({userId: Meteor.userId()}).fetch();
    tweets.sort(hasLatestVariation);
    return tweets;
  };
}

function hasLatestVariation (t1, t2) {
  return (getLatest(t1.variations) < getLatest(t2.variations)) ? -1 : 1;
}

function getLatest(variations) {
  var recent = Number.POSITIVE_INFINITY;
  for(var i=variations.length;i-->0;)
    if(!variations[i].sent && !variations[i].error && variations[i].time < recent)
      recent = variations[i].time;
  return recent;
}
<commit_msg>Renamed tweetList -> tweetsList<commit_after><|endoftext|>