<commit_before>var existCookie = document.cookie.match(/^(.*;)?\s*tipCookie\s*=\s*[^;]+(.*)?$/);
var htmlNames = ["Importanttips.html","Secondarytips.html","Tertiarytips.html"];
var fileNames = ["https://raw.githubusercontent.com/umple/umple/Issue%231636_TOTD/build/reference/6600ImportantTips.txt","https://raw.githubusercontent.com/umple/umple/Issue%231636_TOTD/build/reference/6601SecondaryTips.txt", "https://raw.githubusercontent.com/umple/umple/Issue%231636_TOTD/build/reference/6602TertiaryTips.txt"];

if (existCookie==null){
    // =========================================
    // Tip Information Gatherers
    // =========================================

        var firstTime = localStorage.getItem("first_time");
        if(!firstTime) {
            window.localStorage.setItem('tipCount',0);
            window.localStorage.setItem('priorityCount',0);

            //acquiring tipInformation
            for (let files=0; files<fileNames.length; files++){
                jQuery.ajax({
                    url: fileNames[files],
                    success: function(results){
                        let allInfo=results;
                        allInfo=allInfo.split("
");
                        var descrpt=[];
                        for (let i=0; i<allInfo.length; i++){
                            var t=[];
                            t.push(allInfo[i].substring(0, allInfo[i].indexOf("
")));
                            var link="http://manual.umple.org/manual/"+htmlNames[files];
                            t.push(allInfo[i].substring(allInfo[i].indexOf("
")+6, allInfo[i].length-1)+'View All Tips');
                            descrpt.push(t);
                        }
                        window.localStorage.setItem('tipInfo'+files, JSON.stringify(descrpt)); //adding items to local storage
                        },
                    error: function(response){
                        descrpt.push(["couldn't access file",error]);
                    }
                })
            }
            window.localStorage.setItem("first_time","1");
        }

    // =========================================
    // Tip Pickers
    // =========================================

    jQuery(document).ajaxStop(function() {
        var priority=window.localStorage.getItem('priorityCount');
        var tip = JSON.parse(window.localStorage.getItem('tipInfo'+priority));
        var num = parseInt(window.localStorage.getItem('tipCount'));

        if (tip!=null){
            document.getElementById('styleTip').innerHTML = "
Tip: "+tip[num+1][0] + ' Click for more';
            document.getElementById('extraInfo').innerHTML = tip[num+1][1];
            if (num+2>=tip.length-1){
                if (parseInt(priority)+1>=3) //renew data
                    for (let files=0; files<fileNames.length; files++){
                        jQuery.ajax({
                            url: fileNames[files],
                            success: function(results){
                                let allInfo=results;
                                allInfo=allInfo.split("
");
                                var descrpt=[];
                                for (let i=0; i<allInfo.length; i++){
                                    var t=[];
                                    t.push(allInfo[i].substring(0, allInfo[i].indexOf("
")));
                                    var link="http://manual.umple.org/manual/"+htmlNames[files];
                                    t.push(allInfo[i].substring(allInfo[i].indexOf("
")+6, allInfo[i].length-1)+'View All Tips');
                                    descrpt.push(t);
                                }
                                localStorage.setItem('tipInfo'+files, JSON.stringify(descrpt)); //adding items to local storage
                                },
                            error: function(response){
                                descrpt.push(["couldn't access file","error"]);
                            }
                        })
                        this.localStorage.setItem('priorityCount', '0');
                    }

                else this.localStorage.setItem('priorityCount', parseInt(priority)+1);
                localStorage.setItem('tipCount','0');
            }
            else{
                localStorage.setItem('tipCount',num+1);
            }
        }
        let currentTime=new Date();
        currentTime.setTime(currentTime.getTime() + (24*60*60*1000));
        document.cookie="tipCookie=done; expires="+currentTime.toUTCString()+"; path=/";
    });

}

// =========================================
// Display/Hide Functions
// =========================================

function showExtra(){
    document.getElementById('extraInfo').classList.remove("fade-outInst");
    document.getElementById('extraInfo').classList.add("fade-in");
    setTimeout(function(){hideExtra();}, 8000);
}

function hideExtra(){
    document.getElementById('extraInfo').classList.remove("fade-in");
    document.getElementById('extraInfo').classList.add("fade-outInst");
}<commit_msg>Changed target for links and set exp date to midnight<commit_after>var existCookie = document.cookie.match(/^(.*;)?\s*tipCookie\s*=\s*[^;]+(.*)?$/);
var htmlNames = ["Importanttips.html","Secondarytips.html","Tertiarytips.html"];
var fileNames = ["https://raw.githubusercontent.com/umple/umple/Issue%231636_TOTD/build/reference/6600ImportantTips.txt","https://raw.githubusercontent.com/umple/umple/Issue%231636_TOTD/build/reference/6601SecondaryTips.txt", "https://raw.githubusercontent.com/umple/umple/Issue%231636_TOTD/build/reference/6602TertiaryTips.txt"];

if (existCookie==null){
    // =========================================
    // Tip Information Gatherers
    // =========================================

        var firstTime = localStorage.getItem("first_time");
        if(!firstTime) {
            window.localStorage.setItem('tipCount',0);
            window.localStorage.setItem('priorityCount',0);

            //acquiring tipInformation
            for (let files=0; files<fileNames.length; files++){
                jQuery.ajax({
                    url: fileNames[files],
                    success: function(results){
                        let allInfo=results;
                        allInfo=allInfo.split("
");
                        var descrpt=[];
                        for (let i=0; i<allInfo.length; i++){
                            var t=[];
                            t.push(allInfo[i].substring(0, allInfo[i].indexOf("
")));
                            var link="http://manual.umple.org/manual/"+htmlNames[files];
                            t.push(allInfo[i].substring(allInfo[i].indexOf("
")+6, allInfo[i].length-11)+'View All Tips');
                            descrpt.push(t);
                        }
                        window.localStorage.setItem('tipInfo'+files, JSON.stringify(descrpt)); //adding items to local storage
                        },
                    error: function(response){
                        descrpt.push(["couldn't access file",error]);
                    }
                })
            }
            window.localStorage.setItem("first_time","1");
        }

    // =========================================
    // Tip Pickers
    // =========================================

    jQuery(document).ajaxStop(function() {
        var priority=window.localStorage.getItem('priorityCount');
        var tip = JSON.parse(window.localStorage.getItem('tipInfo'+priority));
        var num = parseInt(window.localStorage.getItem('tipCount'));

        if (tip!=null){
            document.getElementById('styleTip').innerHTML = "
Tip: "+tip[num+1][0] + ' Click for more';
            jQuery('#styleTip a').attr('target', 'helppage');
            document.getElementById('extraInfo').innerHTML = tip[num+1][1];
            jQuery('#extraInfo a').attr('target', 'helppage');
            if (num+2>=tip.length-1){
                if (parseInt(priority)+1>=3) //renew data
                    for (let files=0; files<fileNames.length; files++){
                        jQuery.ajax({
                            url: fileNames[files],
                            success: function(results){
                                let allInfo=results;
                                allInfo=allInfo.split("
");
                                var descrpt=[];
                                for (let i=0; i<allInfo.length; i++){
                                    var t=[];
                                    t.push(allInfo[i].substring(0, allInfo[i].indexOf("
")));
                                    var link="http://manual.umple.org/manual/"+htmlNames[files];
                                    t.push(allInfo[i].substring(allInfo[i].indexOf("
")+6, allInfo[i].length-1)+'View All Tips');
                                    descrpt.push(t);
                                }
                                localStorage.setItem('tipInfo'+files, JSON.stringify(descrpt)); //adding items to local storage
                                },
                            error: function(response){
                                descrpt.push(["couldn't access file","error"]);
                            }
                        })
                        this.localStorage.setItem('priorityCount', '0');
                    }

                else this.localStorage.setItem('priorityCount', parseInt(priority)+1);
                localStorage.setItem('tipCount','0');
            }
            else{
                localStorage.setItem('tipCount',num+1);
            }
        }
        let currentTime=new Date();
        currentTime.setTime(currentTime.getTime());
        currentTime.setHours(24, 0, 0, 0);
        document.cookie="tipCookie=done; expires="+currentTime.toString()+"; path=/";
    });

}

// =========================================
// Display/Hide Functions
// =========================================

function showExtra(){
    document.getElementById('extraInfo').classList.remove("fade-outInst");
    document.getElementById('extraInfo').classList.add("fade-in");
    setTimeout(function(){hideExtra();}, 10000);
}

function hideExtra(){
    document.getElementById('extraInfo').classList.remove("fade-in");
    document.getElementById('extraInfo').classList.add("fade-outInst");
}<|endoftext|>


<commit_before>'use strict';
angular.module('arethusa.relation').service('relation', [
  'state',
  'configurator',
  'globalSettings',
  function (state, configurator, globalSettings) {
    var self = this;

    this.canSearch = true;

    globalSettings.addColorizer('relation');

    function configure() {
      configurator.getConfAndDelegate('relation', self);
      configurator.getStickyConf('relation', self, ['advancedMode']);
      self.relationValues = self.conf.relations;
      self.relations = {};
      colorMap = undefined;
    }

    configure();

    // Currently selected labels
    this.currentLabels = function () {
      return arethusaUtil.inject({}, state.selectedTokens, function (memo, id, event) {
        memo[id] = self.relations[id];
      });
    };

    // Label handling
    function splitLabel(relation, label) {
      label = angular.isDefined(label) ? label : relation.label;
      var split = label.split('_');
      relation.prefix = split.shift() || '';
      relation.suffix = split.join('_');
    }

    this.buildLabel = function (relation, doNotSet) {
      var elements = [
          relation.prefix,
          relation.suffix
        ];
      var clean = arethusaUtil.inject([], elements, function (memo, el) {
          if (el) {
            memo.push(el);
          }
        });

      var label = clean.join('_');
      if (!doNotSet) {
        relation.label = label;
      }
      return label;
    };

    this.prefixWithAncestors = function(relation) {
      return arethusaUtil.inject([], relation.ancestors, function(memo, ancestor) {
        memo.push(ancestor.short);
      }).join(' > ') || '---';
    };

    this.suffixOrPlaceholder = function(relation) {
      return relation.suffix || '---';
    };

    this.usePrefix = 'prefix';
    this.useSuffix = 'suffix';
    this.defineAncestors = true;

    // This function is a disgrace. Please refactor.
    function getRelationValueObj(prefix) {
      var hits = arethusaUtil.findNestedProperties(self.relationValues, prefix);
      try {
        return hits[prefix][0][prefix];
      } catch(e) {}
    }
    this.initAncestors = function(relation) {
      // calculate a real ancestor chain here if need be
      var prefix = relation.prefix;
      var ancestors = [];
      if (prefix) {
        var obj = getRelationValueObj(prefix);
        if (obj) ancestors.push(obj);
      }
      relation.ancestors = ancestors;
    };

    this.expandRelation = function (relation) {
      splitLabel(relation);
      self.initAncestors(relation);
      return relation;
    };

    // Empty template for relation objects
    this.relationTemplate = function () {
      return {
        prefix: '',
        suffix: '',
        label: '',
        ancestors: []
      };
    };

    // Search/Selector
    this.resetSearchedLabel = function () {
      self.searchedLabel = self.relationTemplate();
    };

    this.selectByLabel = function (label) {
      var ids = arethusaUtil.inject([], self.relations, function (memo, id, rel) {
          if (rel.relation.label === label) {
            memo.push(id);
          }
        });
      state.multiSelect(ids);
    };

    this.buildLabelAndSearch = function(rel) {
      rel = rel ? rel : self.searchedLabel;
      self.buildLabel(rel);
      self.selectByLabel(rel.label);
    };

    // Multi-changer
    this.resetMultiChanger = function () {
      this.multiChanger = self.relationTemplate();
    };

    this.multiChangePossible = function () {
      // We check for the prefix, as only a suffix, which would
      // fill the label already would not be allowed.
      //
      // Tokens need to be selected to of course.
      return self.multiChanger.prefix !== '' &&
        state.hasSelections();
    };

    // Pretty ridiculous changes to gain compatibility with the
    // new state eventing.
    //
    // There is some duplicate stuff happening, to blame is the
    // whole nestedMenu directive logic, which has to be redone
    // for other reasons as well.
    //
    // Prefix/Suffix and Ancestors have already been built by
    // the directive when we enter relation.stateChange, only
    // the label has to be built.
    //
    // Because we need to define proper values for prefix/suffix
    // and ancestors when we want to undo/redo our changes, we
    // have to recreate them during during stateChange, which
    // leads to a redefinition on the initial event. It's not
    // really a problem, it's just not very pretty...
    //
    this.applyMultiChanger = function () {
      // We have to copy the multiChanger, so that its model
      // stays intact, when we remove the label. We need to do
      // this because we will rebuild it through changeState.
      var cleanChanger = angular.copy(self.multiChanger);
      delete cleanChanger.label;

      state.doBatched(function() {
        angular.forEach(self.currentLabels(), function (obj, id) {
          var oldAncestors = obj.relation.ancestors;
          angular.extend(obj.relation, cleanChanger);
          self.changeState(obj.relation, oldAncestors);
        });
      });
    };

    function undoFn(id, obj, val, oldAncestors) {
      oldAncestors = oldAncestors || angular.copy(obj.ancestors);
      return function() {
        splitLabel(obj, val);
        obj.ancestors = oldAncestors;
        if (isColorizer()) { state.addStyle(id, self.styleOf(oldAncestors)); }
        state.change(obj.id, 'relation.label', val);
      };
    }

    function preExecFn(id, obj, val) {
      var newAncestors = angular.copy(obj.ancestors);
      return function() {
        obj.ancestors = newAncestors;
        splitLabel(obj, val);
        if (isColorizer()) state.addStyle(id, self.styleOf(newAncestors));
      };
    }

    function isColorizer() {
      return globalSettings.isColorizer('relation');
    }

    this.styleOf = function(ancestors) {
      var chain = aU.map(ancestors, 'short').join('.');
      return aU.getProperty(self.relationValues.labels, chain).style || {};
    };

    this.changeState = function(relObj, oldAncestors) {
      var id = relObj.id;
      var oldVal = relObj.label;
      var newVal = self.buildLabel(relObj, !!id);

      if (id) {
        state.change(id, 'relation.label', newVal,
                    undoFn(id, relObj, oldVal, oldAncestors),
                    preExecFn(id, relObj, newVal));
      }
    };

    // Init
    function addToInternalState(container, id, token) {
      if (!token.relation) token.relation = self.relationTemplate();
      // Passing the id is a hacky shortcut to allow access to
      // state.change. If we ever have to change ids on the fly,
      // this will call for trouble. Watch out.
      token.relation.id = id;
      container[id] = {
        string: token.string,
        relation: self.expandRelation(token.relation || '')
      };
    }

    this.createInternalState = function () {
      return arethusaUtil.inject({}, state.tokens, addToInternalState);
    };

    this.canEdit = function() {
      return self.mode === "editor";
    };

    state.on('tokenAdded', function(event, token) {
      addToInternalState(self.relations, token.id, token);
    });

    state.on('tokenRemoved', function(event, token) {
      delete self.relations[token.id];
    });

    function extractColor(obj, target, keys) {
      angular.forEach(obj, function(rel, name) {
        var style  = rel.style;
        var nested = rel.nested;
        if (style) {
          var key = aU.flatten(aU.map(keys, rel)).join(' || ');
          target[key] = style;
        }

        if (nested) {
          extractColor(nested, target, keys);
        }
      });
    }

    function createColorMap() {
      var keys = ['short', 'long'];
      var map = { header: keys, colors: {} };

      extractColor(self.relationValues.labels, map.colors, keys);
      return map;
    }

    var colorMap;
    this.colorMap = function() {
      if (!colorMap) colorMap = createColorMap();
      return colorMap;
    };

    function setStyle(id) {
      var anc = aU.last(self.relations[id].relation.ancestors) || {};
      var style = anc.style || {};
      state.setStyle(id, style);
    }

    this.applyStyling = function() {
      angular.forEach(state.tokens, function(token, id) {
        if (token.relation.label) {
          setStyle(id);
        } else {
          state.unsetStyle(id);
        }
      });
    };

    this.init = function () {
      configure();
      self.relations = self.createInternalState();
      self.resetSearchedLabel();
      self.resetMultiChanger();
    };
  }
]);
<commit_msg>Call correct styling fn in relation<commit_after>'use strict';
angular.module('arethusa.relation').service('relation', [
  'state',
  'configurator',
  'globalSettings',
  function (state, configurator, globalSettings) {
    var self = this;

    this.canSearch = true;

    globalSettings.addColorizer('relation');

    function configure() {
      configurator.getConfAndDelegate('relation', self);
      configurator.getStickyConf('relation', self, ['advancedMode']);
      self.relationValues = self.conf.relations;
      self.relations = {};
      colorMap = undefined;
    }

    configure();

    // Currently selected labels
    this.currentLabels = function () {
      return arethusaUtil.inject({}, state.selectedTokens, function (memo, id, event) {
        memo[id] = self.relations[id];
      });
    };

    // Label handling
    function splitLabel(relation, label) {
      label = angular.isDefined(label) ? label : relation.label;
      var split = label.split('_');
      relation.prefix = split.shift() || '';
      relation.suffix = split.join('_');
    }

    this.buildLabel = function (relation, doNotSet) {
      var elements = [
          relation.prefix,
          relation.suffix
        ];
      var clean = arethusaUtil.inject([], elements, function (memo, el) {
          if (el) {
            memo.push(el);
          }
        });

      var label = clean.join('_');
      if (!doNotSet) {
        relation.label = label;
      }
      return label;
    };

    this.prefixWithAncestors = function(relation) {
      return arethusaUtil.inject([], relation.ancestors, function(memo, ancestor) {
        memo.push(ancestor.short);
      }).join(' > ') || '---';
    };

    this.suffixOrPlaceholder = function(relation) {
      return relation.suffix || '---';
    };

    this.usePrefix = 'prefix';
    this.useSuffix = 'suffix';
    this.defineAncestors = true;

    // This function is a disgrace. Please refactor.
    function getRelationValueObj(prefix) {
      var hits = arethusaUtil.findNestedProperties(self.relationValues, prefix);
      try {
        return hits[prefix][0][prefix];
      } catch(e) {}
    }
    this.initAncestors = function(relation) {
      // calculate a real ancestor chain here if need be
      var prefix = relation.prefix;
      var ancestors = [];
      if (prefix) {
        var obj = getRelationValueObj(prefix);
        if (obj) ancestors.push(obj);
      }
      relation.ancestors = ancestors;
    };

    this.expandRelation = function (relation) {
      splitLabel(relation);
      self.initAncestors(relation);
      return relation;
    };

    // Empty template for relation objects
    this.relationTemplate = function () {
      return {
        prefix: '',
        suffix: '',
        label: '',
        ancestors: []
      };
    };

    // Search/Selector
    this.resetSearchedLabel = function () {
      self.searchedLabel = self.relationTemplate();
    };

    this.selectByLabel = function (label) {
      var ids = arethusaUtil.inject([], self.relations, function (memo, id, rel) {
          if (rel.relation.label === label) {
            memo.push(id);
          }
        });
      state.multiSelect(ids);
    };

    this.buildLabelAndSearch = function(rel) {
      rel = rel ? rel : self.searchedLabel;
      self.buildLabel(rel);
      self.selectByLabel(rel.label);
    };

    // Multi-changer
    this.resetMultiChanger = function () {
      this.multiChanger = self.relationTemplate();
    };

    this.multiChangePossible = function () {
      // We check for the prefix, as only a suffix, which would
      // fill the label already would not be allowed.
      //
      // Tokens need to be selected to of course.
      return self.multiChanger.prefix !== '' &&
        state.hasSelections();
    };

    // Pretty ridiculous changes to gain compatibility with the
    // new state eventing.
    //
    // There is some duplicate stuff happening, to blame is the
    // whole nestedMenu directive logic, which has to be redone
    // for other reasons as well.
    //
    // Prefix/Suffix and Ancestors have already been built by
    // the directive when we enter relation.stateChange, only
    // the label has to be built.
    //
    // Because we need to define proper values for prefix/suffix
    // and ancestors when we want to undo/redo our changes, we
    // have to recreate them during during stateChange, which
    // leads to a redefinition on the initial event. It's not
    // really a problem, it's just not very pretty...
    //
    this.applyMultiChanger = function () {
      // We have to copy the multiChanger, so that its model
      // stays intact, when we remove the label. We need to do
      // this because we will rebuild it through changeState.
      var cleanChanger = angular.copy(self.multiChanger);
      delete cleanChanger.label;

      state.doBatched(function() {
        angular.forEach(self.currentLabels(), function (obj, id) {
          var oldAncestors = obj.relation.ancestors;
          angular.extend(obj.relation, cleanChanger);
          self.changeState(obj.relation, oldAncestors);
        });
      });
    };

    function undoFn(id, obj, val, oldAncestors) {
      oldAncestors = oldAncestors || angular.copy(obj.ancestors);
      return function() {
        splitLabel(obj, val);
        obj.ancestors = oldAncestors;
        if (isColorizer()) { state.addStyle(id, self.styleOf(oldAncestors)); }
        state.change(obj.id, 'relation.label', val);
      };
    }

    function preExecFn(id, obj, val) {
      var newAncestors = angular.copy(obj.ancestors);
      return function() {
        obj.ancestors = newAncestors;
        splitLabel(obj, val);
        if (isColorizer()) state.addStyle(id, self.styleOf(newAncestors));
      };
    }

    function isColorizer() {
      return globalSettings.isColorizer('relation');
    }

    this.styleOf = function(ancestors) {
      var chain = aU.map(ancestors, 'short').join('.');
      return aU.getProperty(self.relationValues.labels, chain).style || {};
    };

    this.changeState = function(relObj, oldAncestors) {
      var id = relObj.id;
      var oldVal = relObj.label;
      var newVal = self.buildLabel(relObj, !!id);

      if (id) {
        state.change(id, 'relation.label', newVal,
                    undoFn(id, relObj, oldVal, oldAncestors),
                    preExecFn(id, relObj, newVal));
      }
    };

    // Init
    function addToInternalState(container, id, token) {
      if (!token.relation) token.relation = self.relationTemplate();
      // Passing the id is a hacky shortcut to allow access to
      // state.change. If we ever have to change ids on the fly,
      // this will call for trouble. Watch out.
      token.relation.id = id;
      container[id] = {
        string: token.string,
        relation: self.expandRelation(token.relation || '')
      };
    }

    this.createInternalState = function () {
      return arethusaUtil.inject({}, state.tokens, addToInternalState);
    };

    this.canEdit = function() {
      return self.mode === "editor";
    };

    state.on('tokenAdded', function(event, token) {
      addToInternalState(self.relations, token.id, token);
    });

    state.on('tokenRemoved', function(event, token) {
      delete self.relations[token.id];
    });

    function extractColor(obj, target, keys) {
      angular.forEach(obj, function(rel, name) {
        var style  = rel.style;
        var nested = rel.nested;
        if (style) {
          var key = aU.flatten(aU.map(keys, rel)).join(' || ');
          target[key] = style;
        }

        if (nested) {
          extractColor(nested, target, keys);
        }
      });
    }

    function createColorMap() {
      var keys = ['short', 'long'];
      var map = { header: keys, colors: {} };

      extractColor(self.relationValues.labels, map.colors, keys);
      return map;
    }

    var colorMap;
    this.colorMap = function() {
      if (!colorMap) colorMap = createColorMap();
      return colorMap;
    };

    function setStyle(id) {
      var anc = aU.last(self.relations[id].relation.ancestors) || {};
      var style = anc.style || {};
      state.addStyle(id, style);
    }

    this.applyStyling = function() {
      angular.forEach(state.tokens, function(token, id) {
        if (token.relation.label) {
          setStyle(id);
        } else {
          state.unsetStyle(id);
        }
      });
    };

    this.init = function () {
      configure();
      self.relations = self.createInternalState();
      self.resetSearchedLabel();
      self.resetMultiChanger();
    };
  }
]);
<|endoftext|>


<commit_before>/**
 * Marionette Routing
 *
 * Copyright © 2015-2016 Luiz Américo Pereira Câmara. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import _ from 'underscore'
import Radio from 'backbone.radio'
import cherrytree from 'cherrytree'
import Route from './route'

let mnRouteMap = Object.create(null)
export const routerChannel = Radio.channel('router')
let router

export function createRouter(options) {
  if (router) {
    throw new Error('Instance of router already created')
  }
  return router = Route.prototype.$router = cherrytree(options)
}

export function destroyRouter(instance) {
  router = null
  Route.prototype.$router = null
  mnRouteMap = Object.create(null)
  instance.destroy()
}

export function getMnRoutes(routes) {
  return routes.map(function (route) {
    return mnRouteMap[route.name]
  })
}

routerChannel.reply('transitionTo', function () {
  return router.transitionTo.apply(router, arguments)
})

routerChannel.reply('isActive', function () {
  return router.isActive.apply(router, arguments)
})

routerChannel.reply('generate', function () {
  return router.generate.apply(router, arguments)
})

routerChannel.reply('goBack', function () {
  //in wait of a better implementation
  history.back();
})

function getChangingIndex(prevRoutes, currentRoutes){
  var index, prev, current;
  const count = Math.max(prevRoutes.length, currentRoutes.length)
  for (index = 0; index < count; index++) {
    prev = prevRoutes[index]
    current = currentRoutes[index]
    if (!(prev && current) || (prev.name !== current.name) || !_.isEqual(prev.params, current.params)) {
      break
    }
  }
  return index
}

function findRouteConfig(routeName, index, routes) {
  let parentRoutes = routes.slice(0, index).reverse().map(function (route) {
    return mnRouteMap[route.name]
  })
  let config
  parentRoutes.some(function (route) {
    let childRoutes = _.result(route, 'childRoutes')
    config = childRoutes && childRoutes[routeName]
    if (_.isFunction(config) && !(config.prototype instanceof Route)) {
      config = config.call(route)
    }
    return config
  })
  return config
}

function createRouteInstance(options) {
  if (options.prototype instanceof Route) {
    return new options()
  }
  let routeOptions = Object.assign({}, options.routeOptions, _.pick(options, ['viewClass', 'viewOptions']))
  if (options.routeClass) {
    return new options.routeClass(routeOptions)
  } else if (options.viewClass || options.abstract) {
    return new Route(routeOptions)
  }
}

function createMnRoute(route, index, routes) {
  let instance = createRouteInstance(route.options)
  if (!instance) {
    let config = findRouteConfig(route.name, index, routes)
    return Promise.resolve(config).then(function (options) {
      return options && createRouteInstance(options)
    })
  }
  if (!instance) {
    throw new Error(`Unable to create route ${route.name}: routeClass or viewClass must be defined`)
  }
  instance.$name = route.name
  return instance
}

function getParentRegion(routes, route) {
  var region, parent
  let routeIndex = routes.indexOf(route) - 1
  while (routeIndex >= 0) {
    parent = routes[routeIndex]
    if (parent.view) {
      region = parent.view.getRegion('outlet')
      if (region) {
        return region
      } else {
        throw new Error('No outlet region in view')
      }
    }
    routeIndex--
  }
  if (!router.rootRegion) {
    throw new Error('No outlet region')
  }
  return router.rootRegion
}

export function middleware(transition) {

  routerChannel.trigger('before:transition', transition)

  if (transition.isCancelled) {
    return
  }

  let prevRoutes = transition.prev.routes
  let changingIndex = getChangingIndex(prevRoutes, transition.routes)
  var routeIndex, routeInstance

  //deactivate previous routes
  for (routeIndex = prevRoutes.length - 1; routeIndex >= changingIndex; routeIndex--) {
    routeInstance = mnRouteMap[prevRoutes[routeIndex].name]
    if (routeInstance) {
      routerChannel.trigger('before:deactivate', transition, routeInstance)
      if (!transition.isCancelled) {
        routeInstance.deactivate(transition)
        routerChannel.trigger('deactivate', transition, routeInstance)
      }
      if (transition.isCancelled) {
        return
      }
    }
  }

  //build route tree and creating instances if necessary
  let mnRoutes = transition.mnRoutes = []

  let promise = transition.routes.reduce(function (acc, route, i, routes) {
    return acc.then(function (res) {
      let instance = mnRouteMap[route.name]
      if (instance) {
        res.push(instance)
        return res
      } else {
        instance = createMnRoute(route, i, routes)
        return Promise.resolve(instance).then(function (mnRoute) {
          mnRouteMap[route.name] = mnRoute
          res.push(mnRoute)
          return res
        })
      }
    });
  }, Promise.resolve(mnRoutes));

  //activate routes in order
  let activated

  promise = promise.then(function () {
    activated = mnRoutes.slice(changingIndex)
    return activated.reduce(function (prevPromise, mnRoute) {
      return prevPromise.then(function () {
        if (!transition.isCancelled) {
          routerChannel.trigger('before:activate', transition, mnRoute)
          if (!transition.isCancelled) {
            return Promise.resolve(mnRoute.activate(transition)).then(function () {
              routerChannel.trigger('activate', transition, mnRoute)
            })
          }
        }
        return Promise.resolve()
      })
    }, Promise.resolve())
  })

  transition.then(function () {
    router.state.mnRoutes = mnRoutes
    routerChannel.trigger('transition', transition)
  })

  //render views
  return promise.then(function () {
    //ensure at least the target (last) route is rendered
    if (!activated.length && mnRoutes.length) {
      activated.push(mnRoutes[mnRoutes.length - 1])
    }
    activated.forEach(function (mnRoute) {
      if (mnRoute.viewClass) {
        let parentRegion = getParentRegion(mnRoutes, mnRoute)
        mnRoute.renderView(parentRegion)
      }
    })
  })
}<commit_msg>Use _.extend instead of Object.assign<commit_after>/**
 * Marionette Routing
 *
 * Copyright © 2015-2016 Luiz Américo Pereira Câmara. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import _ from 'underscore'
import Radio from 'backbone.radio'
import cherrytree from 'cherrytree'
import Route from './route'

let mnRouteMap = Object.create(null)
export const routerChannel = Radio.channel('router')
let router

export function createRouter(options) {
  if (router) {
    throw new Error('Instance of router already created')
  }
  return router = Route.prototype.$router = cherrytree(options)
}

export function destroyRouter(instance) {
  router = null
  Route.prototype.$router = null
  mnRouteMap = Object.create(null)
  instance.destroy()
}

export function getMnRoutes(routes) {
  return routes.map(function (route) {
    return mnRouteMap[route.name]
  })
}

routerChannel.reply('transitionTo', function () {
  return router.transitionTo.apply(router, arguments)
})

routerChannel.reply('isActive', function () {
  return router.isActive.apply(router, arguments)
})

routerChannel.reply('generate', function () {
  return router.generate.apply(router, arguments)
})

routerChannel.reply('goBack', function () {
  //in wait of a better implementation
  history.back();
})

function getChangingIndex(prevRoutes, currentRoutes){
  var index, prev, current;
  const count = Math.max(prevRoutes.length, currentRoutes.length)
  for (index = 0; index < count; index++) {
    prev = prevRoutes[index]
    current = currentRoutes[index]
    if (!(prev && current) || (prev.name !== current.name) || !_.isEqual(prev.params, current.params)) {
      break
    }
  }
  return index
}

function findRouteConfig(routeName, index, routes) {
  let parentRoutes = routes.slice(0, index).reverse().map(function (route) {
    return mnRouteMap[route.name]
  })
  let config
  parentRoutes.some(function (route) {
    let childRoutes = _.result(route, 'childRoutes')
    config = childRoutes && childRoutes[routeName]
    if (_.isFunction(config) && !(config.prototype instanceof Route)) {
      config = config.call(route)
    }
    return config
  })
  return config
}

function createRouteInstance(options) {
  if (options.prototype instanceof Route) {
    return new options()
  }
  let routeOptions = _.extend({}, options.routeOptions, _.pick(options, ['viewClass', 'viewOptions']))
  if (options.routeClass) {
    return new options.routeClass(routeOptions)
  } else if (options.viewClass || options.abstract) {
    return new Route(routeOptions)
  }
}

function createMnRoute(route, index, routes) {
  let instance = createRouteInstance(route.options)
  if (!instance) {
    let config = findRouteConfig(route.name, index, routes)
    return Promise.resolve(config).then(function (options) {
      return options && createRouteInstance(options)
    })
  }
  if (!instance) {
    throw new Error(`Unable to create route ${route.name}: routeClass or viewClass must be defined`)
  }
  instance.$name = route.name
  return instance
}

function getParentRegion(routes, route) {
  var region, parent
  let routeIndex = routes.indexOf(route) - 1
  while (routeIndex >= 0) {
    parent = routes[routeIndex]
    if (parent.view) {
      region = parent.view.getRegion('outlet')
      if (region) {
        return region
      } else {
        throw new Error('No outlet region in view')
      }
    }
    routeIndex--
  }
  if (!router.rootRegion) {
    throw new Error('No outlet region')
  }
  return router.rootRegion
}

export function middleware(transition) {

  routerChannel.trigger('before:transition', transition)

  if (transition.isCancelled) {
    return
  }

  let prevRoutes = transition.prev.routes
  let changingIndex = getChangingIndex(prevRoutes, transition.routes)
  var routeIndex, routeInstance

  //deactivate previous routes
  for (routeIndex = prevRoutes.length - 1; routeIndex >= changingIndex; routeIndex--) {
    routeInstance = mnRouteMap[prevRoutes[routeIndex].name]
    if (routeInstance) {
      routerChannel.trigger('before:deactivate', transition, routeInstance)
      if (!transition.isCancelled) {
        routeInstance.deactivate(transition)
        routerChannel.trigger('deactivate', transition, routeInstance)
      }
      if (transition.isCancelled) {
        return
      }
    }
  }

  //build route tree and creating instances if necessary
  let mnRoutes = transition.mnRoutes = []

  let promise = transition.routes.reduce(function (acc, route, i, routes) {
    return acc.then(function (res) {
      let instance = mnRouteMap[route.name]
      if (instance) {
        res.push(instance)
        return res
      } else {
        instance = createMnRoute(route, i, routes)
        return Promise.resolve(instance).then(function (mnRoute) {
          mnRouteMap[route.name] = mnRoute
          res.push(mnRoute)
          return res
        })
      }
    });
  }, Promise.resolve(mnRoutes));

  //activate routes in order
  let activated

  promise = promise.then(function () {
    activated = mnRoutes.slice(changingIndex)
    return activated.reduce(function (prevPromise, mnRoute) {
      return prevPromise.then(function () {
        if (!transition.isCancelled) {
          routerChannel.trigger('before:activate', transition, mnRoute)
          if (!transition.isCancelled) {
            return Promise.resolve(mnRoute.activate(transition)).then(function () {
              routerChannel.trigger('activate', transition, mnRoute)
            })
          }
        }
        return Promise.resolve()
      })
    }, Promise.resolve())
  })

  transition.then(function () {
    router.state.mnRoutes = mnRoutes
    routerChannel.trigger('transition', transition)
  })

  //render views
  return promise.then(function () {
    //ensure at least the target (last) route is rendered
    if (!activated.length && mnRoutes.length) {
      activated.push(mnRoutes[mnRoutes.length - 1])
    }
    activated.forEach(function (mnRoute) {
      if (mnRoute.viewClass) {
        let parentRegion = getParentRegion(mnRoutes, mnRoute)
        mnRoute.renderView(parentRegion)
      }
    })
  })
}<|endoftext|>


<commit_before>'use strict';
Package('cl.quickcorp.tools',[
  Class('MarkdownTemplateHandler',DefaultTemplateHandler,{
    template:'',
    assign:function (data){
      var converter = new showdown.Converter();
      var parsedAssignmentText = converter.makeHtml(this.template);
      return parsedAssignmentText;
    }
  })
]);
<commit_msg>GitHub flavour to show README.md<commit_after>'use strict';
Package('cl.quickcorp.tools',[
  Class('MarkdownTemplateHandler',DefaultTemplateHandler,{
    template:'',
    assign:function (data){
      var converter = new showdown.Converter();
      converter.setFlavor('github');
      var parsedAssignmentText = converter.makeHtml(this.template);
      return parsedAssignmentText;
    }
  })
]);
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name helmeditor2App.controller:PrototypeCtrl
 * @description
 * # PrototypeCtrl
 * Controller of the helmeditor2App
 */
angular.module('helmeditor2App')
  .controller('PrototypeCtrl', ['$scope', '$http', 'webservice', function ($scope, $http, webservice) {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

  	/* Variables related to the prototype code in HTML */
  	$scope.polyTypes = [
      { value: 'PEPTIDE', label:'PEPTIDE' },
      { value: 'RNA', label:'RNA/DNA' }
  	];
  	$scope.polymerType = $scope.polyTypes[0];
  	$scope.result = '';
  	$scope.imageUrl = '';

  	/* Event processing prototype - invoke factory function to get HELM notation */
  	$scope.getHelmNotation = function (polymerType, inputSequence) {
      if (!angular.isDefined(inputSequence)) {
        window.alert('Invalid input');
        return;
      }
      webservice.getHelmNotation(polymerType.value, inputSequence)
        .success(function (response) {
          $scope.result = response.HELMNotation;
        })
        .error(function (response) {
          $scope.result = 'Invalid sequence';
          console.log(response);
        });
    };

  	/* Event processing prototype - invoke factory function to get HELM image */
  	$scope.getHelmImage = function (inputSequence) {
      if (!angular.isDefined(inputSequence)) {
        window.alert('Invalid input');
        return;
    	}
      $scope.imageUrl = webservice.getHelmImage(inputSequence);
      $http.get($scope.imageUrl)
        .error(function (response) {
          window.alert(response);
        });
    };
  }]);
<commit_msg>Update prototype.js<commit_after>'use strict';

/**
 * @ngdoc function
 * @name helmeditor2App.controller:PrototypeCtrl
 * @description
 * # PrototypeCtrl
 * Controller of the helmeditor2App
 */
angular.module('helmeditor2App')
  .controller('PrototypeCtrl', ['$scope', '$http', 'webservice', function ($scope, $http, webservice) {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

  	/* Variables related to the prototype code in HTML */
  	$scope.polyTypes = [
      { value: 'PEPTIDE', label:'PEPTIDE' },
      { value: 'RNA', label:'RNA/DNA' }
  	];
  	$scope.polymerType = $scope.polyTypes[0];
  	$scope.result = '';
  	$scope.imageUrl = '';

  	/* Event processing prototype - invoke factory function to get HELM notation */
  	$scope.getHelmNotation = function (polymerType, inputSequence) {
      if (!angular.isDefined(inputSequence)) {
        window.alert('Invalid input');
        return;
      }
      if (polymerType.value === 'PEPTIDE') {
        webservice.getHelmNotationPeptide(inputSequence)
          .success(function (response) {
            $scope.result = response.HELMNotation;
          })
          .error(function (response) {
            $scope.result = 'Invalid sequence';
            console.log(response);
          });
      } else if (polymerType.value === 'RNA') {
        webservice.getHelmNotationRna(inputSequence)
          .success(function (response) {
            $scope.result = response.HELMNotation;
          })
          .error(function (response) {
            $scope.result = 'Invalid sequence';
            console.log(response);
          });
      }
    };

  	/* Event processing prototype - invoke factory function to get HELM image */
  	$scope.getHelmImage = function (inputSequence) {
      if (!angular.isDefined(inputSequence)) {
        window.alert('Invalid input');
        return;
    	}
      $scope.imageUrl = webservice.getHelmImageUrl(inputSequence);
      $http.get($scope.imageUrl)
        .error(function (response) {
          window.alert(response);
        });
    };
  }]);
<|endoftext|>


<commit_before>/**
 * Copyright (C) Ivan Kravets <me@ikravets.com>
 * See LICENSE for details.
 */

(function() {
  'use strict';

  angular
    .module('siteApp')
    .factory('dataService', dataService);

  function dataService($resource, siteConfig) {
    return {
      getLibSearchResult: getLibSearchResult,
      getLibExamples: getLibExamples,
      getLibInfo: getLibInfo,
      getLibDlUrl: getLibDlUrl,
      getLibStats: getLibStats,
      getFrameworks: getFrameworks,
      getPlatforms: getPlatforms
    };

    function getLibSearchResult(data) {
      return $resource(siteConfig.apiURL + '/lib/search', data).get();
    }

    function getLibExamples(data) {
      return $resource(siteConfig.apiURL + '/lib/examples', data).get();
    }

    function getLibInfo(id) {
      return $resource(siteConfig.apiURL + '/lib/info/' + id).get();
    }

    function getLibDlUrl(id) {
      return $resource(
        siteConfig.apiURL + '/lib/download/' + id).get();
    }

    function getLibStats() {
      return $resource(siteConfig.apiURL + '/lib/stats').get();
    }

    function getFrameworks() {
      return [
        {name: 'arduino', title: 'Arduino'},
        {name: 'energia', title: 'Energia'}
      ];
    }

    function getPlatforms() {
      return [
        {name: 'atmelavr', title: 'Atmel AVR'},
        {name: 'timsp430', title: 'TI MSP430'},
        {name: 'titiva', title: 'TI TIVA'}
      ];
    }
  }

})();
<commit_msg>Add Teensy platform<commit_after>/**
 * Copyright (C) Ivan Kravets <me@ikravets.com>
 * See LICENSE for details.
 */

(function() {
  'use strict';

  angular
    .module('siteApp')
    .factory('dataService', dataService);

  function dataService($resource, siteConfig) {
    return {
      getLibSearchResult: getLibSearchResult,
      getLibExamples: getLibExamples,
      getLibInfo: getLibInfo,
      getLibDlUrl: getLibDlUrl,
      getLibStats: getLibStats,
      getFrameworks: getFrameworks,
      getPlatforms: getPlatforms
    };

    function getLibSearchResult(data) {
      return $resource(siteConfig.apiURL + '/lib/search', data).get();
    }

    function getLibExamples(data) {
      return $resource(siteConfig.apiURL + '/lib/examples', data).get();
    }

    function getLibInfo(id) {
      return $resource(siteConfig.apiURL + '/lib/info/' + id).get();
    }

    function getLibDlUrl(id) {
      return $resource(
        siteConfig.apiURL + '/lib/download/' + id).get();
    }

    function getLibStats() {
      return $resource(siteConfig.apiURL + '/lib/stats').get();
    }

    function getFrameworks() {
      return [
        {name: 'arduino', title: 'Arduino'},
        {name: 'energia', title: 'Energia'}
      ];
    }

    function getPlatforms() {
      return [
        {name: 'atmelavr', title: 'Atmel AVR'},
        {name: 'timsp430', title: 'TI MSP430'},
        {name: 'titiva', title: 'TI TIVA'},
        {name: 'teensy', title: 'Teensy'}
      ];
    }
  }

})();
<|endoftext|>


<commit_before>define(['jquery', 'gameStates/BaseState', 'modules/CountScoreKeeper','modules/SettingsModule','components/scoreControl',
  'text!templates/game.visibleHand.html', 'text!templates/game.visibleDeck.html', 'text!templates/game.scoreControl.html'],
  function($, BaseState, ScoreKeeper, Settings, scoreControlComp, visibleHandHtml, visibleDeckHtml, scoreControlHtml){
  'use strict';
  function CountState(game){
    BaseState.call(this, game, 'Count');
    /*
     Step - Description
     0  - Pone counts hand
     1  - Dealer counts hand
     2  - Dealer counts crib
     */
    game.countStateStep = game.countStateStep || 0;
    this.scoreKeeper = new ScoreKeeper();
  }

  CountState.prototype = Object.create(BaseState.prototype);
  CountState.prototype.constructor = CountState;

  CountState.prototype.templates = function(){
    var templates = BaseState.prototype.templates();
    templates.deck = visibleDeckHtml;
    templates.p2Hand = visibleHandHtml;
    if(this.isScorePoints)
      templates.scoreControl = scoreControlHtml;
    return templates;
  };

  CountState.prototype.init = function(){
    this.p1.maxPoints = 29;
    this.p1.availablePoints = setAvailablePoints(this.p1.maxPoints);
    this.isScorePoints = false;
    this.p1.restoreHand();
    this.p2.restoreHand();
    if(this.game.countStateStep === 0)
      processCountStep.call(this);

    else {
      this.render();
    }
  };

  CountState.prototype.action = function(){
    if(this.isScorePoints){
      this.game.countStateStep--;//hack to fix auto incriment
    }

    processCountStep.call(this);
  };

  CountState.prototype.bindEvents = function(){
    //bind defaults
    BaseState.prototype.bindEvents.call(this);

    scoreControlComp.init(this.p1);
  };

  function setAvailablePoints(size){
    var i = 0;
    var arrayPoints = [];
    while(i < size){
      i++;
      arrayPoints.push(i);
    }
    return arrayPoints;
  }

  function processCountStep(){
    var points = 0;
    if(this.game.countStateStep === 0)
      processFirstStep.call(this, points);
    else if(this.game.countStateStep === 1)
      processSecondStep.call(this, points);
    else if(this.game.countStateStep === 2)
      processThirdStep.call(this);
    else
      processEndOfCount.call(this);
  }

  function processFirstStep(points){
    if(isPlayerOneCribOwner.call(this)){
      evaluatePlayerTwoScore.call(this, points);
    } else {
      evaluatePlayerOneScore.call(this, points);
    }
    this.game.countStateStep += 1;
    this.render();
  }

  function processSecondStep(points){
    if(isPlayerOneCribOwner.call(this)){
      evaluatePlayerOneScore.call(this, points);
      this.p2.hand = [];
    } else {
      evaluatePlayerTwoScore.call(this, points);
      this.p1.hand = [];
    }
    this.game.countStateStep += 1;
    this.render();
  }

  function processThirdStep(){
    this.game.$cribOwner.hand = (this.game.$cribOwner.crib.length === 4) ? this.game.$cribOwner.crib : this.game.$cribOwner.hand;
    this.game.$cribOwner.crib = [];
    if(isPlayerOneCribOwner.call(this)){
      evaluatePlayerOneScore.call(this);
    } else {
      evaluatePlayerTwoScore.call(this);
    }
    this.game.countStateStep += 1;
    this.render();
  }

  function processEndOfCount(){
    if(isPlayerOneCribOwner.call(this)){
      this.game.$cribOwner = this.p2;
    } else {
      this.game.$cribOwner = this.p1;
    }
    showPlayerOneHand.call(this);
    this.game.$showTopCard = false;
    this.game.countStateStep = 0;
    this.render();
    if(this.p1.isWinner() || this.p2.isWinner())
      this.mediator.publish('transition', 'Summary', true);
    else {
      this.mediator.publish('transition', 'Deal');
    }
  }

  function evaluatePlayerOneScore(points){
    showPlayerOneHand.call(this);
    if(!this.isScorePoints){
      this.scoreKeeper.evaluateHand(this.p1, this.game.topCard);
      if(this.p1.isWinner())
        this.mediator.publish('transition', 'Summary', true);
    }
    return points;
  }

  function evaluatePlayerTwoScore(points){
    showPlayerTwoHand.call(this);
    this.scoreKeeper.evaluateHand(this.p2, this.game.topCard);
    if(this.p2.isWinner())
      this.mediator.publish('transition', 'Summary', true);
    return points;
  }

  function isPlayerOneCribOwner(){
    return this.game.$cribOwner === this.p1;
  }

  function showPlayerOneHand(){
    this.game.$player2HandVisible = false;
    this.game.$player1HandVisible = true;
    if(Settings.get('manual-count')){
      this.isScorePoints = this.isScorePoints ? false : true;
      if(this.isScorePoints)
        this.p1.selectedScore = 0;
    }
  }

  function showPlayerTwoHand(){
    this.game.$player2HandVisible = true;
    this.game.$player1HandVisible = false;
  }

  return CountState;
});
<commit_msg>fix CountState scoreControl display<commit_after>define(['jquery', 'gameStates/BaseState', 'modules/CountScoreKeeper','modules/SettingsModule','components/scoreControl',
  'text!templates/game.visibleHand.html', 'text!templates/game.visibleDeck.html', 'text!templates/game.scoreControl.html'],
  function($, BaseState, ScoreKeeper, Settings, scoreControlComp, visibleHandHtml, visibleDeckHtml, scoreControlHtml){
  'use strict';
  function CountState(game){
    BaseState.call(this, game, 'Count');
    /*
     Step - Description
     0  - Pone counts hand
     1  - Dealer counts hand
     2  - Dealer counts crib
     */
    game.countStateStep = game.countStateStep || 0;
    this.scoreKeeper = new ScoreKeeper();
  }

  CountState.prototype = Object.create(BaseState.prototype);
  CountState.prototype.constructor = CountState;

  CountState.prototype.templates = function(){
    var templates = BaseState.prototype.templates();
    templates.deck = visibleDeckHtml;
    templates.p2Hand = visibleHandHtml;
    if(this.game.isScorePoints)
      templates.scoreControl = scoreControlHtml;
    return templates;
  };

  CountState.prototype.init = function(){
    this.p1.maxPoints = 29;
    this.p1.availablePoints = setAvailablePoints(this.p1.maxPoints);
    if(this.game.isScorePoints === undefined)
      this.game.isScorePoints = false;
    this.p1.restoreHand();
    this.p2.restoreHand();
    if(this.game.countStateStep === 0)
      processCountStep.call(this);

    else {
      this.render();
    }
  };

  CountState.prototype.action = function(){
    if(this.game.isScorePoints){
      this.game.countStateStep--;//hack to fix auto incriment
    }

    processCountStep.call(this);
  };

  CountState.prototype.bindEvents = function(){
    //bind defaults
    BaseState.prototype.bindEvents.call(this);

    scoreControlComp.init(this.p1);
  };

  function setAvailablePoints(size){
    var i = 0;
    var arrayPoints = [];
    while(i < size){
      i++;
      arrayPoints.push(i);
    }
    return arrayPoints;
  }

  function processCountStep(){
    var points = 0;
    if(this.game.countStateStep === 0)
      processFirstStep.call(this, points);
    else if(this.game.countStateStep === 1)
      processSecondStep.call(this, points);
    else if(this.game.countStateStep === 2)
      processThirdStep.call(this);
    else
      processEndOfCount.call(this);
  }

  function processFirstStep(points){
    if(isPlayerOneCribOwner.call(this)){
      evaluatePlayerTwoScore.call(this, points);
    } else {
      evaluatePlayerOneScore.call(this, points);
    }
    this.game.countStateStep += 1;
    this.render();
  }

  function processSecondStep(points){
    if(isPlayerOneCribOwner.call(this)){
      evaluatePlayerOneScore.call(this, points);
      this.p2.hand = [];
    } else {
      evaluatePlayerTwoScore.call(this, points);
      this.p1.hand = [];
    }
    this.game.countStateStep += 1;
    this.render();
  }

  function processThirdStep(){
    this.game.$cribOwner.hand = (this.game.$cribOwner.crib.length === 4) ? this.game.$cribOwner.crib : this.game.$cribOwner.hand;
    this.game.$cribOwner.crib = [];
    if(isPlayerOneCribOwner.call(this)){
      evaluatePlayerOneScore.call(this);
    } else {
      evaluatePlayerTwoScore.call(this);
    }
    this.game.countStateStep += 1;
    this.render();
  }

  function processEndOfCount(){
    if(isPlayerOneCribOwner.call(this)){
      this.game.$cribOwner = this.p2;
    } else {
      this.game.$cribOwner = this.p1;
    }
    showPlayerOneHand.call(this);
    this.game.$showTopCard = false;
    this.game.countStateStep = 0;
    this.render();
    if(this.p1.isWinner() || this.p2.isWinner())
      this.mediator.publish('transition', 'Summary', true);
    else {
      this.mediator.publish('transition', 'Deal');
    }
  }

  function evaluatePlayerOneScore(points){
    showPlayerOneHand.call(this);
    if(!this.game.isScorePoints){
      this.scoreKeeper.evaluateHand(this.p1, this.game.topCard);
      if(this.p1.isWinner())
        this.mediator.publish('transition', 'Summary', true);
    }
    return points;
  }

  function evaluatePlayerTwoScore(points){
    showPlayerTwoHand.call(this);
    this.scoreKeeper.evaluateHand(this.p2, this.game.topCard);
    if(this.p2.isWinner())
      this.mediator.publish('transition', 'Summary', true);
    return points;
  }

  function isPlayerOneCribOwner(){
    return this.game.$cribOwner === this.p1;
  }

  function showPlayerOneHand(){
    this.game.$player2HandVisible = false;
    this.game.$player1HandVisible = true;
    if(Settings.get('manual-count')){
      this.game.isScorePoints = this.game.isScorePoints ? false : true;
      if(this.game.isScorePoints)
        this.p1.selectedScore = 0;
    }
  }

  function showPlayerTwoHand(){
    this.game.$player2HandVisible = true;
    this.game.$player1HandVisible = false;
  }

  return CountState;
});
<|endoftext|>


<commit_before>/**
 * Kicks in the JSHint check on the sourcecode
 *
 * Copyright (C) 2011 Nikolay Nemshilov
 */

/**
 * Runs the JSHint check on the source code
 *
 * @param {Array} arguments
 * @return void
 */
exports.init = function(args) {
  var check  = require('jshint').JSHINT;
  var module = require('../package').parse(process.cwd() + '/package.json').name;
  var report;

  check(require('../source').compile(), {
    boss:   true,
    curly:  true,
    expr:   true
  });

  if (check.errors.length) {
    report = "\u001B[31m - Source check failed for '"+ module +"': \u001B[0m\n\n"

    check.errors.forEach(function(error) {
      if (error && error.id === '(error)') {
        for (var j=0, pointer=''; j < error.character-1; j++) { pointer += '-'; }

        report += "   \u001B[35m"+ error.reason +"\u001B[0m ";

        if (error.evidence) {
          report += "Line: "+ error.line + ", Char: "+ error.character + "\n";
          report += "   "+ error.evidence + "\n";
          report += "   \u001B[33m"+ pointer + "^\u001B[0m";
        }

        report += "\n\n";
      }
    });

  } else {
    report = " ✓ \u001B[32mOK\u001B[0m '"+ module + "'";
  }

  console.log(report);
};

exports.help = function(args) {
  console.log(
    "Checks the project source code against JSHint\n\n" +
    "Usage: lovely check"
  );
}<commit_msg>Source code checker formatting update<commit_after>/**
 * Kicks in the JSHint check on the sourcecode
 *
 * Copyright (C) 2011 Nikolay Nemshilov
 */

/**
 * Runs the JSHint check on the source code
 *
 * @param {Array} arguments
 * @return void
 */
exports.init = function(args) {
  var check  = require('jshint').JSHINT;
  var module = require('../package').parse(process.cwd() + '/package.json').name;
  var report;

  check(require('../source').compile(), {
    boss:   true,
    curly:  true,
    expr:   true
  });

  if (check.errors.length) {
    report = "\u001B[31m - Source check failed for '"+ module +"': \u001B[0m\n\n"

    check.errors.forEach(function(error) {
      if (error && error.id === '(error)') {
        for (var j=0, pointer=''; j < error.character-1; j++) { pointer += '-'; }

        report += "   \u001B[35m"+ error.reason +"\u001B[0m ";

        if (error.evidence) {
          report += "Line: "+ error.line + ", Char: "+ error.character + "\n";
          report += "   "+ error.evidence + "\n";
          report += "   \u001B[33m"+ pointer + "^\u001B[0m";
        }

        report += "\n\n";
      }
    });

  } else {
    report = "✓ \u001B[32mOK\u001B[0m » "+ module;
  }

  console.log(report);
};

exports.help = function(args) {
  console.log(
    "Checks the project source code against JSHint\n\n" +
    "Usage: lovely check"
  );
}<|endoftext|>


<commit_before>import _ from 'lodash'
// https://github.com/nickyout/fast-stable-stringify/issues/8#issuecomment-329455969
// import stringify from 'fast-stable-stringify'

import { TMP_ID_PREFIX } from '../constant'
import { load } from '../collection/load'
import { dispatchMutations } from '../store'
import { prepareFindData } from './findInMemory'

export const isPreloadSkip = (self, option) => !option.serverPreload && self.store && self.store.vanCtx.duringServerPreload

export function defaultGetQueryString(query, option, coll) {
  if (Array.isArray(query)) {
    query = { [coll.idField]: { $in: query } }
  }
  const opt = { ..._.omitBy(option, (v, k) => k[0] === '_'), query }
  const sortedKeys = _.keys(opt).sort()
  return _.map(sortedKeys, k => `${k}=${JSON.stringify(opt[k])}`).join('&')
}

// @auto-fold here
function markPromise(self, key, promise, overwrite) {
  const { _fetchingPromises } = self
  if (!overwrite) {
    const oldPromise = _fetchingPromises[key]
    if (oldPromise) return oldPromise
  }

  promise
    .then(ret => {
      if (_fetchingPromises[key] === promise) {
        delete _fetchingPromises[key]
        self.addMutation(null) // force render to update isFetching
      }
      return ret
    })
    .catch(err => {
      if (_fetchingPromises[key] === promise) {
        delete _fetchingPromises[key]
        self.addMutation(null) // force render to update isFetching
      }
      return Promise.reject(err)
    })
  _fetchingPromises[key] = promise
  return promise
}

const isTmpId = (id, tmpIdPrefix = TMP_ID_PREFIX) => !id || _.startsWith(id, tmpIdPrefix)
const sortUniqFilter = (ids, tmpIdPrefix) => _.filter(_.sortedUniq(ids.sort()), id => !isTmpId(id, tmpIdPrefix))
// @auto-fold here
function prepareFetchQuery(query, idField, tmpIdPrefix = TMP_ID_PREFIX) {
  if (Array.isArray(query)) {
    const ids = sortUniqFilter(query, tmpIdPrefix)
    if (ids.length === 0) {
      return false
    }
    return ids
  }

  const fetchQuery = { ...query }
  const entries = Object.entries(query)
  for (let i = 0, ii = entries.length; i < ii; i++) {
    const [key, matcher] = entries[i]
    if (matcher) {
      if (typeof matcher === 'string' && isTmpId(matcher, tmpIdPrefix)) {
        return false
      } else if (matcher.$in) {
        const $in = sortUniqFilter(matcher.$in, tmpIdPrefix)
        if ($in.length === 0) {
          return false
        }
        fetchQuery[key] = { $in }
      }
    } else if (key === idField) {
      // idField is falsy
      return false
    }
  }
  return fetchQuery
}

export function findRemote(coll, query, option) {
  const notForce = !option.force

  prepareFindData(coll, query, option)
  if (notForce && option._allIdsHit) return false

  const fetchQuery = prepareFetchQuery(query, coll.idField)
  if (notForce && fetchQuery === false) return false

  const queryString = (coll.getQueryString || defaultGetQueryString)(fetchQuery, option, coll)
  if (notForce && queryString === false) return false
  option.queryString = queryString

  if (notForce) {
    const { fetchAts } = coll.getState()
    const now = Date.now()
    // collection.fetchMaxAge: 1, // in seconds; null, 0 or -1 means no maxAge
    const { fetchMaxAge } = coll
    if (fetchMaxAge > 0 ? fetchAts[queryString] > now - fetchMaxAge : fetchAts[queryString]) {
      return false
    }
    fetchAts[queryString] = now
  }

  // want to return fetching promise for findAsync
  const { onFetch } = coll
  const p = Promise.resolve(onFetch(fetchQuery, option, coll)).then(res => {
    load(coll, res)
    // flush dispatch mutates after load()
    dispatchMutations(coll.store)
    return res
  })
  return markPromise(coll, queryString, p)
}
<commit_msg>feat: add fetchingAt state<commit_after>import _ from 'lodash'
// https://github.com/nickyout/fast-stable-stringify/issues/8#issuecomment-329455969
// import stringify from 'fast-stable-stringify'

import { TMP_ID_PREFIX } from '../constant'
import { load } from '../collection/load'
import { dispatchMutations } from '../store'
import { prepareFindData } from './findInMemory'

export const isPreloadSkip = (self, option) => !option.serverPreload && self.store && self.store.vanCtx.duringServerPreload

export function defaultGetQueryString(query, option, coll) {
  if (Array.isArray(query)) {
    query = { [coll.idField]: { $in: query } }
  }
  const opt = { ..._.omitBy(option, (v, k) => k[0] === '_'), query }
  const sortedKeys = _.keys(opt).sort()
  return _.map(sortedKeys, k => `${k}=${JSON.stringify(opt[k])}`).join('&')
}

// @auto-fold here
function markPromiseFinally(self, key, promise) {
  const { _fetchingPromises } = self
  if (_fetchingPromises[key] === promise) {
    delete _fetchingPromises[key]
    if (Object.keys(_fetchingPromises).length === 0) {
      self.addMutation({ $merge: { fetchingAt: undefined } })
    }
  }
}
function markPromise(self, key, promise) {
  const { _fetchingPromises } = self
  // if (!overwrite) {
  const oldPromise = _fetchingPromises[key]
  if (oldPromise) return oldPromise
  // }

  promise
    .then(ret => {
      markPromiseFinally(self, key, promise)
      return ret
    })
    .catch(err => {
      markPromiseFinally(self, key, promise)
      return Promise.reject(err)
    })
  _fetchingPromises[key] = promise
  self.addMutation({ $merge: { fetchingAt: Date.now() } })
  return promise
}

const isTmpId = (id, tmpIdPrefix = TMP_ID_PREFIX) => !id || _.startsWith(id, tmpIdPrefix)
const sortUniqFilter = (ids, tmpIdPrefix) => _.filter(_.sortedUniq(ids.sort()), id => !isTmpId(id, tmpIdPrefix))
// @auto-fold here
function prepareFetchQuery(query, idField, tmpIdPrefix = TMP_ID_PREFIX) {
  if (Array.isArray(query)) {
    const ids = sortUniqFilter(query, tmpIdPrefix)
    if (ids.length === 0) {
      return false
    }
    return ids
  }

  const fetchQuery = { ...query }
  const entries = Object.entries(query)
  for (let i = 0, ii = entries.length; i < ii; i++) {
    const [key, matcher] = entries[i]
    if (matcher) {
      if (typeof matcher === 'string' && isTmpId(matcher, tmpIdPrefix)) {
        return false
      } else if (matcher.$in) {
        const $in = sortUniqFilter(matcher.$in, tmpIdPrefix)
        if ($in.length === 0) {
          return false
        }
        fetchQuery[key] = { $in }
      }
    } else if (key === idField) {
      // idField is falsy
      return false
    }
  }
  return fetchQuery
}

export function findRemote(coll, query, option) {
  const notForce = !option.force

  prepareFindData(coll, query, option)
  if (notForce && option._allIdsHit) return false

  const fetchQuery = prepareFetchQuery(query, coll.idField)
  if (notForce && fetchQuery === false) return false

  const queryString = (coll.getQueryString || defaultGetQueryString)(fetchQuery, option, coll)
  if (notForce && queryString === false) return false
  option.queryString = queryString

  if (notForce) {
    const { fetchAts } = coll.getState()
    const now = Date.now()
    // collection.fetchMaxAge: 1, // in seconds; null, 0 or -1 means no maxAge
    const { fetchMaxAge } = coll
    if (fetchMaxAge > 0 ? fetchAts[queryString] > now - fetchMaxAge : fetchAts[queryString]) {
      return false
    }
    fetchAts[queryString] = now
  }

  // want to return fetching promise for findAsync
  const { onFetch } = coll
  const p = Promise.resolve(onFetch(fetchQuery, option, coll)).then(res => {
    load(coll, res)
    // flush dispatch mutates after load()
    dispatchMutations(coll.store)
    return res
  })
  return markPromise(coll, queryString, p)
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import VersionNumber from 'react-native-version-number';
import Hyperlink from 'react-native-hyperlink';
import {
    Linking,
    View,
    Platform,
    ScrollView,
    Image,
    Text
} from 'react-native';
import I18n from 'react-native-i18n';
import Config from '../../constants/Config';

class About extends Component {

    render() {
        return (
            <View style={styles.bgColor} >
                <ScrollView
                    automaticallyAdjustContentInsets={false}
                    scrollEventThrottle={200}
                    style={styles.scrollView}
                >
        <View style={styles.container}>
          <View style={styles.containerAbout}>
            <Image style={styles.kortlogo} source={{ uri: 'kort_logo' }} />
            <Text style={styles.textTitle}>{I18n.t('about_version_title')}</Text>
            <Text style={styles.textSubTitle}>{VersionNumber.appVersion}</Text>
            <Text style={styles.textTitle}>{I18n.t('about_information_title')}</Text>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                {`${I18n.t('about_information_homepage')} ${Config.KORT_WEBSITE}`}
                </Text>
            </Hyperlink>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                {`${I18n.t('about_information_feedback')} ${Config.KORT_USERVOICE}`}
                </Text>
            </Hyperlink>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                {`${I18n.t('about_information_bugs')} ${Config.KORT_GITHUB}`}
                </Text>
            </Hyperlink>
            <Text style={styles.textTitle}>{I18n.t('about_developers_title')}</Text>
            <Text style={styles.textSubTitle}>Andreas Egloff</Text>
            <Text style={styles.textSubTitle}>Jürg Hunziker</Text>
            <Text style={styles.textSubTitle}>Stefan Oderbolz</Text>
            <Text style={styles.textTitle}>{I18n.t('about_project_title')}</Text>
            <Text style={styles.textSubTitle}>Master's Thesis 2017</Text>
            <Text style={styles.textSubTitle}>HSR Hochschule für Technik Rapperswil</Text>
            <Text style={styles.textSubTitle}>
              {I18n.t('about_project_advisor')} Prof. Stefan Keller
            </Text>
            <Image
                style={styles.hsrlogo}
                source={require('../../../assets/images/about/hsr_logo.png')}
            />
            <Text style={styles.textTitle}>{I18n.t('about_credits_title')}</Text>
            <Text style={styles.textSubTitle}>{I18n.t('about_credits_partner')} Liip AG</Text>
            <Text style={styles.textSubTitle}>
              {I18n.t('about_credits_tiledata')} Klokan Technologies
            </Text>
            <Hyperlink
                onPress={url => Linking.openURL(url)}
                linkText={url => {
                    if (url === 'http://www.flaticon.com/authors/freepik') {
                        return 'Freepik';
                    } else if (url === 'http://www.flaticon.com/authors/cursor-creative') {
                        return 'Cursor Creative';
                    }
                        return 'www.flaticon.com';
                    }
                }
            >
                <Text style={styles.textSubTitle}>
                {I18n.t('about_credits_markers')}
                Icon made by http://www.flaticon.com/authors/freepik, http://www.flaticon.com/authors/cursor-creative from www.flaticon.com
                </Text>
            </Hyperlink>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                Fonts: FontAwesome, Ionicons, MaterialIcons
                </Text>
            </Hyperlink>
            <Text style={styles.textTitle}>{I18n.t('about_legal_title')}</Text>
            <Text style={styles.textSubTitle}>{I18n.t('about_legal_message')}</Text>
          </View>
        </View>
      </ScrollView>
            </View>
        );
    }
}

const styles = {
    bgColor: {
        marginTop: (Platform.OS === 'ios') ? 64 : 54,
        backgroundColor: '#202931',
        flex: 1
    },
    scrollView: {
    marginBottom: 46,
  },
  container: {
    flex: 1,
    padding: 20,
  },
  containerAbout: {
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
    backgroundColor: '#395971',
    borderColor: '#657C8E',
    borderRadius: 5,
    borderWidth: 1,
    paddingLeft: 5,
    paddingRight: 5,
    paddingTop: 10,
    paddingBottom: 10

  },
  textTitle: {
    textAlign: 'center',
    fontSize: 18,
    marginTop: 7,
    color: 'white'
  },
  textSubTitle: {
    marginTop: 5,
    color: 'white'
  },
  kortlogo: {
    alignSelf: 'center',
    marginTop: 7,
    height: 128,
    width: 128,
  },
  hsrlogo: {
    alignSelf: 'center',
    marginTop: 10,
    marginBottom: 10,
    height: 40,
    width: 150,
  },
};

export default (About);
<commit_msg>added additional icon contributor<commit_after>import React, { Component } from 'react';
import VersionNumber from 'react-native-version-number';
import Hyperlink from 'react-native-hyperlink';
import {
    Linking,
    View,
    Platform,
    ScrollView,
    Image,
    Text
} from 'react-native';
import I18n from 'react-native-i18n';
import Config from '../../constants/Config';

class About extends Component {

    render() {
        return (
            <View style={styles.bgColor} >
                <ScrollView
                    automaticallyAdjustContentInsets={false}
                    scrollEventThrottle={200}
                    style={styles.scrollView}
                >
        <View style={styles.container}>
          <View style={styles.containerAbout}>
            <Image style={styles.kortlogo} source={{ uri: 'kort_logo' }} />
            <Text style={styles.textTitle}>{I18n.t('about_version_title')}</Text>
            <Text style={styles.textSubTitle}>{VersionNumber.appVersion}</Text>
            <Text style={styles.textTitle}>{I18n.t('about_information_title')}</Text>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                {`${I18n.t('about_information_homepage')} ${Config.KORT_WEBSITE}`}
                </Text>
            </Hyperlink>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                {`${I18n.t('about_information_feedback')} ${Config.KORT_USERVOICE}`}
                </Text>
            </Hyperlink>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                {`${I18n.t('about_information_bugs')} ${Config.KORT_GITHUB}`}
                </Text>
            </Hyperlink>
            <Text style={styles.textTitle}>{I18n.t('about_developers_title')}</Text>
            <Text style={styles.textSubTitle}>Andreas Egloff</Text>
            <Text style={styles.textSubTitle}>Jürg Hunziker</Text>
            <Text style={styles.textSubTitle}>Stefan Oderbolz</Text>
            <Text style={styles.textTitle}>{I18n.t('about_project_title')}</Text>
            <Text style={styles.textSubTitle}>Master's Thesis 2017</Text>
            <Text style={styles.textSubTitle}>HSR Hochschule für Technik Rapperswil</Text>
            <Text style={styles.textSubTitle}>
              {I18n.t('about_project_advisor')} Prof. Stefan Keller
            </Text>
            <Image
                style={styles.hsrlogo}
                source={require('../../../assets/images/about/hsr_logo.png')}
            />
            <Text style={styles.textTitle}>{I18n.t('about_credits_title')}</Text>
            <Text style={styles.textSubTitle}>{I18n.t('about_credits_partner')} Liip AG</Text>
            <Text style={styles.textSubTitle}>
              {I18n.t('about_credits_tiledata')} Klokan Technologies
            </Text>
            <Hyperlink
                onPress={url => Linking.openURL(url)}
                linkText={url => {
                    if (url === 'http://www.flaticon.com/authors/freepik') {
                        return 'Freepik';
                    } else if (url === 'http://www.flaticon.com/authors/cursor-creative') {
                        return 'Cursor Creative';
                    } else if (url === 'http://www.flaticon.com/authors/hevngrafix') {
                        return 'HevnGrafix';
                    }
                        return 'www.flaticon.com';
                    }
                }
            >
                <Text style={styles.textSubTitle}>
                {I18n.t('about_credits_markers')}
                Icon made by http://www.flaticon.com/authors/freepik, http://www.flaticon.com/authors/cursor-creative, http://www.flaticon.com/authors/hevngrafix from www.flaticon.com
                </Text>
            </Hyperlink>
            <Hyperlink onPress={url => Linking.openURL(url)}>
                <Text style={styles.textSubTitle}>
                Fonts: FontAwesome, Ionicons, MaterialIcons
                </Text>
            </Hyperlink>
            <Text style={styles.textTitle}>{I18n.t('about_legal_title')}</Text>
            <Text style={styles.textSubTitle}>{I18n.t('about_legal_message')}</Text>
          </View>
        </View>
      </ScrollView>
            </View>
        );
    }
}

const styles = {
    bgColor: {
        marginTop: (Platform.OS === 'ios') ? 64 : 54,
        backgroundColor: '#202931',
        flex: 1
    },
    scrollView: {
    marginBottom: 46,
  },
  container: {
    flex: 1,
    padding: 20,
  },
  containerAbout: {
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
    backgroundColor: '#395971',
    borderColor: '#657C8E',
    borderRadius: 5,
    borderWidth: 1,
    paddingLeft: 5,
    paddingRight: 5,
    paddingTop: 10,
    paddingBottom: 10

  },
  textTitle: {
    textAlign: 'center',
    fontSize: 18,
    marginTop: 7,
    color: 'white'
  },
  textSubTitle: {
    marginTop: 5,
    color: 'white'
  },
  kortlogo: {
    alignSelf: 'center',
    marginTop: 7,
    height: 128,
    width: 128,
  },
  hsrlogo: {
    alignSelf: 'center',
    marginTop: 10,
    marginBottom: 10,
    height: 40,
    width: 150,
  },
};

export default (About);
<|endoftext|>