<commit_before>/*!
 * @license MIT
 * @author Marek Kalnik
 * @copyright (c) Maisons du Monde
 */
;(function ($, document)
{
    "use strict";

    $.fn.MDMImageViewport = function (images, settings)
    {
        if (!$.isArray(images) || images.length === 0)
        {
            throw "MDMImageViewport: You need to pass an non-empty array of image paths to viewport on instantiation";
        }

        return this.each(function ()
        {
            var container = $(this),
                config = $.extend({}, settings),
                cache,

                props = {
                    loaded:false,
                    images:[],
                    current:0,
                    nbImages:0
                },

                methods = {
                    construct:function ()
                    {
                        $(document).bind('mdm-animation.beat', methods.eventChangeImage);
                        container.addClass('mdm-image-viewport');
                        container.append('

');
                        cache = container.children('.cache');
                        cache.hide();

                        if (config.width)
                        {
                            methods.setWidth(config.width);
                        }

                        if (config.height)
                        {
                            methods.setHeight(config.height);
                        }

                        methods.loadImages(images);
                        container.data('maxImages', props.nbImages);
                    },
                    loadImages:function (images)
                    {
                        var image = new Image(), i, len;

                        props.loaded = false;
                        props.images = images;

                        image.src = images[0];

                        image.onload = function ()
                        {
                            if (typeof config.width === 'undefined')
                            {
                                methods.setWidth('auto');
                            }
                            if (typeof config.height === 'undefined')
                            {
                                methods.setHeight('auto');
                            }
                        };
                        cache.append($(document.createElement('img')).attr({src: images[0]}));

                        for (i = 1, len = images.length; i < len; i++)
                        {
                            image = new Image();
                            image.src = images[i];
                            cache.append($(document.createElement('img')).attr({src: images[i]}));
                        }

                        props.nbImages = len;
                        props.loaded = true;
                        methods.setContainerImage(0);
                    },
                    eventChangeImage:function (event, data)
                    {
                        if (typeof props.images[data.current] !== 'undefined')
                        {
                            methods.setContainerImage(data.current);
                        }
                    },
                    setContainerImage:function (index)
                    {
                        container.find('img').first().attr('src', props.images[index]);
                    },
                    setWidth:function (width)
                    {
                        container.width(width);
                        container.find('img').first().width(width);
                    },
                    setHeight:function (height)
                    {
                        container.height(height);
                        container.find('img').first().height(height);
                    }
                };

            methods.construct();
        });
    };
})(jQuery, document);
<commit_msg>Prepare for more intelligent preloader<commit_after>/*!
 * @license MIT
 * @author Marek Kalnik
 * @copyright (c) Maisons du Monde
 */
;(function ($, document)
{
    "use strict";

    $.fn.MDMImageViewport = function (images, settings)
    {
        if (!$.isArray(images) || images.length === 0)
        {
            throw "MDMImageViewport: You need to pass an non-empty array of image paths to viewport on instantiation";
        }

        return this.each(function ()
        {
            var container = $(this),
                config = $.extend({}, settings),
                cache,

                props = {
                    loaded:false,
                    images:[],
                    current:0,
                    nbImages:0,
                    loadedImages:0
                },

                methods = {
                    construct:function ()
                    {
                        $(document).bind('mdm-animation.beat', methods.eventChangeImage);
                        container.addClass('mdm-image-viewport');
                        container.append('

');
                        cache = container.children('.cache');
                        cache.hide();

                        if (config.width)
                        {
                            methods.setWidth(config.width);
                        }

                        if (config.height)
                        {
                            methods.setHeight(config.height);
                        }

                        methods.loadImages(images);
                        container.data('maxImages', props.nbImages);
                    },
                    loadImages:function (images)
                    {
                        var image = new Image(), i, len;

                        props.loaded = false;
                        props.images = images;

                        image.src = images[0];

                        image.onload = function ()
                        {
                            if (typeof config.width === 'undefined')
                            {
                                methods.setWidth('auto');
                            }
                            if (typeof config.height === 'undefined')
                            {
                                methods.setHeight('auto');
                            }

                            methods.imageLoaded();
                        };
                        cache.append($(document.createElement('img')).attr({src: images[0]}));

                        for (i = 1, len = images.length; i < len; i++)
                        {
                            image = new Image();
                            image.src = images[i];
                            image.onload = methods.imageLoaded;
                            cache.append($(document.createElement('img')).attr({src: images[i]}));
                        }

                        props.nbImages = len;
                    },
                    imageLoaded: function()
                    {
                        props.loadedImages++;
                        if (props.loadedImages === props.nbImages)
                        {
                            props.loaded = true;
                            $(document).trigger('mdm-image-viewport.images-loaded');
                            methods.setContainerImage(0);
                        }
                    },
                    eventChangeImage:function (event, data)
                    {
                        if (typeof props.images[data.current] !== 'undefined')
                        {
                            methods.setContainerImage(data.current);
                        }
                    },
                    setContainerImage:function (index)
                    {
                        container.find('img').first().attr('src', props.images[index]);
                    },
                    setWidth:function (width)
                    {
                        container.width(width);
                        container.find('img').first().width(width);
                    },
                    setHeight:function (height)
                    {
                        container.height(height);
                        container.find('img').first().height(height);
                    }
                };

            methods.construct();
        });
    };
})(jQuery, document);
<|endoftext|>


<commit_before>define([
  'chaplin',
  'models/base/model'
], function(Chaplin, Model) {
  'use strict';

  var HelloWorld = Model.extend({

    defaults: {
      message: 'Hello World!'
    }

    //,initialize: function(attributes, options) {
      //Model.apply(this, arguments);
      //console.debug('HelloWorld#initialize');
    //}

  });

  return HelloWorld;
});
<commit_msg>Update hello_world.js<commit_after>define([
  'chaplin',
  'models/base/model'
], function(Chaplin, Model) {
  'use strict';

  var HelloWorld = Model.extend({

    defaults: {
      message: 'Hello World!'
    }

    //,initialize: function(attributes, options) {
    //  Model.prototype.initialize.apply(this, arguments);
    //  console.debug('HelloWorld#initialize');
    //}

  });

  return HelloWorld;
});
<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var fs = require('fs');

var hiscoresUrl = 'http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=';

var playerName = 'Max Deviant';

http.get(hiscoresUrl + playerName, function (res) {
    var data = [];

    res.on('data', function (chunk) {
        data.push(chunk);
    });

    res.on('end', function () {
        var stats = extractStats(data.join().split('\n'));

        fs.readFile('quests.json', 'utf8', function (err, data) {
            if (err) {
                console.log(err);

                return;
            }

            var tracker = new Quests(JSON.parse(data), stats);

            tracker.completeQuests(['black-knights-fortress', 'cooks-assistant', 'creature-of-fenkenstrain', 'demon-slayer', 'druidic-ritual', 'dorics-quest', 'the-digsite', 'dragon-slayer', 'elemental-workshop-1', 'elemental-workshop-2', 'fishing-contest', 'goblin-diplomacy', 'imp-catcher', 'the-knights-sword', 'pirates-treasure', 'priest-in-peril', 'prince-ali-rescue', 'the-restless-ghost', 'romeo-and-juliet', 'rune-mysteries', 'sheep-shearer', 'a-souls-bane', 'tears-of-guthix', 'vampire-slayer', 'waterfall-quest', 'witchs-potion', 'nature-spirit']);

            console.log(tracker.listRequirements('lunar-diplomacy'))
            console.log(tracker.computeTotalRequirements('lunar-diplomacy'));

            console.log(tracker.recommendNext());

            var xp = new XP();
        });
    });
}).end();

function extractStats(raw) {
    var stats = {};

    var skills = ['overall', 'attack', 'defence', 'strength', 'constitution', 'ranged', 'prayer', 'magic', 'cooking', 'woodcutting', 'fletching', 'fishing', 'firemaking', 'crafting', 'smithing', 'mining', 'herblore', 'agility', 'thieving', 'slayer', 'farming', 'runecrafting', 'hunter', 'construction'];

    for (var i in skills) {
        var row = raw[i].split(',');

        stats[skills[i]] = {
            rank: row[0],
            level: row[1],
            xp: row[2]
        };
    }

    return stats;
}

function grep(array, key, value) {
    for (var i in array) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
}

var XP = function () {
    this.chart = {};

    this.init = function () {
        var xp, sum, last, diff;

        for (var level = 1; level < 100; level++) {
            last = xp;
            sum = 0;

            for (var x = 1; x <= level - 1; x++) {
                sum += Math.floor(x + 300 * Math.pow(2, x / 7));
            }

            xp = Math.floor(sum / 4);

            diff = xp - last;

            this.chart[level] = {
                xp: xp,
                diff: diff
            };
        }
    };

    this.atLevel = function (level) {
        return this.chart[level].xp;
    };

    this.forLevel = function (level, currExp) {
        return this.chart[level].xp - currExp;
    };

    this.getLevel = function (currExp, gainedExp) {
        var newExp = parseInt(currExp) + parseInt(gainedExp);

        for (var i = 1; i < 100; i++) {
            if (newExp >= this.chart[i].xp) {
                continue;
            }

            return i;
        }

        return 99;
    };

    this.init();
};

var Quests = function (questList, stats) {
    this.list = questList;
    this.stats = stats;
    this.completed = {
        count: 0,
        percent: 0,
        list: {}
    };

    this.findQuest = function (questName) {
        return grep(this.list, 'slug', questName) || grep(this.list, 'name', questName);
    };

    this.findAvailable = function () {
        var available = [];

        for (var i in this.list) {
            var canDo = true;
            var skillReqs = this.list[i].requirements.skills;
            var questReqs = this.list[i].requirements.quests;

            if (this.completed.list[this.list[i].slug]) {
                continue;
            }

            if (this.hasRequirements(this.list[i].slug)) {
                available.push(this.list[i].slug);
            }
        }

        return available;
    };

    this.listRequirements = function (questName) {
        var quest = this.findQuest(questName);

        return quest.requirements;
    };

    this.hasSkillRequirements = function (questName) {
        var hasStats = true;
        var quest = this.findQuest(questName);
        var skillReqs = quest.requirements.skills;

        for (var i in skillReqs) {
            if (this.stats[i].level < skillReqs[i]) {
                hasStats = false;
            }
        }

        return hasStats;
    };

    this.hasQuestRequirements = function (questName) {
        var hasQuests = true;
        var quest = this.findQuest(questName);
        var questReqs = quest.requirements.quests;

        for (var i in questReqs) {
            if (!this.completed.list[questReqs[i]]) {
                hasQuests = false;
            }
        }

        return hasQuests;
    };

    this.hasRequirements = function (questName) {
        return this.hasSkillRequirements(questName) && this.hasQuestRequirements(questName);
    };

    this.completeQuest = function (quest) {
        this.completeQuests([quest]);
    };

    this.completeQuests = function (quests) {
        for (var i in quests) {
            this.completed.list[quests[i]] = true;
            this.completed.count++;
        }
    };

    this.getCompleted = function () {
        return {
            count: this.completed.count,
            percent: Math.round((this.completed.count / this.list.length) * 100),
            quests: Object.keys(this.completed.list)
        };
    };

    this.computeTotalRequirements = function (questName) {
        var quest = this.findQuest(questName);

        var skillReqs = quest.requirements.skills;
        var questReqs = quest.requirements.quests;

        var totalSkills = {};
        var totalQuests = [];

        for (var i in skillReqs) {
            totalSkills[i] = skillReqs[i];
        }

        for (var i in questReqs) {
            var priorReqs = this.computeTotalRequirements(questReqs[i]);

            for (var j in priorReqs.skills) {
                if (typeof totalSkills[j] === 'undefined' || priorReqs.skills[j] > totalSkills[j]) {
                    totalSkills[j] = priorReqs.skills[j];
                }
            }

            for (var j in priorReqs.quests) {
                if (totalQuests.indexOf(priorReqs.quests[j]) === -1) {
                    totalQuests.push(priorReqs.quests[j]);
                }
            }

            if (totalQuests.indexOf(questReqs[i]) === -1) {
                totalQuests.push(questReqs[i]);
            }
        }

        return {
            skills: totalSkills,
            quests: totalQuests
        };
    };

    this.recommendNext = function () {
        var xp = new XP();
        var recommended = [];

        var neededExp = {};

        for (var i in this.list) {
            if (this.completed.list[this.list[i].slug]) {
                continue;
            }

            var skillReqs = this.list[i].requirements.skills;
            var total = 0;

            neededExp[this.list[i].slug] = 0;

            for (var j in skillReqs) {

                if (skillReqs[j] > this.stats[j].level) {
                    neededExp[this.list[i].slug] += xp.forLevel(skillReqs[j], this.stats[j].xp);
                }
            }
        }

        var lowest = {};

        for (var i in neededExp) {
            if (typeof lowest.xp === 'undefined' || neededExp[i] < lowest.xp) {
                lowest.quest = i;
                lowest.xp = neededExp[i];

                if (this.hasQuestRequirements(i)) {
                    recommended.push(i);
                }
            } else if (lowest.xp === neededExp[i]) {
                if (this.hasQuestRequirements(i)) {
                    recommended.push(i);
                }
            }
        }

        return recommended;
    };
};<commit_msg>Add missing semicolon<commit_after>'use strict';

var http = require('http');
var fs = require('fs');

var hiscoresUrl = 'http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=';

var playerName = 'Max Deviant';

http.get(hiscoresUrl + playerName, function (res) {
    var data = [];

    res.on('data', function (chunk) {
        data.push(chunk);
    });

    res.on('end', function () {
        var stats = extractStats(data.join().split('\n'));

        fs.readFile('quests.json', 'utf8', function (err, data) {
            if (err) {
                console.log(err);

                return;
            }

            var tracker = new Quests(JSON.parse(data), stats);

            tracker.completeQuests(['black-knights-fortress', 'cooks-assistant', 'creature-of-fenkenstrain', 'demon-slayer', 'druidic-ritual', 'dorics-quest', 'the-digsite', 'dragon-slayer', 'elemental-workshop-1', 'elemental-workshop-2', 'fishing-contest', 'goblin-diplomacy', 'imp-catcher', 'the-knights-sword', 'pirates-treasure', 'priest-in-peril', 'prince-ali-rescue', 'the-restless-ghost', 'romeo-and-juliet', 'rune-mysteries', 'sheep-shearer', 'a-souls-bane', 'tears-of-guthix', 'vampire-slayer', 'waterfall-quest', 'witchs-potion', 'nature-spirit']);

            console.log(tracker.listRequirements('lunar-diplomacy'));
            console.log(tracker.computeTotalRequirements('lunar-diplomacy'));

            console.log(tracker.recommendNext());

            var xp = new XP();
        });
    });
}).end();

function extractStats(raw) {
    var stats = {};

    var skills = ['overall', 'attack', 'defence', 'strength', 'constitution', 'ranged', 'prayer', 'magic', 'cooking', 'woodcutting', 'fletching', 'fishing', 'firemaking', 'crafting', 'smithing', 'mining', 'herblore', 'agility', 'thieving', 'slayer', 'farming', 'runecrafting', 'hunter', 'construction'];

    for (var i in skills) {
        var row = raw[i].split(',');

        stats[skills[i]] = {
            rank: row[0],
            level: row[1],
            xp: row[2]
        };
    }

    return stats;
}

function grep(array, key, value) {
    for (var i in array) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
}

var XP = function () {
    this.chart = {};

    this.init = function () {
        var xp, sum, last, diff;

        for (var level = 1; level < 100; level++) {
            last = xp;
            sum = 0;

            for (var x = 1; x <= level - 1; x++) {
                sum += Math.floor(x + 300 * Math.pow(2, x / 7));
            }

            xp = Math.floor(sum / 4);

            diff = xp - last;

            this.chart[level] = {
                xp: xp,
                diff: diff
            };
        }
    };

    this.atLevel = function (level) {
        return this.chart[level].xp;
    };

    this.forLevel = function (level, currExp) {
        return this.chart[level].xp - currExp;
    };

    this.getLevel = function (currExp, gainedExp) {
        var newExp = parseInt(currExp) + parseInt(gainedExp);

        for (var i = 1; i < 100; i++) {
            if (newExp >= this.chart[i].xp) {
                continue;
            }

            return i;
        }

        return 99;
    };

    this.init();
};

var Quests = function (questList, stats) {
    this.list = questList;
    this.stats = stats;
    this.completed = {
        count: 0,
        percent: 0,
        list: {}
    };

    this.findQuest = function (questName) {
        return grep(this.list, 'slug', questName) || grep(this.list, 'name', questName);
    };

    this.findAvailable = function () {
        var available = [];

        for (var i in this.list) {
            var canDo = true;
            var skillReqs = this.list[i].requirements.skills;
            var questReqs = this.list[i].requirements.quests;

            if (this.completed.list[this.list[i].slug]) {
                continue;
            }

            if (this.hasRequirements(this.list[i].slug)) {
                available.push(this.list[i].slug);
            }
        }

        return available;
    };

    this.listRequirements = function (questName) {
        var quest = this.findQuest(questName);

        return quest.requirements;
    };

    this.hasSkillRequirements = function (questName) {
        var hasStats = true;
        var quest = this.findQuest(questName);
        var skillReqs = quest.requirements.skills;

        for (var i in skillReqs) {
            if (this.stats[i].level < skillReqs[i]) {
                hasStats = false;
            }
        }

        return hasStats;
    };

    this.hasQuestRequirements = function (questName) {
        var hasQuests = true;
        var quest = this.findQuest(questName);
        var questReqs = quest.requirements.quests;

        for (var i in questReqs) {
            if (!this.completed.list[questReqs[i]]) {
                hasQuests = false;
            }
        }

        return hasQuests;
    };

    this.hasRequirements = function (questName) {
        return this.hasSkillRequirements(questName) && this.hasQuestRequirements(questName);
    };

    this.completeQuest = function (quest) {
        this.completeQuests([quest]);
    };

    this.completeQuests = function (quests) {
        for (var i in quests) {
            this.completed.list[quests[i]] = true;
            this.completed.count++;
        }
    };

    this.getCompleted = function () {
        return {
            count: this.completed.count,
            percent: Math.round((this.completed.count / this.list.length) * 100),
            quests: Object.keys(this.completed.list)
        };
    };

    this.computeTotalRequirements = function (questName) {
        var quest = this.findQuest(questName);

        var skillReqs = quest.requirements.skills;
        var questReqs = quest.requirements.quests;

        var totalSkills = {};
        var totalQuests = [];

        for (var i in skillReqs) {
            totalSkills[i] = skillReqs[i];
        }

        for (var i in questReqs) {
            var priorReqs = this.computeTotalRequirements(questReqs[i]);

            for (var j in priorReqs.skills) {
                if (typeof totalSkills[j] === 'undefined' || priorReqs.skills[j] > totalSkills[j]) {
                    totalSkills[j] = priorReqs.skills[j];
                }
            }

            for (var j in priorReqs.quests) {
                if (totalQuests.indexOf(priorReqs.quests[j]) === -1) {
                    totalQuests.push(priorReqs.quests[j]);
                }
            }

            if (totalQuests.indexOf(questReqs[i]) === -1) {
                totalQuests.push(questReqs[i]);
            }
        }

        return {
            skills: totalSkills,
            quests: totalQuests
        };
    };

    this.recommendNext = function () {
        var xp = new XP();
        var recommended = [];

        var neededExp = {};

        for (var i in this.list) {
            if (this.completed.list[this.list[i].slug]) {
                continue;
            }

            var skillReqs = this.list[i].requirements.skills;
            var total = 0;

            neededExp[this.list[i].slug] = 0;

            for (var j in skillReqs) {

                if (skillReqs[j] > this.stats[j].level) {
                    neededExp[this.list[i].slug] += xp.forLevel(skillReqs[j], this.stats[j].xp);
                }
            }
        }

        var lowest = {};

        for (var i in neededExp) {
            if (typeof lowest.xp === 'undefined' || neededExp[i] < lowest.xp) {
                lowest.quest = i;
                lowest.xp = neededExp[i];

                if (this.hasQuestRequirements(i)) {
                    recommended.push(i);
                }
            } else if (lowest.xp === neededExp[i]) {
                if (this.hasQuestRequirements(i)) {
                    recommended.push(i);
                }
            }
        }

        return recommended;
    };
};<|endoftext|>


<commit_before><commit_msg>use "status"<commit_after><|endoftext|>


<commit_before>const Graph = require('../../graph')
const accessor = require('../../utils/accessor')
const cycleRemoval = require('../../layouter/sugiyama/cycle-removal')
const layerAssignment = require('../../layouter/sugiyama/layer-assignment')
const groupLayers = require('../../layouter/sugiyama/misc/group-layers')
const rectangular = require('./rectangular')

const edgeConcentration = (g, h1, h2, method, dummy, idGenerator) => {
  const subgraph = new Graph()
  for (const u of h1) {
    subgraph.addVertex(u, g.vertex(u))
  }
  for (const u of h2) {
    subgraph.addVertex(u, g.vertex(u))
  }
  for (const u of h1) {
    for (const v of h2) {
      if (g.edge(u, v)) {
        subgraph.addEdge(u, v, g.edge(u, v))
      }
    }
  }

  for (const concentration of method(subgraph, h1, h2)) {
    const w = idGenerator(g, h1, h2)
    g.addVertex(w, dummy(concentration.source, concentration.target))
    for (const u of concentration.source) {
      g.addEdge(u, w)
    }
    for (const v of concentration.target) {
      g.addEdge(w, v)
    }
    for (const u of g.inVertices(w)) {
      for (const v of g.outVertices(w)) {
        if (g.edge(u, v)) {
          g.removeEdge(u, v)
        }
      }
    }
  }
}

const privates = new WeakMap()

class EdgeConcentrationTransformer {
  constructor () {
    privates.set(this, {
      cycleRemoval: new cycleRemoval.CycleRemoval(),
      layerAssignment: new layerAssignment.QuadHeuristic(),
      method: rectangular,
      dummy: () => ({dummy: true}),
      idGenerator: () => Symbol()
    })
  }

  transform (g) {
    this.cycleRemoval().call(g)
    const layerMap = this.layerAssignment().call(g)
    const layers = groupLayers(g, layerMap)
    for (let i = 0; i < layers.length - 1; ++i) {
      const h1 = layers[i]
      const h2 = new Set()
      let edges = 0
      for (const u of h1) {
        for (const v of g.outVertices(u)) {
          h2.add(v)
          edges += 1
        }
      }
      edgeConcentration(g, h1, Array.from(h2.values()), this.method(), this.dummy(), this.idGenerator())
    }
    return g
  }

  cycleRemoval () {
    return accessor(this, privates, 'cycleRemoval', arguments)
  }

  layerAssignment () {
    return accessor(this, privates, 'layerAssignment', arguments)
  }

  method () {
    return accessor(this, privates, 'method', arguments)
  }

  dummy () {
    return accessor(this, privates, 'dummy', arguments)
  }

  idGenerator () {
    return accessor(this, privates, 'idGenerator', arguments)
  }
}

module.exports = EdgeConcentrationTransformer
<commit_msg>Fix parameter for idGenerator<commit_after>const Graph = require('../../graph')
const accessor = require('../../utils/accessor')
const cycleRemoval = require('../../layouter/sugiyama/cycle-removal')
const layerAssignment = require('../../layouter/sugiyama/layer-assignment')
const groupLayers = require('../../layouter/sugiyama/misc/group-layers')
const rectangular = require('./rectangular')

const edgeConcentration = (g, h1, h2, method, dummy, idGenerator) => {
  const subgraph = new Graph()
  for (const u of h1) {
    subgraph.addVertex(u, g.vertex(u))
  }
  for (const u of h2) {
    subgraph.addVertex(u, g.vertex(u))
  }
  for (const u of h1) {
    for (const v of h2) {
      if (g.edge(u, v)) {
        subgraph.addEdge(u, v, g.edge(u, v))
      }
    }
  }

  for (const concentration of method(subgraph, h1, h2)) {
    const w = idGenerator(g, concentration.source, concentration.target)
    g.addVertex(w, dummy(concentration.source, concentration.target))
    for (const u of concentration.source) {
      g.addEdge(u, w)
    }
    for (const v of concentration.target) {
      g.addEdge(w, v)
    }
    for (const u of g.inVertices(w)) {
      for (const v of g.outVertices(w)) {
        if (g.edge(u, v)) {
          g.removeEdge(u, v)
        }
      }
    }
  }
}

const privates = new WeakMap()

class EdgeConcentrationTransformer {
  constructor () {
    privates.set(this, {
      cycleRemoval: new cycleRemoval.CycleRemoval(),
      layerAssignment: new layerAssignment.QuadHeuristic(),
      method: rectangular,
      dummy: () => ({dummy: true}),
      idGenerator: () => Symbol()
    })
  }

  transform (g) {
    this.cycleRemoval().call(g)
    const layerMap = this.layerAssignment().call(g)
    const layers = groupLayers(g, layerMap)
    for (let i = 0; i < layers.length - 1; ++i) {
      const h1 = layers[i]
      const h2 = new Set()
      let edges = 0
      for (const u of h1) {
        for (const v of g.outVertices(u)) {
          h2.add(v)
          edges += 1
        }
      }
      edgeConcentration(g, h1, Array.from(h2.values()), this.method(), this.dummy(), this.idGenerator())
    }
    return g
  }

  cycleRemoval () {
    return accessor(this, privates, 'cycleRemoval', arguments)
  }

  layerAssignment () {
    return accessor(this, privates, 'layerAssignment', arguments)
  }

  method () {
    return accessor(this, privates, 'method', arguments)
  }

  dummy () {
    return accessor(this, privates, 'dummy', arguments)
  }

  idGenerator () {
    return accessor(this, privates, 'idGenerator', arguments)
  }
}

module.exports = EdgeConcentrationTransformer
<|endoftext|>


<commit_before>/* Global equal, responseText, statement, ok, deepEqual, QUnit, module, asyncTest, Util, start */
/*jslint devel: true, browser: true, sloppy: false, maxerr: 50, indent: 4, plusplus: true */
var stateEnv = {};

module('State', {
	setup: function () {
		"use strict";
		Util.init(stateEnv);
	}
});

/*PUT | GET | DELETE http://example.com/TCAPI/activities/<activity ID>/state/<actor>/<State ID>[?registration=<registration>]

Stores, fetches, or deletes the specified state document in the context of the specified activity, actor, and registration (if specified). Actor may be an individual or a team.

DELETE http://example.com/TCAPI/activities/<activity ID>/state/<actor>[/?registration=<registration>]

Deletes all state data for this context (activity + actor [+ registration if specified]).

GET http://example.com/TCAPI/activities/<activity ID>/state/<actor>[/<registration][?since=<timestamp>]
*/

function putGetStateTest(env, useRegistration) {
	"use strict";
	var url = '/activities/state?activityId=<activity ID>&actor=<actor>&stateId=' + env.id,
		reg = '',
		wrongReg = '',
		stateText = 'state test text : ' + env.id;

	if (useRegistration) {
		reg = '&registration=autoTestReg1';
		wrongReg = '&registration=autoTestRegWRONG';
	}

    var headers = {"Content-Type":"text/plain"};
	env.util.request('GET', url + reg, null, true, 404, 'Not Found', function () {
		env.util.requestWithHeaders('PUT', url + reg, headers, stateText, true, 204, 'No Content', function () {
			env.util.request('GET', url + wrongReg, null, true, useRegistration ? 404 : 200, useRegistration ? 'Not Found' : 'OK', function () {
				env.util.request('GET', url + reg, null, true, 200, 'OK', function (xhr) {
					equal(xhr.responseText, stateText);
					env.util.request('DELETE', url + reg, null, true, 204, 'No Content', function () {
						env.util.request('GET', url + reg, null, true, 404, 'Not Found', function () {
							start();
						});
					});
				});
			});
		});
	});
}

function clearStateTest(env, useRegistration) {
	"use strict";
	var reg = '',
		url = '/activities/state?activityId=<activity ID>&actor=<actor>',
		urlKey = url + '&stateId=' + env.id,
		stateText = 'state test text : ' + env.id;

	if (useRegistration) {
		reg = '&registration=autoTestReg1';
	}
	var ii = 1;

	env.util.request('GET', urlKey + reg + '&sequence=1&ii=' + ii++, null, true, 404, 'Not Found', function (xhr) {
		env.util.request('PUT', urlKey + reg + '&sequence=2&ii=' + ii++, stateText, true, 204, 'No Content', function (xhr) {
			env.util.request('GET', urlKey + '&sequence=3&ii=' + ii++, null, true, useRegistration ? 404 : 200, useRegistration ? 'Not Found' : 'OK', function (xhr) {
				env.util.request('GET', urlKey + reg + '&sequence=4&ii=' + ii++, null, true, 200, 'OK', function (xhr) {
					equal(xhr.responseText, stateText, "sequence=5&ii=" + ii++);
					env.util.request('DELETE', url + reg + '&sequence=6&ii=' + ii++, null, true, 204, 'No Content', function (xhr) {
						env.util.request('GET', urlKey + reg + '&sequence=7&ii=' + ii++, null, true, 404, 'Not Found', function (xhr) {
							start();
						});
					});
				});
			});
		});
	});
}

asyncTest('PUT/GET/DELETE', function () { "use strict"; putGetStateTest(stateEnv, false); });
asyncTest('PUT/GET/DELETE (with registration)', function () { "use strict"; putGetStateTest(stateEnv, true); });
asyncTest('clear state', function () { "use strict"; clearStateTest(stateEnv, false); });
asyncTest('clear state (registration)', function () { "use strict"; clearStateTest(stateEnv, true); });
asyncTest('GET multiple state keys', function () {
	"use strict";
	stateEnv.util.getMultipleTest(stateEnv, '/activities/state?activityId=<activity ID>&actor=<actor>','stateId');
});

asyncTest('GET multiple state keys (with registration)', function () {
	"use strict";
	stateEnv.util.getMultipleTest(stateEnv, '/activities/state?activityId=<activity ID>&actor=<actor>&registration=autoTestReg1','stateId' );
});

asyncTest('Concurrency Rules', function(){
    "use strict";
    var env = stateEnv;
    var url = "/activities/state?activityId=<activity ID>&actor=<actor>&stateId=" + env.util.ruuid();
    env.util.concurrencyRulesTest(env, url, false);
});
<commit_msg>added "missing State id" test<commit_after>/* Global equal, responseText, statement, ok, deepEqual, QUnit, module, asyncTest, Util, start */
/*jslint devel: true, browser: true, sloppy: false, maxerr: 50, indent: 4, plusplus: true */
var stateEnv = {};

module('State', {
	setup: function () {
		"use strict";
		Util.init(stateEnv);
	}
});

/*PUT | GET | DELETE http://example.com/TCAPI/activities/<activity ID>/state/<actor>/<State ID>[?registration=<registration>]

Stores, fetches, or deletes the specified state document in the context of the specified activity, actor, and registration (if specified). Actor may be an individual or a team.

DELETE http://example.com/TCAPI/activities/<activity ID>/state/<actor>[/?registration=<registration>]

Deletes all state data for this context (activity + actor [+ registration if specified]).

GET http://example.com/TCAPI/activities/<activity ID>/state/<actor>[/<registration][?since=<timestamp>]
*/

function putGetStateTest(env, useRegistration) {
	"use strict";
	var url = '/activities/state?activityId=<activity ID>&actor=<actor>&stateId=' + env.id,
		reg = '',
		wrongReg = '',
		stateText = 'state test text : ' + env.id;

	if (useRegistration) {
		reg = '&registration=autoTestReg1';
		wrongReg = '&registration=autoTestRegWRONG';
	}

    var headers = {"Content-Type":"text/plain"};
	env.util.request('GET', url + reg, null, true, 404, 'Not Found', function () {
		env.util.requestWithHeaders('PUT', url + reg, headers, stateText, true, 204, 'No Content', function () {
			env.util.request('GET', url + wrongReg, null, true, useRegistration ? 404 : 200, useRegistration ? 'Not Found' : 'OK', function () {
				env.util.request('GET', url + reg, null, true, 200, 'OK', function (xhr) {
					equal(xhr.responseText, stateText);
					env.util.request('DELETE', url + reg, null, true, 204, 'No Content', function () {
						env.util.request('GET', url + reg, null, true, 404, 'Not Found', function () {
							start();
						});
					});
				});
			});
		});
	});
}

function clearStateTest(env, useRegistration) {
	"use strict";
	var reg = '',
		url = '/activities/state?activityId=<activity ID>&actor=<actor>',
		urlKey = url + '&stateId=' + env.id,
		stateText = 'state test text : ' + env.id;

	if (useRegistration) {
		reg = '&registration=autoTestReg1';
	}
	var ii = 1;

	env.util.request('GET', urlKey + reg + '&sequence=1&ii=' + ii++, null, true, 404, 'Not Found', function (xhr) {
		env.util.request('PUT', urlKey + reg + '&sequence=2&ii=' + ii++, stateText, true, 204, 'No Content', function (xhr) {
			env.util.request('GET', urlKey + '&sequence=3&ii=' + ii++, null, true, useRegistration ? 404 : 200, useRegistration ? 'Not Found' : 'OK', function (xhr) {
				env.util.request('GET', urlKey + reg + '&sequence=4&ii=' + ii++, null, true, 200, 'OK', function (xhr) {
					equal(xhr.responseText, stateText, "sequence=5&ii=" + ii++);
					env.util.request('DELETE', url + reg + '&sequence=6&ii=' + ii++, null, true, 204, 'No Content', function (xhr) {
						env.util.request('GET', urlKey + reg + '&sequence=7&ii=' + ii++, null, true, 404, 'Not Found', function (xhr) {
							start();
						});
					});
				});
			});
		});
	});
}

asyncTest('PUT/GET/DELETE', function () { "use strict"; putGetStateTest(stateEnv, false); });
asyncTest('PUT/GET/DELETE (with registration)', function () { "use strict"; putGetStateTest(stateEnv, true); });
asyncTest('clear state', function () { "use strict"; clearStateTest(stateEnv, false); });
asyncTest('clear state (registration)', function () { "use strict"; clearStateTest(stateEnv, true); });
asyncTest('GET multiple state keys', function () {
	"use strict";
	stateEnv.util.getMultipleTest(stateEnv, '/activities/state?activityId=<activity ID>&actor=<actor>','stateId');
});

asyncTest('GET multiple state keys (with registration)', function () {
	"use strict";
	stateEnv.util.getMultipleTest(stateEnv, '/activities/state?activityId=<activity ID>&actor=<actor>&registration=autoTestReg1','stateId' );
});

asyncTest('Concurrency Rules', function(){
    "use strict";
    var env = stateEnv;
    var url = "/activities/state?activityId=<activity ID>&actor=<actor>&stateId=" + env.util.ruuid();
    env.util.concurrencyRulesTest(env, url, false);
});

asyncTest('missing State id', function() {
	"use strict";

    var env = stateEnv;
	var reg = '',
		url = '/activities/state?activityId=<activity ID>&actor=<actor>',
		urlKey = url + '&stateBadid=' + env.id,
		stateText = 'state test text : ' + env.id;

	env.util.request('PUT', urlKey, stateText, true, 400, 'Bad Request', function (xhr) {
		start();
	});
});
<|endoftext|>


<commit_before><commit_msg>feat: make empty string value undefined to fail required validation if necessary<commit_after><|endoftext|>


<commit_before>(function(env) {
    "use strict";

    env.ddg_spice_in_theaters = function(api_result) {

        if (!api_result || api_result.error) {
            return Spice.failed('in_theaters');
        }

        Spice.add({
            id: 'in_theaters',
            name: 'Now Showing',
            data: api_result.movies,
	    signal: 'high',
            meta: {
                sourceName: 'Rotten Tomatoes',
                sourceUrl: 'http://www.rottentomatoes.com/movie/in-theaters/',
                total: api_result.movies,
                itemType: 'Movies'
            },
            normalize: function(item) {
		var position;
		if(item.ratings.critics_rating === "Fresh" || item.ratings.critics_rating === "Certified Fresh") {
		    position = "-256px -144px";
		} else if(item.ratings.critics_rating === "Rotten") {
		    position = "-272px -144px";
		}
                return {
                    rating: item.ratings.critics_score >= 0 ? item.ratings.critics_score / 20 : 0,
                    image: item.posters.detailed,
		    icon_url: DDG.get_asset_path('in_theaters','icons-v2.png'),
		    icon_image: position,
		    icon_class: position ? 'tomato--icon' : "",
		    abstract: Handlebars.helpers.ellipsis(item.synopsis, 200),
		    heading: item.title,
		    img_m: item.posters.detailed,
		    url: item.links.alternate
                };
            },
            templates: {
		group: 'products_simple',
                options: {
                    variant: 'poster',
		    subtitle_content: Spice.in_theaters.subtitle_content,
		    rating: false,
		    buy: Spice.in_theaters.buy
                }
            }
        });

        Spice.getDOM('in_theaters').find('.tile__body').addClass('is-hidden');
    }

    // Convert minutes to hr. min. format.
    // e.g. {{time 90}} will return 1 hr. 30 min.
    Handlebars.registerHelper("time", function(runtime) {
        var hours = '',
            minutes = runtime;

        if(runtime >= 60) {
            hours = Math.floor(runtime / 60) + ' hr. ';
            minutes = (runtime % 60);
        }

        return hours + (minutes > 0 ? minutes + ' min.' : '');
    });
}(this));
<commit_msg>in_theaters name<commit_after>(function(env) {
    "use strict";

    env.ddg_spice_in_theaters = function(api_result) {

        if (!api_result || api_result.error) {
            return Spice.failed('in_theaters');
        }

        Spice.add({
            id: 'in_theaters',
            name: 'Movies',
            data: api_result.movies,
	    signal: 'high',
            meta: {
                sourceName: 'Rotten Tomatoes',
                sourceUrl: 'http://www.rottentomatoes.com/movie/in-theaters/',
                total: api_result.movies,
                itemType: 'Movies'
            },
            normalize: function(item) {
		var position;
		if(item.ratings.critics_rating === "Fresh" || item.ratings.critics_rating === "Certified Fresh") {
		    position = "-256px -144px";
		} else if(item.ratings.critics_rating === "Rotten") {
		    position = "-272px -144px";
		}
                return {
                    rating: item.ratings.critics_score >= 0 ? item.ratings.critics_score / 20 : 0,
                    image: item.posters.detailed,
		    icon_url: DDG.get_asset_path('in_theaters','icons-v2.png'),
		    icon_image: position,
		    icon_class: position ? 'tomato--icon' : "",
		    abstract: Handlebars.helpers.ellipsis(item.synopsis, 200),
		    heading: item.title,
		    img_m: item.posters.detailed,
		    url: item.links.alternate
                };
            },
            templates: {
		group: 'products_simple',
                options: {
                    variant: 'poster',
		    subtitle_content: Spice.in_theaters.subtitle_content,
		    rating: false,
		    buy: Spice.in_theaters.buy
                }
            }
        });

        Spice.getDOM('in_theaters').find('.tile__body').addClass('is-hidden');
    }

    // Convert minutes to hr. min. format.
    // e.g. {{time 90}} will return 1 hr. 30 min.
    Handlebars.registerHelper("time", function(runtime) {
        var hours = '',
            minutes = runtime;

        if(runtime >= 60) {
            hours = Math.floor(runtime / 60) + ' hr. ';
            minutes = (runtime % 60);
        }

        return hours + (minutes > 0 ? minutes + ' min.' : '');
    });
}(this));
<|endoftext|>


<commit_before>import { SessionCache } from './sessioncache';
import { Session } from './session';

/**
 * ServerClient is responsible for keeping up-to-date with the current
 * session and handles many of the client-to-server interactions,
 * like passing the controller.
 */
class ServerClient {
  /**
   * Initalizes a ServerClient object.
   * @param {URLSearchParams} urlParams Represents the URLSearchParams
   *    of the session the client is in, holds information such as the
   *    session ID and the screen name of the current user.
   */
  constructor(urlParams) {
    /**
     * function sessionRequest_() is the fetch api request
     * responsible for contacting the server to retrieve the Session
     * object.
     * @return {function(): Promise<any>}
     * @private
     */
    async function sessionRequest_() {
      const /** string */ name = encodeURI(urlParams.get('name'));
      const /** string */ sessionID =
          encodeURI(urlParams.get('session-id'));
      const /** Response */ response = await fetch(
          `/get-session-info?name=${name}&session-id=${sessionID}`);
      return await response.json();
    }

    /**
     * The SessionCache for the current session, contacts the server for
     * the Session object.
     * @private {SessionCache}
     */
    this.sessionCache_ = new SessionCache(sessionRequest_);

    /**
     * @private {URLSearchParams}
     */
    this.urlParams_ = urlParams;
  }

  /**
   * This method starts to cache.
   * @private
   */
  startSessionCache_() {
    throw new Error('Unimplemented');
  }

  /**
   * This method changes the controller of the current session to the
   * Attendee pased in.
   * @param {string} name
   */
  passController(name) {
    throw new Error('Unimplemented');
  }

  /**
   * Returns a promise containing the Session object, given how updated the
   * cache is in refreshing.
   * @return {Promise} The Promise object
   */
  getSession() {
    throw new Error('Unimplemented');
  }
}

export { ServerClient };
<commit_msg>Removes Session import<commit_after>import { SessionCache } from './sessioncache';

/**
 * ServerClient is responsible for keeping up-to-date with the current
 * session and handles many of the client-to-server interactions,
 * like passing the controller.
 */
class ServerClient {
  /**
   * Initalizes a ServerClient object.
   * @param {URLSearchParams} urlParams Represents the URLSearchParams
   *    of the session the client is in, holds information such as the
   *    session ID and the screen name of the current user.
   */
  constructor(urlParams) {
    /**
     * function sessionRequest_() is the fetch api request
     * responsible for contacting the server to retrieve the Session
     * object.
     * @return {function(): Promise<any>}
     * @private
     */
    async function sessionRequest_() {
      const /** string */ name = encodeURI(urlParams.get('name'));
      const /** string */ sessionID =
          encodeURI(urlParams.get('session-id'));
      const /** Response */ response = await fetch(
          `/get-session-info?name=${name}&session-id=${sessionID}`);
      return await response.json();
    }

    /**
     * The SessionCache for the current session, contacts the server for
     * the Session object.
     * @private {SessionCache}
     */
    this.sessionCache_ = new SessionCache(sessionRequest_);

    /**
     * @private {URLSearchParams}
     */
    this.urlParams_ = urlParams;
  }

  /**
   * This method starts to cache.
   * @private
   */
  startSessionCache_() {
    throw new Error('Unimplemented');
  }

  /**
   * This method changes the controller of the current session to the
   * Attendee pased in.
   * @param {string} name
   */
  passController(name) {
    throw new Error('Unimplemented');
  }

  /**
   * Returns a promise containing the Session object, given how updated the
   * cache is in refreshing.
   * @return {Promise} The Promise object
   */
  getSession() {
    throw new Error('Unimplemented');
  }
}

export { ServerClient };
<|endoftext|>


<commit_before>const cp = require('child_process');
const fs = require('fs');
const path = require('path');
const tl = require('azure-pipelines-task-lib/task');
const util = require('./util');

const { Octokit } = require("@octokit/rest");

const OWNER = 'microsoft';
const REPO  = 'azure-pipelines-agent';
const GIT = 'git';
const VALID_RELEASE_RE = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
const octokit = new Octokit({}); // only read-only operations, no need to auth

process.env.EDITOR = process.env.EDITOR === undefined ? 'code --wait' : process.env.EDITOR;

var opt = require('node-getopt').create([
    ['',  'dryrun',               'Dry run only, do not actually commit new release'],
    ['',  'derivedFrom=version',  'Used to get PRs merged since this release was created', 'latest'],
    ['h', 'help',                 'Display this help'],
  ])
  .setHelp(
    'Usage: node createReleaseBranch.js [OPTION] <version>\n' +
    '\n' +
    '[[OPTIONS]]\n'
  )
  .bindHelp()     // bind option 'help' to default action
  .parseSystem(); // parse command line

async function verifyNewReleaseTagOk(newRelease)
{
    if (!newRelease || !newRelease.match(VALID_RELEASE_RE) || newRelease.endsWith('.999.999'))
    {
        console.log(`Invalid version '${newRelease}'. Version must be in the form of <major>.<minor>.<patch> where each level is 0-999`);
        process.exit(-1);
    }
    try
    {
        var tag = 'v' + newRelease;
        await octokit.repos.getReleaseByTag({
            owner: OWNER,
            repo: REPO,
            tag: tag
        });

        console.log(`Version ${newRelease} is already in use`);
        process.exit(-1);
    }
    catch
    {
        console.log(`Version ${newRelease} is available for use`);
    }
}

function writeAgentVersionFile(newRelease)
{
    console.log('Writing agent version file')
    if (!opt.options.dryrun)
    {
        fs.writeFileSync(path.join(__dirname, '..', 'src', 'agentversion'), `${newRelease}\n`);
    }
    return newRelease;
}

async function fetchPRsSinceLastReleaseAndEditReleaseNotes(newRelease, callback)
{
    var derivedFrom = opt.options.derivedFrom;
    console.log("Derived from %o", derivedFrom);

    try
    {
        var releaseInfo;

        if (derivedFrom !== 'latest')
        {
            var tag = 'v' + derivedFrom;

            console.log(`Getting release by tag ${tag}`);

            releaseInfo = await octokit.repos.getReleaseByTag({
                owner: OWNER,
                repo: REPO,
                tag: tag
            });
        }
        else
        {
            console.log("Getting latest release");

            releaseInfo = await octokit.repos.getLatestRelease({
                owner: OWNER,
                repo: REPO
            });
        }

        var branch = opt.options.branch;
        var lastReleaseDate = releaseInfo.data.published_at;
        console.log(`Fetching PRs merged since ${lastReleaseDate} on ${branch}`);
        try
        {
            var results = await octokit.search.issuesAndPullRequests({
                q:`type:pr+is:merged+repo:${OWNER}/${REPO}+base:${branch}+merged:>=${lastReleaseDate}`,
                order: 'asc',
                sort: 'created'
            })
            editReleaseNotesFile(results.data);
        }
        catch (e)
        {
            console.log(`Error: Problem fetching PRs: ${e}`);
            process.exit(-1);
        }
    }
    catch (e)
    {
        console.log(e);
        console.log(`Error: Cannot find release ${opt.options.derivedFrom}. Aborting.`);
        process.exit(-1);
    }
}

function editReleaseNotesFile(body)
{
    var releaseNotesFile = path.join(__dirname, '..', 'releaseNote.md');
    var existingReleaseNotes = fs.readFileSync(releaseNotesFile);
    var newPRs = { 'Features': [], 'Bugs': [], 'Misc': [] };
    body.items.forEach(function (item) {
        var category = 'Misc';
        item.labels.forEach(function (label) {
            if (category)
            {
                if (label.name === 'bug')
                {
                    category = 'Bugs';
                }
                if (label.name === 'enhancement')
                {
                    category = 'Features';
                }
                if (label.name === 'internal')
                {
                    category = null;
                }
            }
        });
        if (category)
        {
            newPRs[category].push(` - ${item.title} (#${item.number})`);
        }
    });
    var newReleaseNotes = '';
    var categories = ['Features', 'Bugs', 'Misc'];
    categories.forEach(function (category) {
        newReleaseNotes += `## ${category}\n${newPRs[category].join('\n')}\n\n`;
    });

    newReleaseNotes += existingReleaseNotes;
    var editorCmd = `${process.env.EDITOR} ${releaseNotesFile}`;
    console.log(editorCmd);
    if (opt.options.dryrun)
    {
        console.log('Found the following PRs = %o', newPRs);
        console.log('\n\n');
        console.log(newReleaseNotes);
        console.log('\n');
    }
    else
    {
        fs.writeFileSync(releaseNotesFile, newReleaseNotes);
        try
        {
            cp.execSync(`${process.env.EDITOR} ${releaseNotesFile}`, {
                stdio: [process.stdin, process.stdout, process.stderr]
            });
        }
        catch (err)
        {
            console.log(err.message);
            process.exit(-1);
        }
    }
}

function commitAndPush(directory, release, branch)
{
    util.execInForeground(GIT + " checkout -b " + branch, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} commit -m "Agent Release ${release}" `, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} -c credential.helper='!f() { echo "username=pat"; echo "password=$PAT"; };f' push --set-upstream origin ${branch}`, directory, opt.options.dryrun);
}

function commitAgentChanges(directory, release)
{
    var newBranch = `releases/${release}`;
    util.execInForeground(`${GIT} add ${path.join('src', 'agentversion')}`, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} add releaseNote.md`, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} config --global user.email "azure-pipelines-bot@microsoft.com"`, null, opt.options.dryrun);
    util.execInForeground(`${GIT} config --global user.name "azure-pipelines-bot"`, null, opt.options.dryrun);
    commitAndPush(directory, release, newBranch);
}

function checkGitStatus()
{
    var git_status = cp.execSync(`${GIT} status --untracked-files=no --porcelain`, { encoding: 'utf-8'});
    if (git_status)
    {
        console.log('You have uncommited changes in this clone. Aborting.');
        console.log(git_status);
        if (!opt.options.dryrun)
        {
            process.exit(-1);
        }
    }
    else
    {
        console.log('Git repo is clean.');
    }
    return git_status;
}

async function main()
{
    try {
        var newRelease = opt.argv[0];
        if (newRelease === undefined)
        {
            console.log('Error: You must supply a version');
            process.exit(-1);
        }
        util.verifyMinimumNodeVersion();
        util.verifyMinimumGitVersion();
        await verifyNewReleaseTagOk(newRelease);
        checkGitStatus();
        writeAgentVersionFile(newRelease);
        await fetchPRsSinceLastReleaseAndEditReleaseNotes(newRelease);
        commitAgentChanges(path.join(__dirname, '..'), newRelease);
        console.log('done.');
    }
    catch (err) {
        tl.setResult(tl.TaskResult.Failed, err.message || 'run() failed', true);
        throw err;
    }
}

main();
<commit_msg>branch in createReleaseBranch.js was undefined (#2949)<commit_after>const cp = require('child_process');
const fs = require('fs');
const path = require('path');
const tl = require('azure-pipelines-task-lib/task');
const util = require('./util');

const { Octokit } = require("@octokit/rest");

const OWNER = 'microsoft';
const REPO  = 'azure-pipelines-agent';
const GIT = 'git';
const VALID_RELEASE_RE = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
const octokit = new Octokit({}); // only read-only operations, no need to auth

process.env.EDITOR = process.env.EDITOR === undefined ? 'code --wait' : process.env.EDITOR;

var opt = require('node-getopt').create([
    ['',  'dryrun',               'Dry run only, do not actually commit new release'],
    ['',  'derivedFrom=version',  'Used to get PRs merged since this release was created', 'latest'],
    ['',  'branch=branch',        'Branch to select PRs merged into', 'master'],
    ['h', 'help',                 'Display this help'],
  ])
  .setHelp(
    'Usage: node createReleaseBranch.js [OPTION] <version>\n' +
    '\n' +
    '[[OPTIONS]]\n'
  )
  .bindHelp()     // bind option 'help' to default action
  .parseSystem(); // parse command line

async function verifyNewReleaseTagOk(newRelease)
{
    if (!newRelease || !newRelease.match(VALID_RELEASE_RE) || newRelease.endsWith('.999.999'))
    {
        console.log(`Invalid version '${newRelease}'. Version must be in the form of <major>.<minor>.<patch> where each level is 0-999`);
        process.exit(-1);
    }
    try
    {
        var tag = 'v' + newRelease;
        await octokit.repos.getReleaseByTag({
            owner: OWNER,
            repo: REPO,
            tag: tag
        });

        console.log(`Version ${newRelease} is already in use`);
        process.exit(-1);
    }
    catch
    {
        console.log(`Version ${newRelease} is available for use`);
    }
}

function writeAgentVersionFile(newRelease)
{
    console.log('Writing agent version file')
    if (!opt.options.dryrun)
    {
        fs.writeFileSync(path.join(__dirname, '..', 'src', 'agentversion'), `${newRelease}\n`);
    }
    return newRelease;
}

async function fetchPRsSinceLastReleaseAndEditReleaseNotes(newRelease, callback)
{
    var derivedFrom = opt.options.derivedFrom;
    console.log("Derived from %o", derivedFrom);

    try
    {
        var releaseInfo;

        if (derivedFrom !== 'latest')
        {
            var tag = 'v' + derivedFrom;

            console.log(`Getting release by tag ${tag}`);

            releaseInfo = await octokit.repos.getReleaseByTag({
                owner: OWNER,
                repo: REPO,
                tag: tag
            });
        }
        else
        {
            console.log("Getting latest release");

            releaseInfo = await octokit.repos.getLatestRelease({
                owner: OWNER,
                repo: REPO
            });
        }

        var branch = opt.options.branch;
        var lastReleaseDate = releaseInfo.data.published_at;
        console.log(`Fetching PRs merged since ${lastReleaseDate} on ${branch}`);
        try
        {
            var results = await octokit.search.issuesAndPullRequests({
                q:`type:pr+is:merged+repo:${OWNER}/${REPO}+base:${branch}+merged:>=${lastReleaseDate}`,
                order: 'asc',
                sort: 'created'
            })
            editReleaseNotesFile(results.data);
        }
        catch (e)
        {
            console.log(`Error: Problem fetching PRs: ${e}`);
            process.exit(-1);
        }
    }
    catch (e)
    {
        console.log(e);
        console.log(`Error: Cannot find release ${opt.options.derivedFrom}. Aborting.`);
        process.exit(-1);
    }
}

function editReleaseNotesFile(body)
{
    var releaseNotesFile = path.join(__dirname, '..', 'releaseNote.md');
    var existingReleaseNotes = fs.readFileSync(releaseNotesFile);
    var newPRs = { 'Features': [], 'Bugs': [], 'Misc': [] };
    body.items.forEach(function (item) {
        var category = 'Misc';
        item.labels.forEach(function (label) {
            if (category)
            {
                if (label.name === 'bug')
                {
                    category = 'Bugs';
                }
                if (label.name === 'enhancement')
                {
                    category = 'Features';
                }
                if (label.name === 'internal')
                {
                    category = null;
                }
            }
        });
        if (category)
        {
            newPRs[category].push(` - ${item.title} (#${item.number})`);
        }
    });
    var newReleaseNotes = '';
    var categories = ['Features', 'Bugs', 'Misc'];
    categories.forEach(function (category) {
        newReleaseNotes += `## ${category}\n${newPRs[category].join('\n')}\n\n`;
    });

    newReleaseNotes += existingReleaseNotes;
    var editorCmd = `${process.env.EDITOR} ${releaseNotesFile}`;
    console.log(editorCmd);
    if (opt.options.dryrun)
    {
        console.log('Found the following PRs = %o', newPRs);
        console.log('\n\n');
        console.log(newReleaseNotes);
        console.log('\n');
    }
    else
    {
        fs.writeFileSync(releaseNotesFile, newReleaseNotes);
        try
        {
            cp.execSync(`${process.env.EDITOR} ${releaseNotesFile}`, {
                stdio: [process.stdin, process.stdout, process.stderr]
            });
        }
        catch (err)
        {
            console.log(err.message);
            process.exit(-1);
        }
    }
}

function commitAndPush(directory, release, branch)
{
    util.execInForeground(GIT + " checkout -b " + branch, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} commit -m "Agent Release ${release}" `, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} -c credential.helper='!f() { echo "username=pat"; echo "password=$PAT"; };f' push --set-upstream origin ${branch}`, directory, opt.options.dryrun);
}

function commitAgentChanges(directory, release)
{
    var newBranch = `releases/${release}`;
    util.execInForeground(`${GIT} add ${path.join('src', 'agentversion')}`, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} add releaseNote.md`, directory, opt.options.dryrun);
    util.execInForeground(`${GIT} config --global user.email "azure-pipelines-bot@microsoft.com"`, null, opt.options.dryrun);
    util.execInForeground(`${GIT} config --global user.name "azure-pipelines-bot"`, null, opt.options.dryrun);
    commitAndPush(directory, release, newBranch);
}

function checkGitStatus()
{
    var git_status = cp.execSync(`${GIT} status --untracked-files=no --porcelain`, { encoding: 'utf-8'});
    if (git_status)
    {
        console.log('You have uncommited changes in this clone. Aborting.');
        console.log(git_status);
        if (!opt.options.dryrun)
        {
            process.exit(-1);
        }
    }
    else
    {
        console.log('Git repo is clean.');
    }
    return git_status;
}

async function main()
{
    try {
        var newRelease = opt.argv[0];
        if (newRelease === undefined)
        {
            console.log('Error: You must supply a version');
            process.exit(-1);
        }
        util.verifyMinimumNodeVersion();
        util.verifyMinimumGitVersion();
        await verifyNewReleaseTagOk(newRelease);
        checkGitStatus();
        writeAgentVersionFile(newRelease);
        await fetchPRsSinceLastReleaseAndEditReleaseNotes(newRelease);
        commitAgentChanges(path.join(__dirname, '..'), newRelease);
        console.log('done.');
    }
    catch (err) {
        tl.setResult(tl.TaskResult.Failed, err.message || 'run() failed', true);
        throw err;
    }
}

main();
<|endoftext|>


<commit_before><commit_msg>Add argument count checking to typechecking injections<commit_after><|endoftext|>


<commit_before>var ddg_spice_sound_cloud = function(api_result) {
    "use strict";

    // Check how many tracks are actually streamable.
    var streamable = 0;
    for(var i = 0; i < api_result.length; i += 1) {
        if(api_result[i].streamable) {
            streamable += 1;
        }
    }

    if(api_result.length === 0 || streamable === 0) {
        return;
    }

    var image_proxy = "/iu/?u=";
    var query = "";

    // Get the original query.
    // We're going to pass this to the More at SoundCloud link.
    var matched, result;
    $("script").each(function() {
        matched = $(this).attr("src");
        if(matched) {
            result = matched.match(/\/js\/spice\/sound_cloud\/(.+)/);
            if(result) {
                query = result[1];
            }
        }
    });

    // Display the plugin.
    var image = Handlebars.helpers.chooseImage(api_result[0].artwork_url, api_result[0].user.avatar_url);
    Spice.render({
        data             : api_result,
        header1          : "Sound Cloud",
        source_url       : "https://soundcloud.com/search?q=" + query,
        source_name      : "SoundCloud",
        image_url        : image_proxy + image,
        template_normal  : "sound_cloud",
        force_big_header : true
    });

    // Force the image to be smaller.
    $("#zero_click_image img").attr("style", "width: 120px !important; height: 120px !important;");

    // Get the size of the screen.
    // If the screen is small, don't display the image.
    var zero_click_image = $("#zero_click_image");
    var checkWidth = function(width) {
        if(width < 750) {
            zero_click_image.addClass("hide");
            $(".zero_click_snippet").attr("style", "margin-left: 0px !important; display: block;");
        } else {
            zero_click_image.removeClass("hide");
            $(".zero_click_snippet").attr("style", "margin-left: 0px !important; display: block; width: 74%;");
        }
    };

    // Monitor the size of the window.
    checkWidth($(window).width());
    $(window).resize(function() {
        checkWidth($(window).width());
    });

    // Initialize SoundManager2.
    window.SM2_DEFER = true;
    var soundSetup = function() {
        window.soundManager = new SoundManager();
        soundManager.url = "/soundmanager2/swf/";
        soundManager.flashVersion = 9;
        soundManager.useFlashBlock = false;
        soundManager.useHTML5Audio = false;
        soundManager.beginDelayedInit();
        soundManager.onready(function() {
            // Prevent the user from clicking the link.
            // This copies the attribute "data-stream" to "href."
            $(".soundcloud-audio").each(function() {
                var stream = $(this).attr("data-stream");
                $(this).attr("href", stream);
            });
            var pagePlayer = new PagePlayer();
            pagePlayer.init();
        });
    };

    var ready = [false, false];
    var checkReady = function(toggle) {
        ready[toggle] = true;
        if(ready[0] && ready[1]) {
            soundSetup();
        }
    };

    // Load page-player.js. This JS file converts a list of MP3s into a playlist.
    $.getScript("/soundmanager2/script/page-player-soundcloud.js", function() {
        checkReady(0);
    });

    // Load SoundManager2. This JS file handles our audio.
    $.getScript("/soundmanager2/script/soundmanager2-nodebug-jsmin.js", function() {
        checkReady(1);
    });
};

// Get the larger version of the image.
Handlebars.registerHelper("chooseImage", function(first, second) {
    "use strict";

    var image = first || second;
    return image.replace(/large\.jpg/, "t200x200.jpg");
});

// Let's not make the title too long.
Handlebars.registerHelper("limit", function(title, username) {
    "use strict";

    if(title.length + username.length > 60) {
        return title.substring(0, 60 - username.length) + "...";
    } else {
        return title;
    }
});

// Check if the sound is streamable.
Handlebars.registerHelper("checkStreamable", function(items, options) {
    "use strict";

    var out = "";
    for(var i = 0; i < items.length; i += 1) {
        if(items[i].streamable) {
            out += options.fn(items[i]);
        }
    }
    return out;
});

Handlebars.registerHelper("toHttps", function(audio) {
    "use strict";

    return audio.replace(/^http:/, "https:");
});<commit_msg>Added a description at the top of the sound_cloud.js file.<commit_after>// Description:
// Returns a list of streamable MP3s.
//
// Dependencies:
// Requires SoundManager2, jQuery, and SoundManager2 page-player (for the player).
//
// Commands:
// soundcloud falloutboy

var ddg_spice_sound_cloud = function(api_result) {
    "use strict";

    // Check how many tracks are actually streamable.
    var streamable = 0;
    for(var i = 0; i < api_result.length; i += 1) {
        if(api_result[i].streamable) {
            streamable += 1;
        }
    }

    if(api_result.length === 0 || streamable === 0) {
        return;
    }

    var image_proxy = "/iu/?u=";
    var query = "";

    // Get the original query.
    // We're going to pass this to the More at SoundCloud link.
    var matched, result;
    $("script").each(function() {
        matched = $(this).attr("src");
        if(matched) {
            result = matched.match(/\/js\/spice\/sound_cloud\/(.+)/);
            if(result) {
                query = result[1];
            }
        }
    });

    // Display the plugin.
    var image = Handlebars.helpers.chooseImage(api_result[0].artwork_url, api_result[0].user.avatar_url);
    Spice.render({
        data             : api_result,
        header1          : "Sound Cloud",
        source_url       : "https://soundcloud.com/search?q=" + query,
        source_name      : "SoundCloud",
        image_url        : image_proxy + image,
        template_normal  : "sound_cloud",
        force_big_header : true
    });

    // Force the image to be smaller.
    $("#zero_click_image img").attr("style", "width: 120px !important; height: 120px !important;");

    // Get the size of the screen.
    // If the screen is small, don't display the image.
    var zero_click_image = $("#zero_click_image");
    var checkWidth = function(width) {
        if(width < 750) {
            zero_click_image.addClass("hide");
            $(".zero_click_snippet").attr("style", "margin-left: 0px !important; display: block;");
        } else {
            zero_click_image.removeClass("hide");
            $(".zero_click_snippet").attr("style", "margin-left: 0px !important; display: block; width: 74%;");
        }
    };

    // Monitor the size of the window.
    checkWidth($(window).width());
    $(window).resize(function() {
        checkWidth($(window).width());
    });

    // Initialize SoundManager2.
    window.SM2_DEFER = true;
    var soundSetup = function() {
        window.soundManager = new SoundManager();
        soundManager.url = "/soundmanager2/swf/";
        soundManager.flashVersion = 9;
        soundManager.useFlashBlock = false;
        soundManager.useHTML5Audio = false;
        soundManager.beginDelayedInit();
        soundManager.onready(function() {
            // Prevent the user from clicking the link.
            // This copies the attribute "data-stream" to "href."
            $(".soundcloud-audio").each(function() {
                var stream = $(this).attr("data-stream");
                $(this).attr("href", stream);
            });
            var pagePlayer = new PagePlayer();
            pagePlayer.init();
        });
    };

    var ready = [false, false];
    var checkReady = function(toggle) {
        ready[toggle] = true;
        if(ready[0] && ready[1]) {
            soundSetup();
        }
    };

    // Load page-player.js. This JS file converts a list of MP3s into a playlist.
    $.getScript("/soundmanager2/script/page-player-soundcloud.js", function() {
        checkReady(0);
    });

    // Load SoundManager2. This JS file handles our audio.
    $.getScript("/soundmanager2/script/soundmanager2-nodebug-jsmin.js", function() {
        checkReady(1);
    });
};

// Get the larger version of the image.
Handlebars.registerHelper("chooseImage", function(first, second) {
    "use strict";

    var image = first || second;
    return image.replace(/large\.jpg/, "t200x200.jpg");
});

// Let's not make the title too long.
Handlebars.registerHelper("limit", function(title, username) {
    "use strict";

    if(title.length + username.length > 60) {
        return title.substring(0, 60 - username.length) + "...";
    } else {
        return title;
    }
});

// Check if the sound is streamable.
Handlebars.registerHelper("checkStreamable", function(items, options) {
    "use strict";

    var out = "";
    for(var i = 0; i < items.length; i += 1) {
        if(items[i].streamable) {
            out += options.fn(items[i]);
        }
    }
    return out;
});

Handlebars.registerHelper("toHttps", function(audio) {
    "use strict";

    return audio.replace(/^http:/, "https:");
});<|endoftext|>


<commit_before>

/* Gestion des talks favoris sur la page de Talk. */
function initFavoris() {

    $('#talk').click(
        function () {
            var id = parseInt($(this).attr('id_talk'));
            var key = 'talk' + id;

            if (localStorage[key] == "true") {
                localStorage[key] = 'false';
            } else {
                localStorage[key] = 'true';
            }
            initTalkOnTalkPage(id);

    });
}

function initTalkOnTalkPage(id_talk) {
    var key = 'talk' + id_talk;
    if (localStorage[key] == "false") {
        $('#talk').html("Ce talk ne fait pas partie de vos favoris");
        $('#talk').removeClass('btn-success');
    } else {
        $('#talk').html("Ce talk fait partie de vos favoris");
        $('#talk').addClass('btn-success');
    }
}

<commit_msg>Correction dans le première affichage des favoris<commit_after>

/* Gestion des talks favoris sur la page de Talk. */
function initFavoris() {

    $('#talk').click(
        function () {
            var id = parseInt($(this).attr('id_talk'));
            var key = 'talk' + id;

            if (localStorage[key] == "true") {
                localStorage[key] = 'false';
            } else {
                localStorage[key] = 'true';
            }
            initTalkOnTalkPage(id);

    });
}

function initTalkOnTalkPage(id_talk) {
    var key = 'talk' + id_talk;
    if (localStorage[key] == "true") {
        $('#talk').html("Ce talk fait partie de vos favoris");
        $('#talk').addClass('btn-success');
    } else {
        $('#talk').html("Ce talk ne fait pas partie de vos favoris");
        $('#talk').removeClass('btn-success');
    }
}

<|endoftext|>


<commit_before><commit_msg>Avoid require(smartcard) crash if service is not started<commit_after><|endoftext|>


<commit_before>
// ----------------------------------------------------------------
// Static classes

class Log {
  // Common line setting
  static get LOG_LENGTH() { return 96; }
  static get LOG_CHARACTER() { return '-'; }

  // View permission
  static get LOG_VIEW() { return true; }
  static get LOG_VIEW_OBJECT() { return true; }
  static get LOG_VIEW_CLASS() { return true; }
  static get LOG_VIEW_CLASS_KEY() { return true; }
  static get LOG_VIEW_ERROR() { return true; }
  static get LOG_VIEW_CAUTION() { return true; }

  // Align definition
  static get ALIGN_LEFT() { return 0; }
  static get ALIGN_CENTER() { return 1; }
  static get ALIGN_RIGHT() { return 2; }

  // Arrow definition
  static get ARROW_OUTPUT() { return ' ---> '; }
  static get ARROW_INPUT() { return ' <--- '; }

  // Length definition
  static get CLASS_LENGTH() { return 24; }
  static get KEY_LENGTH() { return 24; }

  // Style definition
  static get STYLE_COLOR_RED() { return 'color:#f00;'; }
  static get STYLE_COLOR_GREEN() { return 'color:#0f0;'; }
  static get STYLE_COLOR_BLUE() { return 'color:#00f;'; }
  static get STYLE_COLOR_YELLOW() { return 'color:#ff0;'; }
  static get STYLE_COLOR_MAGENTA() { return 'color:#f0f;'; }
  static get STYLE_COLOR_CYAN() { return 'color:#0ff;'; }

  static get STYLE_CLASS() { return 'color:#222;'; }
  static get STYLE_KEY() { return 'color:#828;'; }
  static get STYLE_VALUE() { return 'color:#228;'; }

  static get STYLE_ERROR_LINE() { return 'color:#f00;'; }
  static get STYLE_ERROR_HEADER() { return 'color:#a00;'; }
  static get STYLE_ERROR_CONTENT() { return 'color:#111;'; }

  static get STYLE_CAUTION_LINE() { return 'color:#aa0;'; }
  static get STYLE_CAUTION_HEADER() { return 'color:#440;'; }
  static get STYLE_CAUTION_CONTENT() { return 'color:#111;'; }

  static logError(...array) {
    // View permission
    if (this.LOG_VIEW_ERROR) {
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
      // Write title
      this.log('ERROR', this.ALIGN_CENTER, this.STYLE_ERROR_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_ERROR_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
    }
  }

  static logCaution(...array) {
    // View permission
    if (this.LOG_VIEW_CAUTION) {
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
      // Write title
      this.log('CAUTION', this.ALIGN_CENTER, this.STYLE_CAUTION_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_CAUTION_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
    }
  }

  static logObj(_obj) {
    // View permission
    if (this.LOG_VIEW_OBJECT) {
      // Write object
      console.log(_obj);
    }
  }

  static logClass(_class = 'Class', _value = 'value', _style1 = this.STYLE_CLASS, _style2 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2);
    }
  }

  static logClassKey(_class = 'Class', _key = 'key', _value = 'value', _arrow = Log.ARROW_OUTPUT, _style1 = this.STYLE_CLASS, _style2 = this.STYLE_KEY, _style3 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS_KEY) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write key
      result += _key;
      // Set spacing
      const keyLength = _key.length;
      for (let i = 0; i < this.KEY_LENGTH - keyLength; i++) {
        result += ' ';
      }
      // Set style
      result += '%c';
      // Write arrow
      result += _arrow;
      // Set style
      result += '%c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2, this.STYLE_RESET, _style3);
    }
  }

  static log(_string, _align = this.ALIGN_LEFT, _style = this.STYLE_RESET) {
    // View permission
    if (this.LOG_VIEW) {
      let result = '';

      // String is null
      if (_string == null) {
        // Draw line
        for (let i = 0; i < this.LOG_LENGTH; i++) {
          result += this.LOG_CHARACTER;

        }
        // String exists
      } else {
        // Align left
        if (_align == this.ALIGN_LEFT) {
          // Write string
          result = _string;

          // Align center
        } else if (_align == this.ALIGN_CENTER) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < (this.LOG_LENGTH / 2) - (strLength / 2); i++) {
            result += ' ';
          }
          // Write string
          result += _string;

          // Align right
        } else if (_align == this.ALIGN_RIGHT) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < this.LOG_LENGTH - strLength; i++) {
            result += ' ';
          }
          // Write string
          result += _string;
        }
      }

      // Set style
      // Write result
      console.log(`%c${result}`, _style);
    }
  }
}

class LocalStorage {
  // Check localStorage support
  static get SUPPORT() {
    let result = true;
    if (!localStorage) {
      result = false;
    }
    return result;
  }

  // Build key
  static buildKey(_key) {
      return `${Project.NAME_KEY}.${_key}`;
  }

  // All clear localStorage
  static clear() {
    // Check support
    if (this.SUPPORT) {
      Log.logClass('Local Storage', 'All Clear.');
      // Clear
      localStorage.clear();
    }
  }

  // getItem from localStorage
  static getItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      const _val = localStorage.getItem(_key);
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_OUTPUT);
      // Get
      return _val;
    }
  }

  // setItem from localStorage
  static setItem(_key = 'key', _val = 'value') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_INPUT);
      // Set
      localStorage.setItem(_key, _val);
    }
  }

  // removeItem from localStorage
  static removeItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, 'null', Log.ARROW_INPUT);
      // Remove
      localStorage.removeItem(_key);
    }
  }
}

class SHA256 {
  static getHash(_string = null) {
    if (_string != null) {
      let shaObject = new jsSHA("SHA-256", "TEXT", 1);
      shaObject.update(_string);
      return shaObject.getHash("HEX");
    }
    return null;
  }
}

class Validate {
  static checkMaxLength(
    _string = null,
    _digit = null
  ) {
    if (_string != null && _digit != null) {
      if (_string.length <= _digit) {
        return true;
      }
    }
    return false;
  }
}
<commit_msg>Add function checkMinLength to Validate<commit_after>
// ----------------------------------------------------------------
// Static classes

class Log {
  // Common line setting
  static get LOG_LENGTH() { return 96; }
  static get LOG_CHARACTER() { return '-'; }

  // View permission
  static get LOG_VIEW() { return true; }
  static get LOG_VIEW_OBJECT() { return true; }
  static get LOG_VIEW_CLASS() { return true; }
  static get LOG_VIEW_CLASS_KEY() { return true; }
  static get LOG_VIEW_ERROR() { return true; }
  static get LOG_VIEW_CAUTION() { return true; }

  // Align definition
  static get ALIGN_LEFT() { return 0; }
  static get ALIGN_CENTER() { return 1; }
  static get ALIGN_RIGHT() { return 2; }

  // Arrow definition
  static get ARROW_OUTPUT() { return ' ---> '; }
  static get ARROW_INPUT() { return ' <--- '; }

  // Length definition
  static get CLASS_LENGTH() { return 24; }
  static get KEY_LENGTH() { return 24; }

  // Style definition
  static get STYLE_COLOR_RED() { return 'color:#f00;'; }
  static get STYLE_COLOR_GREEN() { return 'color:#0f0;'; }
  static get STYLE_COLOR_BLUE() { return 'color:#00f;'; }
  static get STYLE_COLOR_YELLOW() { return 'color:#ff0;'; }
  static get STYLE_COLOR_MAGENTA() { return 'color:#f0f;'; }
  static get STYLE_COLOR_CYAN() { return 'color:#0ff;'; }

  static get STYLE_CLASS() { return 'color:#222;'; }
  static get STYLE_KEY() { return 'color:#828;'; }
  static get STYLE_VALUE() { return 'color:#228;'; }

  static get STYLE_ERROR_LINE() { return 'color:#f00;'; }
  static get STYLE_ERROR_HEADER() { return 'color:#a00;'; }
  static get STYLE_ERROR_CONTENT() { return 'color:#111;'; }

  static get STYLE_CAUTION_LINE() { return 'color:#aa0;'; }
  static get STYLE_CAUTION_HEADER() { return 'color:#440;'; }
  static get STYLE_CAUTION_CONTENT() { return 'color:#111;'; }

  static logError(...array) {
    // View permission
    if (this.LOG_VIEW_ERROR) {
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
      // Write title
      this.log('ERROR', this.ALIGN_CENTER, this.STYLE_ERROR_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_ERROR_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
    }
  }

  static logCaution(...array) {
    // View permission
    if (this.LOG_VIEW_CAUTION) {
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
      // Write title
      this.log('CAUTION', this.ALIGN_CENTER, this.STYLE_CAUTION_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_CAUTION_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
    }
  }

  static logObj(_obj) {
    // View permission
    if (this.LOG_VIEW_OBJECT) {
      // Write object
      console.log(_obj);
    }
  }

  static logClass(_class = 'Class', _value = 'value', _style1 = this.STYLE_CLASS, _style2 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2);
    }
  }

  static logClassKey(_class = 'Class', _key = 'key', _value = 'value', _arrow = Log.ARROW_OUTPUT, _style1 = this.STYLE_CLASS, _style2 = this.STYLE_KEY, _style3 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS_KEY) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write key
      result += _key;
      // Set spacing
      const keyLength = _key.length;
      for (let i = 0; i < this.KEY_LENGTH - keyLength; i++) {
        result += ' ';
      }
      // Set style
      result += '%c';
      // Write arrow
      result += _arrow;
      // Set style
      result += '%c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2, this.STYLE_RESET, _style3);
    }
  }

  static log(_string, _align = this.ALIGN_LEFT, _style = this.STYLE_RESET) {
    // View permission
    if (this.LOG_VIEW) {
      let result = '';

      // String is null
      if (_string == null) {
        // Draw line
        for (let i = 0; i < this.LOG_LENGTH; i++) {
          result += this.LOG_CHARACTER;

        }
        // String exists
      } else {
        // Align left
        if (_align == this.ALIGN_LEFT) {
          // Write string
          result = _string;

          // Align center
        } else if (_align == this.ALIGN_CENTER) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < (this.LOG_LENGTH / 2) - (strLength / 2); i++) {
            result += ' ';
          }
          // Write string
          result += _string;

          // Align right
        } else if (_align == this.ALIGN_RIGHT) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < this.LOG_LENGTH - strLength; i++) {
            result += ' ';
          }
          // Write string
          result += _string;
        }
      }

      // Set style
      // Write result
      console.log(`%c${result}`, _style);
    }
  }
}

class LocalStorage {
  // Check localStorage support
  static get SUPPORT() {
    let result = true;
    if (!localStorage) {
      result = false;
    }
    return result;
  }

  // Build key
  static buildKey(_key) {
      return `${Project.NAME_KEY}.${_key}`;
  }

  // All clear localStorage
  static clear() {
    // Check support
    if (this.SUPPORT) {
      Log.logClass('Local Storage', 'All Clear.');
      // Clear
      localStorage.clear();
    }
  }

  // getItem from localStorage
  static getItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      const _val = localStorage.getItem(_key);
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_OUTPUT);
      // Get
      return _val;
    }
  }

  // setItem from localStorage
  static setItem(_key = 'key', _val = 'value') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_INPUT);
      // Set
      localStorage.setItem(_key, _val);
    }
  }

  // removeItem from localStorage
  static removeItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, 'null', Log.ARROW_INPUT);
      // Remove
      localStorage.removeItem(_key);
    }
  }
}

class SHA256 {
  static getHash(_string = null) {
    if (_string != null) {
      let shaObject = new jsSHA("SHA-256", "TEXT", 1);
      shaObject.update(_string);
      return shaObject.getHash("HEX");
    }
    return null;
  }
}

class Validate {
  static checkMaxLength(
    _string = null,
    _digit = null
  ) {
    if (_string != null && _digit != null) {
      if (_string.length <= _digit) {
        return true;
      }
    }
    return false;
  }

  static checkMinLength(
    _string = null,
    _digit = null
  ) {
    if (_string != null && _digit != null) {
      if (_string.length >= _digit) {
        return true;
      }
    }
    return false;
  }
}
<|endoftext|>