<commit_before>import * as utils from '../../../utils';
import helper from '../../helper';
import { header as headerWidget, backButton, empty } from '../../shared/common';
import layout from '../../layout';
import gameApi from '../../../lichess/game';
import i18n from '../../../i18n';
import gameStatus from '../../../lichess/status';
import { toggleGameBookmark } from '../../../xhr';
import session from '../../../session';
import m from 'mithril';
import ViewOnlyBoard from '../../shared/ViewOnlyBoard';

export default function view(ctrl) {
  const header = utils.partialf(headerWidget, null,
    backButton(ctrl.user() ? (ctrl.user().username + ' ' + ctrl.variant + ' Stats') : '')
  );

  function renderBody() {
    const data = ctrl.variantPerfData();
    const days = Math.floor(data.stat.count.seconds/(60*60*24));
    const hours = Math.floor(data.stat.count.seconds/(60*60)) - days*24;
    const mins = Math.floor(data.stat.count.seconds/(60)) - days*24*60 - hours*60;

    return (

             Current Rating

             Rating
             {Math.round(data.perf.glicko.rating) + (data.perf.glicko.provisional ? "?" : "")}

             Last 12 Games Progress
             {helper.progress(data.perf.progress)}

             Ranking
             {data.rank === null ? "" : data.rank}

             Percentile
             {data.percentile === null ? "" : (data.percentile+ "%")}

             Other Rating Stats

             Avg op rating
             {Math.round(data.stat.count.opAvg)}

             Highest rating
              {data.stat.highest.int}
              {data.stat.highest.at.substring(0,10)}

             Lowest rating
              {data.stat.lowest.int}
              {data.stat.lowest.at.substring(0,10)}

             Time playing
             { (days > 0 ? (days+"d, ") : "") + hours + "h, " + mins + "m" }

             Game Stats

             Victories
              {data.stat.count.win}
              {Math.round((data.stat.count.win/data.stat.count.all)*100) + "%"}

             Draws
             {data.stat.count.draw}
             {Math.round((data.stat.count.draw/data.stat.count.all)*100) + "%"}

             Defeats
              {data.stat.count.loss}
              {Math.round((data.stat.count.loss/data.stat.count.all)*100) + "%"}

             Total
             {data.stat.count.all}

 Best Victories

          {data.stat.bestWins.results.map(p => renderGame(p))}

 Worst Defeats

          {data.stat.worstLosses.results.map(p => renderGame(p))}

    );
  }

  return layout.free(header, renderBody, empty, empty);
}

function renderGame(game) {
  var opp = (game.opId.title === null ? "" : game.opId.title) + " " + game.opId.name;
  var date = game.at.substring(0,10);
  var gameId = game.gameId;

  return (

 m.route('/game/' + gameId))}>
      {opp} ({date})

  );
}
<commit_msg>Began international reference work.<commit_after>import * as utils from '../../../utils';
import helper from '../../helper';
import { header as headerWidget, backButton, empty } from '../../shared/common';
import layout from '../../layout';
import gameApi from '../../../lichess/game';
import i18n from '../../../i18n';
import gameStatus from '../../../lichess/status';
import { toggleGameBookmark } from '../../../xhr';
import session from '../../../session';
import m from 'mithril';
import ViewOnlyBoard from '../../shared/ViewOnlyBoard';

export default function view(ctrl) {
  const header = utils.partialf(headerWidget, null,
    backButton(ctrl.user() ? (ctrl.user().username + ' ' + ctrl.variant + ' Stats') : '')
  );

  function renderBody() {
    const data = ctrl.variantPerfData();
    const days = Math.floor(data.stat.count.seconds/(60*60*24));
    const hours = Math.floor(data.stat.count.seconds/(60*60)) - days*24;
    const mins = Math.floor(data.stat.count.seconds/(60)) - days*24*60 - hours*60;

    return (

             Current Rating

             {i18n("rating")}
             {Math.round(data.perf.glicko.rating) + (data.perf.glicko.provisional ? "?" : "")}

             Last 12 Games Progress
             {helper.progress(data.perf.progress)}

             {i18n("rank")}
             {data.rank === null ? "" : data.rank}

             %
             {data.percentile === null ? "" : (data.percentile+ "%")}

             Other Rating Stats

             Avg op rating
             {Math.round(data.stat.count.opAvg)}

             Highest rating
              {data.stat.highest.int}
              {data.stat.highest.at.substring(0,10)}

             Lowest rating
              {data.stat.lowest.int}
              {data.stat.lowest.at.substring(0,10)}

             Time playing
             { (days > 0 ? (days+"d, ") : "") + hours + "h, " + mins + "m" }

             Game Stats

             Victories
              {data.stat.count.win}
              {Math.round((data.stat.count.win/data.stat.count.all)*100) + "%"}

             Draws
             {data.stat.count.draw}
             {Math.round((data.stat.count.draw/data.stat.count.all)*100) + "%"}

             Defeats
              {data.stat.count.loss}
              {Math.round((data.stat.count.loss/data.stat.count.all)*100) + "%"}

             Total
             {data.stat.count.all}

 Best Victories

          {data.stat.bestWins.results.map(p => renderGame(p))}

 Worst Defeats

          {data.stat.worstLosses.results.map(p => renderGame(p))}

    );
  }

  return layout.free(header, renderBody, empty, empty);
}

function renderGame(game) {
  var opp = (game.opId.title === null ? "" : game.opId.title) + " " + game.opId.name;
  var date = game.at.substring(0,10);
  var gameId = game.gameId;

  return (

 m.route('/game/' + gameId))}>
      {opp} ({date})

  );
}
<|endoftext|>


<commit_before>import * as utils from '../../../utils';
import helper from '../../helper';
import { header as headerWidget, backButton } from '../../shared/common';
import layout from '../../layout';
import i18n from '../../../i18n';
import m from 'mithril';
import {shortPerfTitle} from '../../../lichess/perfs';

export default function view(ctrl) {
  const header = utils.partialf(headerWidget, null,
    backButton(ctrl.user() ? (ctrl.user().username + ' ' + shortPerfTitle(ctrl.variant) + ' stats') : '')
  );

  function renderBody() {
    const data = ctrl.variantPerfData();

    if (!data) return null;

    const days = Math.floor(data.stat.count.seconds / (60 * 60 * 24));
    const hours = Math.floor(data.stat.count.seconds / (60 * 60)) - days * 24;
    const mins = Math.floor(data.stat.count.seconds / 60) - days * 24 * 60 - hours * 60;

    return (

             Current Rating

             {i18n('rating')}
             {Math.round(data.perf.glicko.rating) + (data.perf.glicko.provisional ? '?' : '')}

             Last 12 games progress
             {helper.progress(data.perf.progress)}

             {i18n('rank')}
             {data.rank === null ? '' : data.rank}

             Percentile
             {data.percentile === null ? '' : (data.percentile + '%')}

             Other {i18n('rating')} Statistics

             Avg opponent {i18n('rating').toLowerCase()}
             {Math.round(data.stat.count.opAvg)}

             Highest {i18n('rating').toLowerCase()}
              {data.stat.highest ? data.stat.highest.int : ''}
              {data.stat.highest ? data.stat.highest.at.substring(0, 10) : ''}

             Lowest {i18n('rating').toLowerCase()}
              {data.stat.lowest ? data.stat.lowest.int : ''}
              {data.stat.lowest ? data.stat.lowest.at.substring(0, 10) : ''}

             {i18n('tpTimeSpentPlaying', 0).split(':')[0]}
             { (days > 0 ? (days + 'd, ') : '') + hours + 'h, ' + mins + 'm' }

             Game Stats

             {i18n('wins')}
              {data.stat.count.win}
              {Math.round((data.stat.count.win / data.stat.count.all) * 100) + '%'}

             {toTitleCase(i18n('nbDraws', 0).split(' ')[1])}
             {data.stat.count.draw}
             {Math.round((data.stat.count.draw / data.stat.count.all) * 100) + '%'}

             {i18n('losses')}
              {data.stat.count.loss}
              {Math.round((data.stat.count.loss / data.stat.count.all) * 100) + '%'}

             Total
             {data.stat.count.all}

             {i18n('rated')}
             {data.stat.count.rated}
             {Math.round((data.stat.count.rated / data.stat.count.all) * 100) + '%'}

             {i18n('tournament')}
             {data.stat.count.tour}
             {Math.round((data.stat.count.tour / data.stat.count.all) * 100) + '%'}

             Berserk
             {data.stat.count.berserk}
             {Math.round((data.stat.count.berserk / data.stat.count.all) * 100) + '%'}

             Disconnect
             {data.stat.count.disconnects}
             {Math.round((data.stat.count.disconnects / data.stat.count.all) * 100) + '%'}

             Streaks

             Playing streak
             {data.stat.playStreak.nb.max.v}
             {data.stat.playStreak.lastDate.substring(0, 10)}

             {i18n('winStreak')}
              {data.stat.resultStreak.win.max.v ? data.stat.resultStreak.win.max.v : ''}
              {data.stat.resultStreak.win.max.to ? data.stat.resultStreak.win.max.to.at.substring(0, 10) : ''}

             Losing streak
              {data.stat.resultStreak.loss.max.v ? data.stat.resultStreak.loss.max.v : ''}
              {data.stat.resultStreak.loss.max.to ? data.stat.resultStreak.loss.max.to.at.substring(0, 10) : ''}

 Best Wins

          {data.stat.bestWins.results.map(p => renderGame(p))}

    );
  }

  return layout.free(header, renderBody);
}

function renderGame(game) {
  var opp = (game.opId.title === null ? '' : game.opId.title) + ' ' + game.opId.name;
  var date = game.at.substring(0, 10);
  var gameId = game.gameId;

  return (

 m.route('/game/' + gameId))}>
      {opp} ({date})

  );
}

function isEmpty(element) {
  if (!element)
    return 'empty';
  else
    return '';
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
<commit_msg>Fix rating rounding<commit_after>import * as utils from '../../../utils';
import helper from '../../helper';
import { header as headerWidget, backButton } from '../../shared/common';
import layout from '../../layout';
import i18n from '../../../i18n';
import m from 'mithril';
import {shortPerfTitle} from '../../../lichess/perfs';

export default function view(ctrl) {
  const header = utils.partialf(headerWidget, null,
    backButton(ctrl.user() ? (ctrl.user().username + ' ' + shortPerfTitle(ctrl.variant) + ' stats') : '')
  );

  function renderBody() {
    const data = ctrl.variantPerfData();

    if (!data) return null;

    const days = Math.floor(data.stat.count.seconds / (60 * 60 * 24));
    const hours = Math.floor(data.stat.count.seconds / (60 * 60)) - days * 24;
    const mins = Math.floor(data.stat.count.seconds / 60) - days * 24 * 60 - hours * 60;

    return (

             Current Rating

             {i18n('rating')}
             {data.perf.glicko.rating + (data.perf.glicko.provisional ? '?' : '')}

             Last 12 games progress
             {helper.progress(data.perf.progress)}

             {i18n('rank')}
             {data.rank === null ? '' : data.rank}

             Percentile
             {data.percentile === null ? '' : (data.percentile + '%')}

             Other {i18n('rating')} Statistics

             Avg opponent {i18n('rating').toLowerCase()}
             {data.stat.count.opAvg}

             Highest {i18n('rating').toLowerCase()}
              {data.stat.highest ? data.stat.highest.int : ''}
              {data.stat.highest ? data.stat.highest.at.substring(0, 10) : ''}

             Lowest {i18n('rating').toLowerCase()}
              {data.stat.lowest ? data.stat.lowest.int : ''}
              {data.stat.lowest ? data.stat.lowest.at.substring(0, 10) : ''}

             {i18n('tpTimeSpentPlaying', 0).split(':')[0]}
             { (days > 0 ? (days + 'd, ') : '') + hours + 'h, ' + mins + 'm' }

             Game Stats

             {i18n('wins')}
              {data.stat.count.win}
              {Math.round((data.stat.count.win / data.stat.count.all) * 100) + '%'}

             {toTitleCase(i18n('nbDraws', 0).split(' ')[1])}
             {data.stat.count.draw}
             {Math.round((data.stat.count.draw / data.stat.count.all) * 100) + '%'}

             {i18n('losses')}
              {data.stat.count.loss}
              {Math.round((data.stat.count.loss / data.stat.count.all) * 100) + '%'}

             Total
             {data.stat.count.all}

             {i18n('rated')}
             {data.stat.count.rated}
             {Math.round((data.stat.count.rated / data.stat.count.all) * 100) + '%'}

             {i18n('tournament')}
             {data.stat.count.tour}
             {Math.round((data.stat.count.tour / data.stat.count.all) * 100) + '%'}

             Berserk
             {data.stat.count.berserk}
             {Math.round((data.stat.count.berserk / data.stat.count.all) * 100) + '%'}

             Disconnect
             {data.stat.count.disconnects}
             {Math.round((data.stat.count.disconnects / data.stat.count.all) * 100) + '%'}

             Streaks

             Playing streak
             {data.stat.playStreak.nb.max.v}
             {data.stat.playStreak.lastDate.substring(0, 10)}

             {i18n('winStreak')}
              {data.stat.resultStreak.win.max.v ? data.stat.resultStreak.win.max.v : ''}
              {data.stat.resultStreak.win.max.to ? data.stat.resultStreak.win.max.to.at.substring(0, 10) : ''}

             Losing streak
              {data.stat.resultStreak.loss.max.v ? data.stat.resultStreak.loss.max.v : ''}
              {data.stat.resultStreak.loss.max.to ? data.stat.resultStreak.loss.max.to.at.substring(0, 10) : ''}

 Best Wins

          {data.stat.bestWins.results.map(p => renderGame(p))}

    );
  }

  return layout.free(header, renderBody);
}

function renderGame(game) {
  var opp = (game.opId.title === null ? '' : game.opId.title) + ' ' + game.opId.name;
  var date = game.at.substring(0, 10);
  var gameId = game.gameId;

  return (

 m.route('/game/' + gameId))}>
      {opp} ({date})

  );
}

function isEmpty(element) {
  if (!element)
    return 'empty';
  else
    return '';
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
<|endoftext|>


<commit_before>(function ($) {
    $(function () {
        var $widget = $('.comments-widget'),
            $formWrap = $('.comment-form-wrap'),
            $form = $formWrap.find('form'),
            $pid = $form.find('#Comment_parent_id'),
            $text = $form.find('#Comment_text'),
            $notifications = $('#notifications');

        function clearForm() {
            if ($.fn.redactor !== undefined) {
                $text.redactor('insert.set', '');
            }
            $text.val('');
            $pid.val('');
        }

        function insertComment(pid, content) {
            if (!pid) {
                $widget.append(content);
                return;
            }

            var $parent = $widget.find('[data-id="' + pid + '"]'),
                $lastChild = $widget.find('[data-pid="' + pid + '"]:last');

            if ($lastChild.length > 0) {
                $lastChild.after(content);
            } else {
                $parent.after(content);
            }
        }

        $widget.on('click', 'a.reply', function (event) {
            var $this = $(this),
                $item = $this.parents('.comments-item');

            event.preventDefault();
            if ($this.attr('rel') != $pid.val()) {
                clearForm();
                $item.after($formWrap);
                $form.find('#close-comment').show();
                $pid.val($this.attr('rel'));
            }
        });

        $widget.on('keyup', 'textarea, input[type=text]', function (event) {
            if (event.ctrlKey && event.keyCode == 13) {
                $form.submit();
            }
        });

        $form.on('click', '#close-comment', function () {
            $(this).hide();
            clearForm();
            $widget.append($formWrap);
        });

        $form.on('submit', function (event) {
            event.preventDefault();

            if (!$text.val()) {
                $notifications.notify({message: {text: 'Комментарий пуст =('}, 'type': 'danger'}).show();
                return;
            }

            $.post($form.attr('action'), $form.serialize(), function (response) {
                $notifications.notify({
                    message: {text: response.data.message},
                    'type': response.result ? 'success' : 'danger'
                }).show();

                $('#captcha-refresh').trigger('click');

                if (response.result) {
                    insertComment(response.data.comment.parent_id, response.data.commentContent);
                    clearForm();
                    $widget.append($formWrap);
                    $form.find('#close-comment').hide();
                }
            }, 'json');
        });
    });
})(jQuery);
<commit_msg>fix #1950<commit_after>(function ($) {
    $(function () {
        var $widget = $('.comments-widget'),
            $formWrap = $('.comment-form-wrap'),
            $form = $formWrap.find('form'),
            $pid = $form.find('#Comment_parent_id'),
            $text = $form.find('#Comment_text'),
            $notifications = $('#notifications');

        function clearForm() {
            $form[0].reset();
            if ($.fn.redactor !== undefined) {
                $text.redactor('insert.set', '');
            }
        }

        function insertComment(pid, content) {
            if (!pid) {
                $widget.append(content);
                return;
            }

            var $parent = $widget.find('[data-id="' + pid + '"]'),
                $lastChild = $widget.find('[data-pid="' + pid + '"]:last');

            if ($lastChild.length > 0) {
                $lastChild.after(content);
            } else {
                $parent.after(content);
            }
        }

        $widget.on('click', 'a.reply', function (event) {
            var $this = $(this),
                $item = $this.parents('.comments-item');

            event.preventDefault();
            if ($this.attr('rel') != $pid.val()) {
                clearForm();
                $item.after($formWrap);
                $form.find('#close-comment').show();
                $pid.val($this.attr('rel'));
            }
        });

        $widget.on('keyup', 'textarea, input[type=text]', function (event) {
            if (event.ctrlKey && event.keyCode == 13) {
                $form.submit();
            }
        });

        $form.on('click', '#close-comment', function () {
            $(this).hide();
            clearForm();
            $widget.append($formWrap);
        });

        $form.on('submit', function (event) {
            event.preventDefault();

            if (!$text.val()) {
                $notifications.notify({message: {text: 'Комментарий пуст =('}, 'type': 'danger'}).show();
                return;
            }

            $.post($form.attr('action'), $form.serialize(), function (response) {
                $notifications.notify({
                    message: {text: response.data.message},
                    'type': response.result ? 'success' : 'danger'
                }).show();

                $('#captcha-refresh').trigger('click');

                if (response.result) {
                    insertComment(response.data.comment.parent_id, response.data.commentContent);
                    clearForm();
                    $widget.append($formWrap);
                    $form.find('#close-comment').hide();
                }
            }, 'json');
        });
    });
})(jQuery);<|endoftext|>


<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var insert_param = function(key, value) {

        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            document.location.search = '?' + key + '=' + value;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var currentUrl = window.location.pathname;
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(currentUrl.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        } else {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        FeedbackSignal.current_state(current);
        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var currentUrl = window.location.pathname;
            var selected = [];
            var catids = [];

            for(var i=0; i < $scope.selected.length; i++) {

                var me = $scope.selected[i];
                var entity = $(".dashboard-feedback[feedback=" + me + "]");
                var entity_parent = entity.parents('.feedback-group');
                var mode = $scope.status_select_value;
                var score = entity.attr('score');
                var permission = entity.attr('permission');
                var catid = entity.attr('catid');

                console.log(me)
                console.log(score)
                console.log(permission)
                console.log(mode)

                if(
                      (score >= 3 && permission == 1)
                   || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                   || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                  )  {

                    entity.hide();

                    var child_count = entity_parent.children('.dashboard-feedback:visible');

                    if(child_count.length == 0) {
                        entity_parent.hide();
                    }

                    selected.push(me);
                    catids.push(catid);
                }

                var checkbox = $(".feed-checkbox[value=" + me + "]");

                if( checkbox.is(":checked") ) {
                    checkbox.click();
                }
            }

            if(selected.length > 0) {

                if(currentUrl.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                FeedbackSignal.current_state(feed);
                FeedbackControlService.change_status(feed, true);
                $(".checky-box-container").show();
            } else {
                alert("Action is not allowed!");
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            console.log(i);

            var entity = checkboxes[i];
            var myparent = $(entity).parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!$(entity).is(":checked")) {
                    $(entity).click();
                }
            } else {
                $(entity).click();
            }

            update_selected(action, parseInt($(entity).val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            if($scope.date_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('date', $scope.date_filter);
            }
        }

        if(filter_type == 'priority') {
            if($scope.priority_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('priority', $scope.priority_filter);
            }
        }

        if(filter_type == 'status') {
            if($scope.status_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('status', $scope.status_filter);
            }
        }

        if(filter_type == 'rating') {
            if($scope.rating_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('rating', $scope.rating_filter);
            }
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        //console.log("expunged");
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<commit_msg>I can love you<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var insert_param = function(key, value) {

        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            document.location.search = '?' + key + '=' + value;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var currentUrl = window.location.pathname;
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(currentUrl.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        } else {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        FeedbackSignal.current_state(current);
        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var currentUrl = window.location.pathname;
            var selected = [];
            var catids = [];

            for(var i=0; i < $scope.selected.length; i++) {

                var me = $scope.selected[i];
                var entity = $(".dashboard-feedback[feedback=" + me + "]");
                var entity_parent = entity.parents('.feedback-group');
                var mode = $scope.status_select_value;
                var score = entity.attr('score');
                var permission = entity.attr('permission');
                var catid = entity.attr('catid');

                console.log(me)
                console.log(score)
                console.log(permission)
                console.log(mode)

                if(
                      (score >= 3 && permission == 1)
                   || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                   || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                  )  {

                    entity.hide();

                    var child_count = entity_parent.children('.dashboard-feedback:visible');

                    if(child_count.length == 0) {
                        entity_parent.hide();
                    }

                    selected.push(me);
                    catids.push(catid);
                }

                var checkbox = $(".feed-checkbox[value=" + me + "]");

                if( checkbox.is(":checked") ) {
                    checkbox.click();
                }
            }

            if(selected.length > 0) {

                if(currentUrl.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                FeedbackSignal.current_state(feed);
                FeedbackControlService.change_status(feed, true);
                $(".checky-box-container").show();
            } else {
                alert("Action is not allowed!");
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            console.log(entity.val());

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            if($scope.date_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('date', $scope.date_filter);
            }
        }

        if(filter_type == 'priority') {
            if($scope.priority_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('priority', $scope.priority_filter);
            }
        }

        if(filter_type == 'status') {
            if($scope.status_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('status', $scope.status_filter);
            }
        }

        if(filter_type == 'rating') {
            if($scope.rating_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('rating', $scope.rating_filter);
            }
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        //console.log("expunged");
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<|endoftext|>


<commit_before>angular
	.module('DashboardControllerModule', ['chart.js'])
	.controller(
		'DashboardController',
		[
			'$scope',
			'$location',
			'$window',
			'jwtHelper',
			'BindingService',
			'TemplateService',
			function ($scope, $location, $window, jwtHelper,
				bindingService, templateService) {

				var url = $location.$$absUrl;
				var tokenIndex = url.indexOf("?token=");
				if (tokenIndex != -1) {
					var token = url.substring(url
						.indexOf("?token=") + 7, url.length);
					console.log(token);
					$window.sessionStorage.token = token;
					$scope.user = jwtHelper.decodeToken(token);
				}

				$scope.chartNo = 0;
				$scope.dataLoaded = false;
				$scope.statistics = "";
				$scope.title = "";
				$scope.maxChart = 4;
				$scope.elementTypeFilter = "";
				$scope.templateFilter = "";
				$scope.typeFilter = "";
				$scope.typeFilters = [];

				$scope.nextChart = function () {
					console.log("next chart");

					$scope.chartNo++;
					if ($scope.chartNo >= $scope.maxChart)
						$scope.chartNo = 0;
					$scope.showChart();
				}

				$scope.prevChart = function () {
					console.log("prev chart");

					$scope.chartNo--;
					if ($scope.chartNo < 0)
						$scope.chartNo = $scope.maxChart - 1;
					$scope.showChart();
				}

				$scope.$watch('elementTypeFilter', function () {
					console.log("watch");
					$scope.showChart();
				});

				$scope.$watch('templateFilter', function () {
					console.log("watch");
					$scope.showChart();
				});

				$scope.$watch('typeFilter', function () {
					console.log("watch");
					$scope.showChart();
				});

				$scope.showChart = function () {
					console.log("show chart");
					if (!$scope.dataLoaded)
						return;

					switch ($scope.chartNo) {
						case 0: {
							var totCount = [0, 0];
							var users = [];
							for (b in $scope.results) {
								var binding = $scope.results[b]._id;

								// filter by element type
								if ($scope.elementTypeFilter != "" && binding.elementType != $scope.elementTypeFilter)
									continue;

								// filter by case
								if ($scope.templateFilter != "" && binding.template != $scope.templateFilter)
									continue;

								// filter by semantic type
								if ($scope.typeFilter != "" && $scope.typeFilters[getType($scope.typeFilter, $scope.typeFilters)].indexOf(binding.template) == -1)
									continue;

								// count bindings unless assessment is undefined
								if (binding.assessment != undefined) {
									if (binding.scenario == "SCT")
										totCount[0]++;
									else
										totCount[1]++;
								}

								// collect users in users array
								var user = users.indexOf(binding.user);
								if (user == -1) {
									users.push(binding.user);
								}
							}
							$scope.series = ['SNOMED CT', 'Alternative'];
							$scope.labels = ['Total'];
							$scope.data = [[totCount[0]],
								[totCount[1]]];
							$scope.statistics = "total count = "
							+ (totCount[0] + totCount[1])
							+ ", no. of users = "
							+ users.length;
							$scope.title = "Total count";
							$scope.type = 'Bar';
							break;
						}
						case 1: {
							var assessmentCount = {
								sct: [],
								alt: []
							};
							for (var i = 0; i < 4; i++) {
								assessmentCount.sct[i] = 0;
								assessmentCount.alt[i] = 0;
							}

							for (b in $scope.results) {
								var binding = $scope.results[b]._id;

								// filter by element type
								if ($scope.elementTypeFilter != "" && binding.elementType != $scope.elementTypeFilter)
									continue;

								// filter by cas
								if ($scope.templateFilter != "" && binding.template != $scope.templateFilter)
									continue;

								// filter by semantic type
								if ($scope.typeFilter != "" && $scope.typeFilters[getType($scope.typeFilter, $scope.typeFilters)].indexOf(binding.template) == -1)
									continue;

								if (binding.assessment <= 5) {
									var index = binding.assessment;

									if(index > 1)
										index = index - 2;
									else
										index = index - 1;
									if (binding.scenario == "SCT")
										assessmentCount.sct[index]++;
									else
										assessmentCount.alt[index]++;
								}
							}

							$scope.labels = ['Full+Inferred',
								'Partial', 'No', 'OOS'];
							$scope.series = ['SNOMED CT', 'Alternative'];

							$scope.data = [assessmentCount.sct,
								assessmentCount.alt];

							$scope.type = 'Bar';

							var chi2 = $scope.chi2([
								assessmentCount.sct,
								assessmentCount.alt]);
							var df = 1 * (assessmentCount.sct.length - 1);

							$scope.statistics = "df = " + df
							+ ", chi2 = " + chi2.toFixed(2);
							$scope.title = "Coverge";
							break;
						}
						case 2: {
							var groupCount = [0, 0];
							for (b in $scope.results) {
								var binding = $scope.results[b]._id;
								if (binding.target != undefined) {
									if (binding.scenario == "SCT")
										if (binding.target.indexOf(";") == -1)
											groupCount[0]++;
										else
											groupCount[1]++;
								}
							}
							$scope.labels = ['Single code', 'Grouped'];
							$scope.data = groupCount;
							var groupings = (100 * (groupCount[1] / (groupCount[0] + groupCount[1])))
								.toFixed(2);
							$scope.statistics = "groupings "
							+ groupings + " %";
							$scope.title = "Grouping (SNOMED CT)";
							$scope.type = 'Pie';
							break;
						}
						case 3: {
							var groupCount = [0, 0];
							for (b in $scope.results) {
								var binding = $scope.results[b]._id;
								if (binding.target != undefined) {
									if (binding.scenario == "ALT")
										if (binding.target.indexOf(";") == -1)
											groupCount[0]++;
										else
											groupCount[1]++;
								}
							}
							$scope.labels = ['Single code', 'Grouped'];
							$scope.data = groupCount;
							var groupings = (100 * (groupCount[1] / (groupCount[0] + groupCount[1])))
								.toFixed(2);
							$scope.statistics = "groupings "
							+ groupings + " %";
							$scope.title = "Grouping (Alternative)";
							$scope.type = 'Pie';
							break;
						}
					}
				}

				bindingService.getStats().success(function (data) {
					$scope.results = data;

					$scope.dataLoaded = true;

					$scope.showChart();

				}).error(function () {
					$scope.results = [];
				});

				var getType = function(elem, array) {
					for(var i = 0; i < array.length; i++) {
						if(array[i][0] == elem)
							return i;
					}
					return -1;
				}

				templateService.get().success(function (data) {
					$scope.templates = data;

					for(var i = 0; i < $scope.templates.length; i++) {
						var template = $scope.templates[i];

						if(getType(template.type, $scope.typeFilters) == -1) {
							console.log(i);
							var newType = $scope.typeFilters.push([template.type]);
							$scope.typeFilters[newType - 1].push(template._id);
						}
						else
							$scope.typeFilters[getType(template.type, $scope.typeFilters)].push(template._id);
					}
				}).error(function () {
					$scope.templates = [];
				})

				$scope.chi2 = function (data) { // an n x m array
					var lenX = data.length;
					var lenY = data.reduce(function (a, b) {
						return Math.min(a.length, b.length);
					});

					var expected = [];
					var sumX = [];
					var sumY = [];
					var total = 0;
					for (var i = 0; i < lenY; i++)
						sumX[i] = 0.0;

					for (var iX = 0; iX < lenX; iX++) {
						sumY[iX] = 0.0;
						for (var iY = 0; iY < lenY; iY++) {
							sumY[iX] += data[iX][iY];
							sumX[iY] += data[iX][iY];
						}
						total += sumY[iX];
					}

					for (var iX = 0; iX < lenX; iX++) {
						expected[iX] = [];
						for (var iY = 0; iY < lenY; iY++) {
							expected[iX][iY] = sumX[iY] * sumY[iX] / total;
						}
					}

					var criticalValue = 0.0;
					for (var iX = 0; iX < lenX; iX++) {
						for (var iY = 0; iY < lenY; iY++) {
							var sqr = data[iX][iY]
								- expected[iX][iY];
							criticalValue += sqr * sqr / expected[iX][iY];
						}
					}

					if (criticalValue <= 0.0)
						return 0;

					return criticalValue;

				}

			}]);<commit_msg>removed "out of scope" from coverage diagram<commit_after>angular
	.module('DashboardControllerModule', ['chart.js'])
	.controller(
		'DashboardController',
		[
			'$scope',
			'$location',
			'$window',
			'jwtHelper',
			'BindingService',
			'TemplateService',
			function ($scope, $location, $window, jwtHelper,
				bindingService, templateService) {

				var url = $location.$$absUrl;
				var tokenIndex = url.indexOf("?token=");
				if (tokenIndex != -1) {
					var token = url.substring(url
						.indexOf("?token=") + 7, url.length);
					console.log(token);
					$window.sessionStorage.token = token;
					$scope.user = jwtHelper.decodeToken(token);
				}

				$scope.chartNo = 0;
				$scope.dataLoaded = false;
				$scope.statistics = "";
				$scope.title = "";
				$scope.maxChart = 4;
				$scope.elementTypeFilter = "";
				$scope.templateFilter = "";
				$scope.typeFilter = "";
				$scope.typeFilters = [];

				$scope.nextChart = function () {
					console.log("next chart");

					$scope.chartNo++;
					if ($scope.chartNo >= $scope.maxChart)
						$scope.chartNo = 0;
					$scope.showChart();
				}

				$scope.prevChart = function () {
					console.log("prev chart");

					$scope.chartNo--;
					if ($scope.chartNo < 0)
						$scope.chartNo = $scope.maxChart - 1;
					$scope.showChart();
				}

				$scope.$watch('elementTypeFilter', function () {
					console.log("watch");
					$scope.showChart();
				});

				$scope.$watch('templateFilter', function () {
					console.log("watch");
					$scope.showChart();
				});

				$scope.$watch('typeFilter', function () {
					console.log("watch");
					$scope.showChart();
				});

				$scope.showChart = function () {
					console.log("show chart");
					if (!$scope.dataLoaded)
						return;

					switch ($scope.chartNo) {
						case 0: {
							var totCount = [0, 0];
							var users = [];
							for (b in $scope.results) {
								var binding = $scope.results[b]._id;

								// filter by element type
								if ($scope.elementTypeFilter != "" && binding.elementType != $scope.elementTypeFilter)
									continue;

								// filter by case
								if ($scope.templateFilter != "" && binding.template != $scope.templateFilter)
									continue;

								// filter by semantic type
								if ($scope.typeFilter != "" && $scope.typeFilters[getType($scope.typeFilter, $scope.typeFilters)].indexOf(binding.template) == -1)
									continue;

								// count bindings unless assessment is undefined
								if (binding.assessment != undefined) {
									if (binding.scenario == "SCT")
										totCount[0]++;
									else
										totCount[1]++;
								}

								// collect users in users array
								var user = users.indexOf(binding.user);
								if (user == -1) {
									users.push(binding.user);
								}
							}
							$scope.series = ['SNOMED CT', 'Alternative'];
							$scope.labels = ['Total'];
							$scope.data = [[totCount[0]],
								[totCount[1]]];
							$scope.statistics = "total count = "
							+ (totCount[0] + totCount[1])
							+ ", no. of users = "
							+ users.length;
							$scope.title = "Total count";
							$scope.type = 'Bar';
							break;
						}
						case 1: {
							var assessmentCount = {
								sct: [],
								alt: []
							};
							for (var i = 0; i < 3; i++) {
								assessmentCount.sct[i] = 0;
								assessmentCount.alt[i] = 0;
							}

							for (b in $scope.results) {
								var binding = $scope.results[b]._id;

								// filter by element type
								if ($scope.elementTypeFilter != "" && binding.elementType != $scope.elementTypeFilter)
									continue;

								// filter by cas
								if ($scope.templateFilter != "" && binding.template != $scope.templateFilter)
									continue;

								// filter by semantic type
								if ($scope.typeFilter != "" && $scope.typeFilters[getType($scope.typeFilter, $scope.typeFilters)].indexOf(binding.template) == -1)
									continue;

								if (binding.assessment != 5) {
									var index = binding.assessment;

									if(index > 1)
										index = index - 2;
									else
										index = index - 1;
									if (binding.scenario == "SCT")
										assessmentCount.sct[index]++;
									else
										assessmentCount.alt[index]++;
								}
							}

							$scope.labels = ['Full+Inferred',
								'Partial', 'No'];
							$scope.series = ['SNOMED CT', 'Alternative'];

							$scope.data = [assessmentCount.sct,
								assessmentCount.alt];

							$scope.type = 'Bar';

							var chi2 = $scope.chi2([
								assessmentCount.sct,
								assessmentCount.alt]);
							var df = 1 * (assessmentCount.sct.length - 1);

							$scope.statistics = "df = " + df
							+ ", chi2 = " + chi2.toFixed(2);
							$scope.title = "Coverge";
							break;
						}
						case 2: {
							var groupCount = [0, 0];
							for (b in $scope.results) {
								var binding = $scope.results[b]._id;
								if (binding.target != undefined) {
									if (binding.scenario == "SCT")
										if (binding.target.indexOf(";") == -1)
											groupCount[0]++;
										else
											groupCount[1]++;
								}
							}
							$scope.labels = ['Single code', 'Grouped'];
							$scope.data = groupCount;
							var groupings = (100 * (groupCount[1] / (groupCount[0] + groupCount[1])))
								.toFixed(2);
							$scope.statistics = "groupings "
							+ groupings + " %";
							$scope.title = "Grouping (SNOMED CT)";
							$scope.type = 'Pie';
							break;
						}
						case 3: {
							var groupCount = [0, 0];
							for (b in $scope.results) {
								var binding = $scope.results[b]._id;
								if (binding.target != undefined) {
									if (binding.scenario == "ALT")
										if (binding.target.indexOf(";") == -1)
											groupCount[0]++;
										else
											groupCount[1]++;
								}
							}
							$scope.labels = ['Single code', 'Grouped'];
							$scope.data = groupCount;
							var groupings = (100 * (groupCount[1] / (groupCount[0] + groupCount[1])))
								.toFixed(2);
							$scope.statistics = "groupings "
							+ groupings + " %";
							$scope.title = "Grouping (Alternative)";
							$scope.type = 'Pie';
							break;
						}
					}
				}

				bindingService.getStats().success(function (data) {
					$scope.results = data;

					$scope.dataLoaded = true;

					$scope.showChart();

				}).error(function () {
					$scope.results = [];
				});

				var getType = function(elem, array) {
					for(var i = 0; i < array.length; i++) {
						if(array[i][0] == elem)
							return i;
					}
					return -1;
				}

				templateService.get().success(function (data) {
					$scope.templates = data;

					for(var i = 0; i < $scope.templates.length; i++) {
						var template = $scope.templates[i];

						if(getType(template.type, $scope.typeFilters) == -1) {
							console.log(i);
							var newType = $scope.typeFilters.push([template.type]);
							$scope.typeFilters[newType - 1].push(template._id);
						}
						else
							$scope.typeFilters[getType(template.type, $scope.typeFilters)].push(template._id);
					}
				}).error(function () {
					$scope.templates = [];
				})

				$scope.chi2 = function (data) { // an n x m array
					var lenX = data.length;
					var lenY = data.reduce(function (a, b) {
						return Math.min(a.length, b.length);
					});

					var expected = [];
					var sumX = [];
					var sumY = [];
					var total = 0;
					for (var i = 0; i < lenY; i++)
						sumX[i] = 0.0;

					for (var iX = 0; iX < lenX; iX++) {
						sumY[iX] = 0.0;
						for (var iY = 0; iY < lenY; iY++) {
							sumY[iX] += data[iX][iY];
							sumX[iY] += data[iX][iY];
						}
						total += sumY[iX];
					}

					for (var iX = 0; iX < lenX; iX++) {
						expected[iX] = [];
						for (var iY = 0; iY < lenY; iY++) {
							expected[iX][iY] = sumX[iY] * sumY[iX] / total;
						}
					}

					var criticalValue = 0.0;
					for (var iX = 0; iX < lenX; iX++) {
						for (var iY = 0; iY < lenY; iY++) {
							var sqr = data[iX][iY]
								- expected[iX][iY];
							criticalValue += sqr * sqr / expected[iX][iY];
						}
					}

					if (criticalValue <= 0.0)
						return 0;

					return criticalValue;

				}

			}]);<|endoftext|>


<commit_before>module.exports = function (sch) {
  var noComments = function (line) {
    var i = line.indexOf('//')
    return i > -1 ? line.slice(0, i) : line
  }

  var noMultilineComments = function () {
    var inside = false
    return function (token) {
      if (token === '/*') {
        inside = true
        return false
      }
      if (token === '*/') {
        inside = false
        return false
      }
      return !inside
    }
  }

  var trim = function (line) {
    return line.trim()
  }

  return sch
    .replace(/([;,{}=\[\]<>]|\/\*|\*\/)/g, ' $1 ')
    .split(/\n/)
    .map(trim)
    .filter(Boolean)
    .map(noComments)
    .filter(Boolean)
    .join('\n')
    .split(/\s+|\n+/gm)
    .filter(noMultilineComments())
}
<commit_msg>Fix tokenizing of comment after closing brace of last message<commit_after>module.exports = function (sch) {
  var noComments = function (line) {
    var i = line.indexOf('//')
    return i > -1 ? line.slice(0, i) : line
  }

  var noMultilineComments = function () {
    var inside = false
    return function (token) {
      if (token === '/*') {
        inside = true
        return false
      }
      if (token === '*/') {
        inside = false
        return false
      }
      return !inside
    }
  }

  var trim = function (line) {
    return line.trim()
  }

  return sch
    .replace(/([;,{}=\[\]<>]|\/\*|\*\/)/g, ' $1 ')
    .split(/\n/)
    .map(trim)
    .filter(Boolean)
    .map(noComments)
    .map(trim)
    .filter(Boolean)
    .join('\n')
    .split(/\s+|\n+/gm)
    .filter(noMultilineComments())
}
<|endoftext|>


<commit_before>Cards.module('Set.Details', function(Details, App) {
	Details.ItemView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item",
		className: "item",
		events: {
			"click a": "linkClicked",
			"click div.box": "cardClicked"
		},
		cardClicked: function(ev) {
			ev.preventDefault();

			var front = $(ev.currentTarget).find('div.front');
			var back = $(ev.currentTarget).find('div.back');

			if(ev.target.nodeName == "DIV" || ev.target.nodeName == "SPAN") {
				front.toggle();
				back.toggle();
				this.$el.find("div.cardContent.back").toggleClass('active');
				this.$el.find("div.cardContent.front").toggleClass('active');
			}

			console.log(this.$el.find("div.cardContent.front"));
		},
		linkClicked: function(ev) {
			ev.preventDefault();
			console.log("link");
		}
	});

	Details.EmptyView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item-empty",
		className: "empty-item"
	});

	Details.DetailsView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.EmptyView,
		itemView: Details.ItemView,
		itemViewContainer: "div.carousel-inner",
		template: "#set-details-collection",
		ui: {
			modalView: "#pictureModal"
		},
		events: {
			"click a.carousel-control": "cycleCarousel",
			"click button.learn": "learnClicked",
			"click button.memo": "memoClicked",
			"click button.play-meteor": "playMeteor",
			"click a.btn-editCard": "editClicked",
			"click a.btn-showPictureModal": "showModal",
			"click a.btn-deleteCard": "deleteClicked"
		},
		playMeteor: function(ev) {
			App.trigger("play:meteor", this.model.get("id"));
		},
		showModal: function(ev) {
			ev.preventDefault();

			this.showPictureModal();
		},
		editClicked: function(ev) {
			ev.preventDefault();

			//cardid holen
			var cardId = $("div.item.active").children(".box").attr("data-id");

			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $("div.item.active").children(".box").attr("data-id");

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		cycleCarousel: function(ev) {
			ev.preventDefault();
			this.turnCardtoFront(ev);

			if($(ev.currentTarget).hasClass("left")) {
				this.$el.find(":first-child").carousel("prev");
			} else if($(ev.currentTarget).hasClass("right")) {
				this.$el.find(":first-child").carousel("next");
			}
		},

		turnCardtoFront: function(ev) {
			ev.preventDefault();

			var front = this.$el.find("div.cardContent.front");
			var back = this.$el.find("div.cardContent.back");

			if(back.hasClass('active')){
				console.log("togglme");
				front.toggle();
				back.toggle();
				front.toggleClass('active');
				back.toggleClass('active');
			}
		},

		showPictureModal: function() {
			var cardId = $("div.item.active").children(".box").attr("data-id");
			var actualCard = this.collection.get(cardId);
			var cardContent = null;

			if($("div.item.active").find("div.centered.front").hasClass('active')){
				cardContent = actualCard.get("front");
			} else if($("div.item.active").find("div.centered.back").hasClass('active')) {
				cardContent = actualCard.get("back");
			}

			var imgElem = $(document.createElement('img'));
			imgElem.attr('src', cardContent.picture);
			imgElem.attr('title', cardContent.text);
			imgElem.attr('alt', cardContent.text);
			imgElem.attr('width', "538px");

			$("#setdetails-pictureModal-body").empty();
			$("#setdetails-pictureModal-body").append(imgElem);

			this.ui.modalView.modal('show');
		},
		learnClicked: function(ev) {
			App.trigger("set:learn", this.model.get("_id"));
		},
		memoClicked: function(ev) {
			App.trigger("set:memo", this.model.get("_id"));
		},
		onRender: function() {

			if(this.collection.length == 0) {
				this.$el.find("a.carousel-control").hide();
				this.$el.find("button.play-meteor").prop('disabled', true);
				this.$el.find("button.learn").prop('disabled', true);
				this.$el.find("button.memo").prop('disabled', true);
			}

			this.$el.find("div.item").first().addClass("active");

			var pickerContainer = this.$el.find("ol.carousel-indicators").first();
			for(var i = 0; i < this.collection.length; i++) {
				var indicatorElem = $("

").attr("data-slide-to", i);
				if(i === 0) indicatorElem.addClass("active");

				pickerContainer.append(indicatorElem);
			}

			this.$el.find(':first-child').carousel({ interval: false });

			$('#btnToCardLayout').addClass("active");
			$('#btnToListLayout').removeClass("active");

			this.$el.find("div.cardContent.back").removeClass('active');
			this.$el.find("div.cardContent.front").addClass('active');

			//...
			if(this.collection.length !== 0) {
				var cardId = $("div.item.active").children(".box").attr("data-id");
				var actualCard = this.collection.get(cardId);
				//if(actualCard.)
				//console.log(actualCard.get("front"));
				this.$el.find("a.btn-showPictureModal").show();
			}

			var usr = $.cookie('usr');
			$("#usr-name").text();
			$.get("/score/"+usr.username+"/"+this.model.get("_id"), function( data ) {
				$("#meteor-set-points").text(data.score);
			}).fail(function(){
				console.log("yeah");
			});
		},
		onShow: function() {
		var that = this;
		var tweak = 200;

		    $.fn.resizeText = function(){
		      var size = parseInt($(this).css("fontSize"));
		      var html = $(this).html();
		      var textLength = html.length;
		      var span = "" + html + "";
		      that.$el.append(span);
		      var width = that.$el.find('span:last').width();
		      console.log(that.$el.find('span:last'));
		      console.log(width);
		      console.log($(this).width());
		      var newSize = ($(this).width()-tweak)/(width)*size;
		      console.log(newSize);
		      if (newSize < "45"){
		      	console.log("edited size enabled");
		      	$(this).css("fontSize", newSize);
		      }
		      return width;
		    };

		    this.$el.find("div.front").resizeText();
		}
	});

	Details.ListItem = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
	    template: "#set-details-listitem"
	});

	Details.ListEmptyView = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
		template: "#set-details-listitem-empty",
		className: "empty-listitem"
	});

	Details.DetailsListView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.ListEmptyView,
		tagName: "table",
		className: "table table-bordered table-striped table-hover",
		itemView: Details.ListItem,
		itemViewContainer: "tbody",
		template: "#set-details-list",
		events: {
			"click a.btn-listEditCard": "editClicked",
			"click a.btn-listDeleteCard": "deleteClicked"
		},
		editClicked: function(ev) {
			ev.preventDefault();

			var cardId = $(ev.currentTarget).attr("data-id")
			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $(ev.currentTarget).attr("data-id")

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		onRender: function(ev) {
			$('#btnToListLayout').addClass("active");
			$('#btnToCardLayout').removeClass("active");
		}
	});
});<commit_msg>turncard fix<commit_after>Cards.module('Set.Details', function(Details, App) {
	Details.ItemView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item",
		className: "item",
		events: {
			"click a": "linkClicked",
			"click div.box": "cardClicked"
		},
		cardClicked: function(ev) {
			ev.preventDefault();

			var front = $(ev.currentTarget).find('div.front');
			var back = $(ev.currentTarget).find('div.back');

			if(ev.target.nodeName == "DIV" || ev.target.nodeName == "SPAN") {
				front.toggle();
				back.toggle();
				this.$el.find("div.cardContent.back").toggleClass('active');
				this.$el.find("div.cardContent.front").toggleClass('active');
			}

			console.log(this.$el.find("div.cardContent.front"));
		},
		linkClicked: function(ev) {
			ev.preventDefault();
			console.log("link");
		}
	});

	Details.EmptyView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item-empty",
		className: "empty-item"
	});

	Details.DetailsView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.EmptyView,
		itemView: Details.ItemView,
		itemViewContainer: "div.carousel-inner",
		template: "#set-details-collection",
		ui: {
			modalView: "#pictureModal"
		},
		events: {
			"click a.carousel-control": "cycleCarousel",
			"click button.learn": "learnClicked",
			"click button.memo": "memoClicked",
			"click button.play-meteor": "playMeteor",
			"click a.btn-editCard": "editClicked",
			"click a.btn-showPictureModal": "showModal",
			"click a.btn-deleteCard": "deleteClicked"
		},
		playMeteor: function(ev) {
			App.trigger("play:meteor", this.model.get("id"));
		},
		showModal: function(ev) {
			ev.preventDefault();

			this.showPictureModal();
		},
		editClicked: function(ev) {
			ev.preventDefault();

			//cardid holen
			var cardId = $("div.item.active").children(".box").attr("data-id");

			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $("div.item.active").children(".box").attr("data-id");

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		cycleCarousel: function(ev) {
			ev.preventDefault();
			this.turnCardtoFront(ev);

			if($(ev.currentTarget).hasClass("left")) {
				this.$el.find(":first-child").carousel("prev");
			} else if($(ev.currentTarget).hasClass("right")) {
				this.$el.find(":first-child").carousel("next");
			}
		},

		turnCardtoFront: function(ev) {
			ev.preventDefault();

			var front = $("div.item.active").find("div.centered.front")
			var back = $("div.item.active").find("div.centered.back")

			if(back.hasClass('active')){
				console.log("togglme");
				front.toggle();
				back.toggle();
				front.toggleClass('active');
				back.toggleClass('active');
			}
		},

		showPictureModal: function() {
			var cardId = $("div.item.active").children(".box").attr("data-id");
			var actualCard = this.collection.get(cardId);
			var cardContent = null;

			if($("div.item.active").find("div.centered.front").hasClass('active')){
				cardContent = actualCard.get("front");
			} else if($("div.item.active").find("div.centered.back").hasClass('active')) {
				cardContent = actualCard.get("back");
			}

			var imgElem = $(document.createElement('img'));
			imgElem.attr('src', cardContent.picture);
			imgElem.attr('title', cardContent.text);
			imgElem.attr('alt', cardContent.text);
			imgElem.attr('width', "538px");

			$("#setdetails-pictureModal-body").empty();
			$("#setdetails-pictureModal-body").append(imgElem);

			this.ui.modalView.modal('show');
		},
		learnClicked: function(ev) {
			App.trigger("set:learn", this.model.get("_id"));
		},
		memoClicked: function(ev) {
			App.trigger("set:memo", this.model.get("_id"));
		},
		onRender: function() {

			if(this.collection.length == 0) {
				this.$el.find("a.carousel-control").hide();
				this.$el.find("button.play-meteor").prop('disabled', true);
				this.$el.find("button.learn").prop('disabled', true);
				this.$el.find("button.memo").prop('disabled', true);
			}

			this.$el.find("div.item").first().addClass("active");

			var pickerContainer = this.$el.find("ol.carousel-indicators").first();
			for(var i = 0; i < this.collection.length; i++) {
				var indicatorElem = $("

").attr("data-slide-to", i);
				if(i === 0) indicatorElem.addClass("active");

				pickerContainer.append(indicatorElem);
			}

			this.$el.find(':first-child').carousel({ interval: false });

			$('#btnToCardLayout').addClass("active");
			$('#btnToListLayout').removeClass("active");

			this.$el.find("div.cardContent.back").removeClass('active');
			this.$el.find("div.cardContent.front").addClass('active');

			//...
			if(this.collection.length !== 0) {
				var cardId = $("div.item.active").children(".box").attr("data-id");
				var actualCard = this.collection.get(cardId);
				//if(actualCard.)
				//console.log(actualCard.get("front"));
				this.$el.find("a.btn-showPictureModal").show();
			}

			var usr = $.cookie('usr');
			$("#usr-name").text();
			$.get("/score/"+usr.username+"/"+this.model.get("_id"), function( data ) {
				$("#meteor-set-points").text(data.score);
			}).fail(function(){
				console.log("yeah");
			});
		},
		onShow: function() {
		var that = this;
		var tweak = 200;

		    $.fn.resizeText = function(){
		      var size = parseInt($(this).css("fontSize"));
		      var html = $(this).html();
		      var textLength = html.length;
		      var span = "" + html + "";
		      that.$el.append(span);
		      var width = that.$el.find('span:last').width();
		      console.log(that.$el.find('span:last'));
		      console.log(width);
		      console.log($(this).width());
		      var newSize = ($(this).width()-tweak)/(width)*size;
		      console.log(newSize);
		      if (newSize < "45"){
		      	console.log("edited size enabled");
		      	$(this).css("fontSize", newSize);
		      }
		      return width;
		    };

		    this.$el.find("div.front").resizeText();
		}
	});

	Details.ListItem = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
	    template: "#set-details-listitem"
	});

	Details.ListEmptyView = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
		template: "#set-details-listitem-empty",
		className: "empty-listitem"
	});

	Details.DetailsListView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.ListEmptyView,
		tagName: "table",
		className: "table table-bordered table-striped table-hover",
		itemView: Details.ListItem,
		itemViewContainer: "tbody",
		template: "#set-details-list",
		events: {
			"click a.btn-listEditCard": "editClicked",
			"click a.btn-listDeleteCard": "deleteClicked"
		},
		editClicked: function(ev) {
			ev.preventDefault();

			var cardId = $(ev.currentTarget).attr("data-id")
			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $(ev.currentTarget).attr("data-id")

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		onRender: function(ev) {
			$('#btnToListLayout').addClass("active");
			$('#btnToCardLayout').removeClass("active");
		}
	});
});<|endoftext|>


<commit_before>'use strict';

angular.module('core').filter('yesNo', function (){
  return function (input) {
    return input ? "Yes" : "No";
  }
});<commit_msg>filter yes no error fix<commit_after>'use strict';

angular.module('core').filter('yesNo', function (){
  return function (input) {
    return input ? 'Yes' : 'No';
  }
});<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require("fs");
var glob = require("glob");
var path = require('path');
var Properties = require("../util/properties");
var log4js = require("log4js");
var LibManager = require('../util/libmanager');
var FileUtil = require("../util/fileutil");
var ErrorManager = require("../util/errormanager");

function ArrowSetup(config, argv) {
    this.config = config;
    this.argv = argv;
}

ArrowSetup.prototype.setup = function () {
    this.setuplog4js();
    this.setupReportDir();
    this.setupDefaultDriverName();
    this.setupTestEngine();
    this.setupDefaultLib();
    this.setupHeadlessParam();
    this.setupCapabilities();
    this.setupMisc();
    this.setupReplaceParam();
    this.setupDefaultParam();
    this.errorCheck(); // keep this as last function call for checking errors.

};

ArrowSetup.prototype.setupReplaceParam = function () {
    if (this.argv.replaceParamJSON) {
        this.config.replaceParamJSON = this.argv.replaceParamJSON;
    }
};

ArrowSetup.prototype.setupDefaultParam = function () {
    if (this.argv.defaultParamJSON) {
        this.config.defaultParamJSON = this.argv.defaultParamJSON;
    }
};

ArrowSetup.prototype.errorCheck = function () {
    var self = this, em = ErrorManager.getInstance(),
    Environment = function() {
        if (self.argv.argv.cooked) {
            // em.errorLog("self.argv.argv.cooked {0}",  JSON.stringify(self.argv.argv.cooked));
            var cooked = JSON.stringify(self.argv.argv.cooked), proc = self.mock || process;
            cooked.replace(/"--context","([\w\W]*?)"/, function (match, context) {
                // em.errorLog("match is {0}, context is {1}", match, context);
                context.replace(/environment:([\w\W]*)/, function (match, env) {
                    // em.errorLog("match is {0}, env is {1}", match, env);
                    if (self.dimensions[0].environment[env] === undefined) {
                        em.errorLog(1000, env, self.dimensionsFile);
                        proc.exit(1);
                    } else {
                        self.environment = env;
                    }
                });
            });
        }
    },
    Dimensions = function() {
        // To Do : should check dimensions file with Json schema
        // em.errorLog("config {0} argv {1}", JSON.stringify(self.config), JSON.stringify(self.argv));
        var dimensions = self.argv.dimensions || self.config.dimensions || "", dimJson, i = 0, proc = self.mock || process,
            errorMessage, argv = self.argv.argv || {}, remain = JSON.stringify(argv.remain) || "",
            dimensionsExist = function () {
                return remain.match(/"[\w\W]*\.json"/) && dimensions.length > 0;
            };

        if (dimensionsExist()) {
            try {
                self.dimensionsFile = dimensions;
                dimJson = JSON.parse(fs.readFileSync(dimensions, "utf-8"));
            } catch (e) {
                errorMessage = e.message;
            }
            if (dimJson && dimJson.length > 0 && dimJson[i].dimensions) {
                self.dimensions = dimJson[i].dimensions;
                // em.errorLog("dimensions {0}", JSON.stringify(self.dimensions));
            } else {
                em.errorLog(1001, dimensions, errorMessage || JSON.stringify(dimJson));
                proc.exit(1);
            }
            Environment();
        }
    };

    em.logger = self.mock || em.logger;
    Dimensions();
};

ArrowSetup.prototype.setupReportDir = function () {

    global.reportFolder = "";
    // To generate the reports, if either report is true or reportFolder is passed
    if (this.argv.reportFolder || true === this.argv.report) {

        var fileUtil = new FileUtil(),
            targetFolderPath,
            reportFolderPath;

        // If reportFolder is passed in the argument,
        if (this.argv.reportFolder) {
            targetFolderPath =  path.resolve(global.workingDirectory, this.argv.reportFolder, 'arrow-target');
        } else {
            // Report folder not passed by the user
            // By default, reports shall go under arrow-target/reports
            targetFolderPath =  path.resolve(global.workingDirectory, 'arrow-target');
        }

        // Cleanup report folder if keepTestReport set to false or undefined
        if (this.argv.keepTestReport === undefined || false === this.argv.keepTestReport) {
            fileUtil.removeDirectory(targetFolderPath);
        }

        reportFolderPath = path.resolve(targetFolderPath, 'arrow-report');

        fileUtil.createDirectory(reportFolderPath);

        this.argv.reportFolder = targetFolderPath;
        global.reportFolder = this.argv.reportFolder || "";

    }

};

ArrowSetup.prototype.setupMisc = function () {

    if (this.argv.coverage !== undefined) {
        this.config.coverage = this.argv.coverage;
    }

    if (this.argv.report === undefined && this.config.report) {
        this.argv.report = this.config.report;
    }

    if (this.argv.dimensions) {
        this.argv.dimensions = path.resolve(global.workingDirectory, this.argv.dimensions);
        this.config.dimensions = this.argv.dimensions;
    }
};

ArrowSetup.prototype.setuplog4js = function () {
    var logLevel;
    logLevel = this.config["logLevel"];
    log4js.setGlobalLogLevel(logLevel);
    log4js.restoreConsole();
    this.logger = log4js.getLogger("ArrowSetup");
};

ArrowSetup.prototype.setupDefaultDriverName = function () {
    if (!this.argv.driver) {
        // turn on reuseSession, if browser is being reused
        // adding support for "reuse-" too, just in case if a null version is passed with browser.
        if ("reuse" === this.argv.browser || "reuse-" === this.argv.browser) {
            this.argv.reuseSession = true;
            delete this.argv.browser;
        }

        if (this.argv.reuseSession) {
            this.argv.driver = "selenium";
        }
    }

    // setup the selenium host using the auto hookup if possible
    this.setupSeleniumHost();
};

ArrowSetup.prototype.setupSeleniumHost = function () {
    var wdHubHost,
        wdStatusFile = "/tmp/arrow_sel_server.status";

    // setup the selenium host using the auto hookup if possible
    wdHubHost = this.config["seleniumHost"];
    if (0 === wdHubHost.length) {
        // check if we have a hooked up server
        try {
            fs.statSync(wdStatusFile).isFile();
            wdHubHost = fs.readFileSync(wdStatusFile, "utf-8");
        } catch (ex) {
        }

        // final default
        if (wdHubHost.length === 0) {
            wdHubHost = "http://localhost:4444/wd/hub";
        }
        this.config["seleniumHost"] = wdHubHost;
    }

};

ArrowSetup.prototype.setupDefaultLib = function () {
    this.argv.lib = new LibManager().getAllCommonLib(this.config, this.argv.lib);
    this.logger.debug("Commandline + Common Libs for Test :" + this.argv.lib);
};

ArrowSetup.prototype.setupHeadlessParam = function () {
    var hd,
        results,
        ext;

    if (!this.argv.argv.remain[0]) {
        return;
    }

    hd = this.argv.argv.remain[0];

    results = glob.sync(hd);
    this.logger.info("Glob result: " + results);

    if (0 === results.length) {
        this.logger.error("ERROR : No Test or Descriptor Found, while looking for : " + hd);
        process.exit(1);
    }

    ext = path.extname(results[0]);
    // check the first file to determine the type
    if (".json" === ext) {
        this.config.arrDescriptor = results;
    } else if ((".js" === ext) || (".html" === ext)) {
        if (results.length > 1) {
            this.argv.tests = results;
        } else {
            this.argv.test = results[0];
        }
    } else {
        this.logger.fatal("Unknown test file type " + results[0]);
        process.exit(0);
    }
};

ArrowSetup.prototype.setupCapabilities = function () {
    if (this.argv.capabilities) {
        this.config.capabilities = this.argv.capabilities;
    }
};

ArrowSetup.prototype.setupTestEngine = function () {
    this.config.engine = "yui";
    if (this.argv.engine) {
        this.config.engine = this.argv.engine;
    }
    if (this.argv.engineConfig) {
        try {
            this.config.engineConfig = this.argv.engineConfig;
            if (fs.statSync(this.argv.engineConfig).isFile()) {
                //get absolute path before chdir
                this.config.engineConfig = path.resolve("", this.argv.engineConfig);
            }
        } catch (e) {
        }
    }
};

module.exports = ArrowSetup;

<commit_msg>Fixing connection refused error when --driver=selenium is used when browser=reuse<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require("fs");
var glob = require("glob");
var path = require('path');
var Properties = require("../util/properties");
var log4js = require("log4js");
var LibManager = require('../util/libmanager');
var FileUtil = require("../util/fileutil");
var ErrorManager = require("../util/errormanager");

function ArrowSetup(config, argv) {
    this.config = config;
    this.argv = argv;
}

ArrowSetup.prototype.setup = function () {
    this.setuplog4js();
    this.setupReportDir();
    this.setupDefaultDriverName();
    this.setupTestEngine();
    this.setupDefaultLib();
    this.setupHeadlessParam();
    this.setupCapabilities();
    this.setupMisc();
    this.setupReplaceParam();
    this.setupDefaultParam();
    this.errorCheck(); // keep this as last function call for checking errors.

};

ArrowSetup.prototype.setupReplaceParam = function () {
    if (this.argv.replaceParamJSON) {
        this.config.replaceParamJSON = this.argv.replaceParamJSON;
    }
};

ArrowSetup.prototype.setupDefaultParam = function () {
    if (this.argv.defaultParamJSON) {
        this.config.defaultParamJSON = this.argv.defaultParamJSON;
    }
};

ArrowSetup.prototype.errorCheck = function () {
    var self = this, em = ErrorManager.getInstance(),
    Environment = function() {
        if (self.argv.argv.cooked) {
            // em.errorLog("self.argv.argv.cooked {0}",  JSON.stringify(self.argv.argv.cooked));
            var cooked = JSON.stringify(self.argv.argv.cooked), proc = self.mock || process;
            cooked.replace(/"--context","([\w\W]*?)"/, function (match, context) {
                // em.errorLog("match is {0}, context is {1}", match, context);
                context.replace(/environment:([\w\W]*)/, function (match, env) {
                    // em.errorLog("match is {0}, env is {1}", match, env);
                    if (self.dimensions[0].environment[env] === undefined) {
                        em.errorLog(1000, env, self.dimensionsFile);
                        proc.exit(1);
                    } else {
                        self.environment = env;
                    }
                });
            });
        }
    },
    Dimensions = function() {
        // To Do : should check dimensions file with Json schema
        // em.errorLog("config {0} argv {1}", JSON.stringify(self.config), JSON.stringify(self.argv));
        var dimensions = self.argv.dimensions || self.config.dimensions || "", dimJson, i = 0, proc = self.mock || process,
            errorMessage, argv = self.argv.argv || {}, remain = JSON.stringify(argv.remain) || "",
            dimensionsExist = function () {
                return remain.match(/"[\w\W]*\.json"/) && dimensions.length > 0;
            };

        if (dimensionsExist()) {
            try {
                self.dimensionsFile = dimensions;
                dimJson = JSON.parse(fs.readFileSync(dimensions, "utf-8"));
            } catch (e) {
                errorMessage = e.message;
            }
            if (dimJson && dimJson.length > 0 && dimJson[i].dimensions) {
                self.dimensions = dimJson[i].dimensions;
                // em.errorLog("dimensions {0}", JSON.stringify(self.dimensions));
            } else {
                em.errorLog(1001, dimensions, errorMessage || JSON.stringify(dimJson));
                proc.exit(1);
            }
            Environment();
        }
    };

    em.logger = self.mock || em.logger;
    Dimensions();
};

ArrowSetup.prototype.setupReportDir = function () {

    global.reportFolder = "";
    // To generate the reports, if either report is true or reportFolder is passed
    if (this.argv.reportFolder || true === this.argv.report) {

        var fileUtil = new FileUtil(),
            targetFolderPath,
            reportFolderPath;

        // If reportFolder is passed in the argument,
        if (this.argv.reportFolder) {
            targetFolderPath =  path.resolve(global.workingDirectory, this.argv.reportFolder, 'arrow-target');
        } else {
            // Report folder not passed by the user
            // By default, reports shall go under arrow-target/reports
            targetFolderPath =  path.resolve(global.workingDirectory, 'arrow-target');
        }

        // Cleanup report folder if keepTestReport set to false or undefined
        if (this.argv.keepTestReport === undefined || false === this.argv.keepTestReport) {
            fileUtil.removeDirectory(targetFolderPath);
        }

        reportFolderPath = path.resolve(targetFolderPath, 'arrow-report');

        fileUtil.createDirectory(reportFolderPath);

        this.argv.reportFolder = targetFolderPath;
        global.reportFolder = this.argv.reportFolder || "";

    }

};

ArrowSetup.prototype.setupMisc = function () {

    if (this.argv.coverage !== undefined) {
        this.config.coverage = this.argv.coverage;
    }

    if (this.argv.report === undefined && this.config.report) {
        this.argv.report = this.config.report;
    }

    if (this.argv.dimensions) {
        this.argv.dimensions = path.resolve(global.workingDirectory, this.argv.dimensions);
        this.config.dimensions = this.argv.dimensions;
    }
};

ArrowSetup.prototype.setuplog4js = function () {
    var logLevel;
    logLevel = this.config["logLevel"];
    log4js.setGlobalLogLevel(logLevel);
    log4js.restoreConsole();
    this.logger = log4js.getLogger("ArrowSetup");
};

ArrowSetup.prototype.setupDefaultDriverName = function () {

    // turn on reuseSession, if browser is being reused
    // adding support for "reuse-" too, just in case if a null version is passed with browser.
    if ("reuse" === this.argv.browser || "reuse-" === this.argv.browser) {
        this.argv.reuseSession = true;

        if (!this.argv.driver){
            this.argv.driver = "selenium";
        }
        delete this.argv.browser;
    }

    // setup the selenium host using the auto hookup if possible
    this.setupSeleniumHost();
};

ArrowSetup.prototype.setupSeleniumHost = function () {
    var wdHubHost,
        wdStatusFile = "/tmp/arrow_sel_server.status";

    // setup the selenium host using the auto hookup if possible
    wdHubHost = this.config["seleniumHost"];
    if (0 === wdHubHost.length) {
        // check if we have a hooked up server
        try {
            fs.statSync(wdStatusFile).isFile();
            wdHubHost = fs.readFileSync(wdStatusFile, "utf-8");
        } catch (ex) {
        }

        // final default
        if (wdHubHost.length === 0) {
            wdHubHost = "http://localhost:4444/wd/hub";
        }
        this.config["seleniumHost"] = wdHubHost;
    }

};

ArrowSetup.prototype.setupDefaultLib = function () {
    this.argv.lib = new LibManager().getAllCommonLib(this.config, this.argv.lib);
    this.logger.debug("Commandline + Common Libs for Test :" + this.argv.lib);
};

ArrowSetup.prototype.setupHeadlessParam = function () {
    var hd,
        results,
        ext;

    if (!this.argv.argv.remain[0]) {
        return;
    }

    hd = this.argv.argv.remain[0];

    results = glob.sync(hd);
    this.logger.info("Glob result: " + results);

    if (0 === results.length) {
        this.logger.error("ERROR : No Test or Descriptor Found, while looking for : " + hd);
        process.exit(1);
    }

    ext = path.extname(results[0]);
    // check the first file to determine the type
    if (".json" === ext) {
        this.config.arrDescriptor = results;
    } else if ((".js" === ext) || (".html" === ext)) {
        if (results.length > 1) {
            this.argv.tests = results;
        } else {
            this.argv.test = results[0];
        }
    } else {
        this.logger.fatal("Unknown test file type " + results[0]);
        process.exit(0);
    }
};

ArrowSetup.prototype.setupCapabilities = function () {
    if (this.argv.capabilities) {
        this.config.capabilities = this.argv.capabilities;
    }
};

ArrowSetup.prototype.setupTestEngine = function () {
    this.config.engine = "yui";
    if (this.argv.engine) {
        this.config.engine = this.argv.engine;
    }
    if (this.argv.engineConfig) {
        try {
            this.config.engineConfig = this.argv.engineConfig;
            if (fs.statSync(this.argv.engineConfig).isFile()) {
                //get absolute path before chdir
                this.config.engineConfig = path.resolve("", this.argv.engineConfig);
            }
        } catch (e) {
        }
    }
};

module.exports = ArrowSetup;

<|endoftext|>


<commit_before>var _ = require('lodash');
var path = require('path');

var platforms = {
    LINUX: 'linux',
    LINUX_32: 'linux_32',
    LINUX_64: 'linux_64',
    OSX: 'osx',
    OSX_32: 'osx_32',
    OSX_64: 'osx_64',
    WINDOWS: 'windows',
    WINDOWS_32: 'windows_32',
    WINDOWS_64: 'windows_64',

    detect: detectPlatform
};

// Reduce a platfrom id to its type
function platformToType(platform) {
    return _.first(platform.split('_'));
}

// Detect and normalize the platform name
function detectPlatform(platform) {
    var name = platform.toLowerCase();
    var prefix = "", suffix = "";

    // Detect NuGet/Squirrel.Windows files
    if (name == 'releases' || path.extname(name) == '.nupkg') return platforms.WINDOWS_32;

    // Detect prefix: osx, widnows or linux
    if (_.contains(name, 'win')
        || path.extname(name) == '.exe') prefix = platforms.WINDOWS;

    if (_.contains(name, 'linux')
        || _.contains(name, 'ubuntu')
        || path.extname(name) == '.deb'
        || path.extname(name) == '.rpm') prefix = platforms.LINUX;

    if (_.contains(name, 'mac')
        || _.contains(name, 'osx')
        || name.indexOf('darwin') >= 0
        || path.extname(name) == '.dmg') prefix = platforms.OSX;

    // Detect suffix: 32 or 64
    if (_.contains(name, '32')
        || _.contains(name, 'ia32')
        || _.contains(name, 'i386')) suffix = '32';
    if (_.contains(name, '64') || _.contains(name, 'x64') || _.contains(name, 'amd64')) suffix = '64';

    suffix = suffix || (prefix == platforms.OSX? '64' : '32');
    return _.compact([prefix, suffix]).join('_');
}

// Satisfies a platform
function satisfiesPlatform(platform, list) {
    if (_.contains(list, platform)) return true;

    // By default, user 32bits version
    if (_.contains(list+'_32', platform)) return true;

    return false;
}

// Resolve a platform for a version
function resolveForVersion(version, platformID, opts) {
    opts = _.defaults(opts || {}, {
        // Order for filetype
        filePreference: ['.exe', '.dmg', '.deb', '.rpm', '.zip', '.nupkg'],
        wanted: null
    });

    // Prepare file prefs
    if (opts.wanted) opts.filePreference = _.uniq([opts.wanted].concat(opts.filePreference));

    // Normalize platform id
    platformID = detectPlatform(platformID);

    return _.chain(version.platforms)
        .filter(function(pl) {
            return pl.type.indexOf(platformID) === 0;
        })
        .sort(function(p1, p2) {
            var result = 0;

            // Compare by arhcitecture ("osx_64" > "osx")
            if (p1.type.length > p2.type.length) result = -1;
            else if (p2.type.length > p1.type.length) result = 1;

            // Order by file type if samee architecture
            if (result == 0) {
                var ext1 = path.extname(p1.filename);
                var ext2 = path.extname(p2.filename);
                var pos1 = _.indexOf(opts.filePreference, ext1);
                var pos2 = _.indexOf(opts.filePreference, ext2);

                pos1 = pos1 == -1? opts.filePreference.length : pos1;
                pos2 = pos2 == -1? opts.filePreference.length : pos2;

                if (pos1 < pos2) result = -1;
                else if (pos2 < pos1) result = 1;
            }
            return result;
        })
        .first()
        .value()
}

module.exports = platforms;
module.exports.detect = detectPlatform;
module.exports.satisfies = satisfiesPlatform;
module.exports.toType = platformToType;
module.exports.resolve = resolveForVersion;
<commit_msg>Add tar.gz extensions to lib/utils/platforms.js<commit_after>var _ = require('lodash');
var path = require('path');

var platforms = {
    LINUX: 'linux',
    LINUX_32: 'linux_32',
    LINUX_64: 'linux_64',
    OSX: 'osx',
    OSX_32: 'osx_32',
    OSX_64: 'osx_64',
    WINDOWS: 'windows',
    WINDOWS_32: 'windows_32',
    WINDOWS_64: 'windows_64',

    detect: detectPlatform
};

// Reduce a platfrom id to its type
function platformToType(platform) {
    return _.first(platform.split('_'));
}

// Detect and normalize the platform name
function detectPlatform(platform) {
    var name = platform.toLowerCase();
    var prefix = "", suffix = "";

    // Detect NuGet/Squirrel.Windows files
    if (name == 'releases' || path.extname(name) == '.nupkg') return platforms.WINDOWS_32;

    // Detect prefix: osx, widnows or linux
    if (_.contains(name, 'win')
        || path.extname(name) == '.exe') prefix = platforms.WINDOWS;

    if (_.contains(name, 'linux')
        || _.contains(name, 'ubuntu')
        || path.extname(name) == '.deb'
        || path.extname(name) == '.rpm'
        || path.extname(name) == '.tgz'
        || path.extname(name) == '.tar.gz') prefix = platforms.LINUX;

    if (_.contains(name, 'mac')
        || _.contains(name, 'osx')
        || name.indexOf('darwin') >= 0
        || path.extname(name) == '.dmg') prefix = platforms.OSX;

    // Detect suffix: 32 or 64
    if (_.contains(name, '32')
        || _.contains(name, 'ia32')
        || _.contains(name, 'i386')) suffix = '32';
    if (_.contains(name, '64') || _.contains(name, 'x64') || _.contains(name, 'amd64')) suffix = '64';

    suffix = suffix || (prefix == platforms.OSX? '64' : '32');
    return _.compact([prefix, suffix]).join('_');
}

// Satisfies a platform
function satisfiesPlatform(platform, list) {
    if (_.contains(list, platform)) return true;

    // By default, user 32bits version
    if (_.contains(list+'_32', platform)) return true;

    return false;
}

// Resolve a platform for a version
function resolveForVersion(version, platformID, opts) {
    opts = _.defaults(opts || {}, {
        // Order for filetype
        filePreference: ['.exe', '.dmg', '.deb', '.rpm', '.tgz', '.tar.gz', '.zip', '.nupkg'],
        wanted: null
    });

    // Prepare file prefs
    if (opts.wanted) opts.filePreference = _.uniq([opts.wanted].concat(opts.filePreference));

    // Normalize platform id
    platformID = detectPlatform(platformID);

    return _.chain(version.platforms)
        .filter(function(pl) {
            return pl.type.indexOf(platformID) === 0;
        })
        .sort(function(p1, p2) {
            var result = 0;

            // Compare by arhcitecture ("osx_64" > "osx")
            if (p1.type.length > p2.type.length) result = -1;
            else if (p2.type.length > p1.type.length) result = 1;

            // Order by file type if samee architecture
            if (result == 0) {
                var ext1 = path.extname(p1.filename);
                var ext2 = path.extname(p2.filename);
                var pos1 = _.indexOf(opts.filePreference, ext1);
                var pos2 = _.indexOf(opts.filePreference, ext2);

                pos1 = pos1 == -1? opts.filePreference.length : pos1;
                pos2 = pos2 == -1? opts.filePreference.length : pos2;

                if (pos1 < pos2) result = -1;
                else if (pos2 < pos1) result = 1;
            }
            return result;
        })
        .first()
        .value()
}

module.exports = platforms;
module.exports.detect = detectPlatform;
module.exports.satisfies = satisfiesPlatform;
module.exports.toType = platformToType;
module.exports.resolve = resolveForVersion;
<|endoftext|>