<commit_before>
describe('Observable Array', function() {
    beforeEach(function () {
        testObservableArray = new ko.observableArray([1, 2, 3]);
        notifiedValues = [];
        testObservableArray.subscribe(function (value) {
            notifiedValues.push(value ? value.slice(0) : value);
        });
        beforeNotifiedValues = [];
        testObservableArray.subscribe(function (value) {
            beforeNotifiedValues.push(value ? value.slice(0) : value);
        }, null, "beforeChange");
    });

    it('Should be observable', function () {
        expect(ko.isObservable(testObservableArray)).toEqual(true);
    });

    it('Should initialize to empty array if you pass no args to constructor', function() {
        var instance = new ko.observableArray();
        expect(instance().length).toEqual(0);
    });

    it('Should require constructor arg, if given, to be array-like or null or undefined', function() {
        // Try non-array-like args
        var threw;
        try { threw = false; new ko.observableArray(1); } catch(ex) { threw = true }
        expect(threw).toEqual(true);
        try { threw = false; new ko.observableArray({}); } catch(ex) { threw = true }
        expect(threw).toEqual(true);

        // Try allowed args
        expect((new ko.observableArray([1,2,3]))().length).toEqual(3);
        expect((new ko.observableArray(null))().length).toEqual(0);
        expect((new ko.observableArray(undefined))().length).toEqual(0);
    });

    it('Should be able to write values to it', function () {
        testObservableArray(['X', 'Y']);
        expect(notifiedValues.length).toEqual(1);
        expect(notifiedValues[0][0]).toEqual('X');
        expect(notifiedValues[0][1]).toEqual('Y');
    });

    it('Should be able to mark single items as destroyed', function() {
        var x = {}, y = {};
        testObservableArray([x, y]);
        testObservableArray.destroy(y);
        expect(testObservableArray().length).toEqual(2);
        expect(x._destroy).toEqual(undefined);
        expect(y._destroy).toEqual(true);
    });

    it('Should be able to mark multiple items as destroyed', function() {
        var x = {}, y = {}, z = {};
        testObservableArray([x, y, z]);
        testObservableArray.destroyAll([x, z]);
        expect(testObservableArray().length).toEqual(3);
        expect(x._destroy).toEqual(true);
        expect(y._destroy).toEqual(undefined);
        expect(z._destroy).toEqual(true);
    });

    it('Should be able to mark all items as destroyed by passing no args to destroyAll()', function() {
        var x = {}, y = {}, z = {};
        testObservableArray([x, y, z]);
        testObservableArray.destroyAll();
        expect(testObservableArray().length).toEqual(3);
        expect(x._destroy).toEqual(true);
        expect(y._destroy).toEqual(true);
        expect(z._destroy).toEqual(true);
    });

    it('Should notify subscribers on push', function () {
        testObservableArray.push("Some new value");
        expect(notifiedValues).toEqual([[1, 2, 3, "Some new value"]]);
    });

    it('Should notify "beforeChange" subscribers before push', function () {
        testObservableArray.push("Some new value");
        expect(beforeNotifiedValues).toEqual([[1, 2, 3]]);
    });

    it('Should notify subscribers on pop', function () {
        var popped = testObservableArray.pop();
        expect(popped).toEqual(3);
        expect(notifiedValues).toEqual([[1, 2]]);
    });

    it('Should notify "beforeChange" subscribers before pop', function () {
        var popped = testObservableArray.pop();
        expect(popped).toEqual(3);
        expect(beforeNotifiedValues).toEqual([[1, 2, 3]]);
    });

    it('Should notify subscribers on splice', function () {
        var spliced = testObservableArray.splice(1, 1);
        expect(spliced).toEqual([2]);
        expect(notifiedValues).toEqual([[1, 3]]);
    });

    it('Should notify "beforeChange" subscribers before splice', function () {
        var spliced = testObservableArray.splice(1, 1);
        expect(spliced).toEqual([2]);
        expect(beforeNotifiedValues).toEqual([[1, 2, 3]]);
    });

    it('Should notify subscribers on remove by value', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.remove("Beta");
        expect(removed).toEqual(["Beta"]);
        expect(notifiedValues).toEqual([["Alpha", "Gamma"]]);
    });

    it('Should notify subscribers on remove by predicate', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.remove(function (value) { return value == "Beta"; });
        expect(removed).toEqual(["Beta"]);
        expect(notifiedValues).toEqual([["Alpha", "Gamma"]]);
    });

    it('Should notify subscribers on remove multiple by value', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.removeAll(["Gamma", "Alpha"]);
        expect(removed).toEqual(["Alpha", "Gamma"]);
        expect(notifiedValues).toEqual([["Beta"]]);
    });

    it('Should clear observable array entirely if you pass no args to removeAll()', function() {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.removeAll();
        expect(removed).toEqual(["Alpha", "Beta", "Gamma"]);
        expect(notifiedValues).toEqual([[]]);
    });

    it('Should notify "beforeChange" subscribers before remove', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        beforeNotifiedValues = [];
        var removed = testObservableArray.remove("Beta");
        expect(removed).toEqual(["Beta"]);
        expect(beforeNotifiedValues).toEqual([["Alpha", "Beta", "Gamma"]]);
    });

    it('Should not notify subscribers on remove by value with no match', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.remove("Delta");
        expect(removed).toEqual([]);
        expect(notifiedValues).toEqual([]);
    });

    it('Should not notify "beforeChange" subscribers before remove by value with no match', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        beforeNotifiedValues = [];
        var removed = testObservableArray.remove("Delta");
        expect(removed).toEqual([]);
        expect(beforeNotifiedValues).toEqual([]);
    });

    it('Should modify original array on remove', function () {
        var originalArray = ["Alpha", "Beta", "Gamma"];
        testObservableArray(originalArray);
        notifiedValues = [];
        var removed = testObservableArray.remove("Beta");
        expect(originalArray).toEqual(["Alpha", "Gamma"]);
    });

    it('Should modify original array on removeAll', function () {
        var originalArray = ["Alpha", "Beta", "Gamma"];
        testObservableArray(originalArray);
        notifiedValues = [];
        var removed = testObservableArray.removeAll();
        expect(originalArray).toEqual([]);
    });

    it('Should notify subscribers on replace', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        testObservableArray.replace("Beta", "Delta");
        expect(notifiedValues).toEqual([["Alpha", "Delta", "Gamma"]]);
    });

    it('Should notify "beforeChange" subscribers before replace', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        beforeNotifiedValues = [];
        testObservableArray.replace("Beta", "Delta");
        expect(beforeNotifiedValues).toEqual([["Alpha", "Beta", "Gamma"]]);
    });

    it('Should notify subscribers after marking items as destroyed', function () {
        var x = {}, y = {}, didNotify = false;
        testObservableArray([x, y]);
        testObservableArray.subscribe(function(value) {
            expect(x._destroy).toEqual(undefined);
            expect(y._destroy).toEqual(true);
            didNotify = true;
        });
        testObservableArray.destroy(y);
        expect(didNotify).toEqual(true);
    });

    it('Should notify "beforeChange" subscribers before marking items as destroyed', function () {
        var x = {}, y = {}, didNotify = false;
        testObservableArray([x, y]);
        testObservableArray.subscribe(function(value) {
            expect(x._destroy).toEqual(undefined);
            expect(y._destroy).toEqual(undefined);
            didNotify = true;
        }, null, "beforeChange");
        testObservableArray.destroy(y);
        expect(didNotify).toEqual(true);
    });

    it('Should be able to return first index of item', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        expect(testObservableArray.indexOf("Beta")).toEqual(1);
        expect(testObservableArray.indexOf("Gamma")).toEqual(2);
        expect(testObservableArray.indexOf("Alpha")).toEqual(0);
        expect(testObservableArray.indexOf("fake")).toEqual(-1);
    });

    it('Should return 0 when you call myArray.length, and the true length when you call myArray().length', function() {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        expect(testObservableArray.length).toEqual(0); // Because JavaScript won't let us override "length" directly
        expect(testObservableArray().length).toEqual(3);
    });

    it('Should be able to call standard mutators without creating a subscription', function() {
        var timesEvaluated = 0,
            newArray = ko.observableArray(["Alpha", "Beta", "Gamma"]);

        var computed = ko.computed(function() {
            // Make a few standard mutations
            newArray.push("Delta");
            newArray.remove("Beta");
            newArray.splice(2, 1);

            // Peek to ensure we really had the intended effect
            expect(newArray.peek()).toEqual(["Alpha", "Gamma"]);

            // Also make use of the KO delete/destroy functions to check they don't cause subscriptions
            newArray([{ someProp: 123 }]);
            newArray.destroyAll();
            expect(newArray.peek()[0]._destroy).toEqual(true);
            newArray.removeAll();
            expect(newArray.peek()).toEqual([]);

            timesEvaluated++;
        });

        // Verify that we haven't caused a subscription
        expect(timesEvaluated).toEqual(1);
        expect(newArray.getSubscriptionsCount()).toEqual(0);

        // Don't just trust getSubscriptionsCount - directly verify that mutating newArray doesn't cause a re-eval
        newArray.push("Another");
        expect(timesEvaluated).toEqual(1);
    });
})
<commit_msg>Add tests showing proper behavior when removing or "destroying" observables in an observable array.<commit_after>
describe('Observable Array', function() {
    beforeEach(function () {
        testObservableArray = new ko.observableArray([1, 2, 3]);
        notifiedValues = [];
        testObservableArray.subscribe(function (value) {
            notifiedValues.push(value ? value.slice(0) : value);
        });
        beforeNotifiedValues = [];
        testObservableArray.subscribe(function (value) {
            beforeNotifiedValues.push(value ? value.slice(0) : value);
        }, null, "beforeChange");
    });

    it('Should be observable', function () {
        expect(ko.isObservable(testObservableArray)).toEqual(true);
    });

    it('Should initialize to empty array if you pass no args to constructor', function() {
        var instance = new ko.observableArray();
        expect(instance().length).toEqual(0);
    });

    it('Should require constructor arg, if given, to be array-like or null or undefined', function() {
        // Try non-array-like args
        var threw;
        try { threw = false; new ko.observableArray(1); } catch(ex) { threw = true }
        expect(threw).toEqual(true);
        try { threw = false; new ko.observableArray({}); } catch(ex) { threw = true }
        expect(threw).toEqual(true);

        // Try allowed args
        expect((new ko.observableArray([1,2,3]))().length).toEqual(3);
        expect((new ko.observableArray(null))().length).toEqual(0);
        expect((new ko.observableArray(undefined))().length).toEqual(0);
    });

    it('Should be able to write values to it', function () {
        testObservableArray(['X', 'Y']);
        expect(notifiedValues.length).toEqual(1);
        expect(notifiedValues[0][0]).toEqual('X');
        expect(notifiedValues[0][1]).toEqual('Y');
    });

    it('Should be able to mark single items as destroyed', function() {
        var x = {}, y = {};
        testObservableArray([x, y]);
        testObservableArray.destroy(y);
        expect(testObservableArray().length).toEqual(2);
        expect(x._destroy).toEqual(undefined);
        expect(y._destroy).toEqual(true);
    });

    it('Should be able to mark multiple items as destroyed', function() {
        var x = {}, y = {}, z = {};
        testObservableArray([x, y, z]);
        testObservableArray.destroyAll([x, z]);
        expect(testObservableArray().length).toEqual(3);
        expect(x._destroy).toEqual(true);
        expect(y._destroy).toEqual(undefined);
        expect(z._destroy).toEqual(true);
    });

    it('Should be able to mark observable items as destroyed', function() {
        var x = ko.observable(), y = ko.observable();
        testObservableArray([x, y]);
        testObservableArray.destroy(y);
        expect(testObservableArray().length).toEqual(2);
        expect(x._destroy).toEqual(undefined);
        expect(y._destroy).toEqual(true);
    });

    it('Should be able to mark all items as destroyed by passing no args to destroyAll()', function() {
        var x = {}, y = {}, z = {};
        testObservableArray([x, y, z]);
        testObservableArray.destroyAll();
        expect(testObservableArray().length).toEqual(3);
        expect(x._destroy).toEqual(true);
        expect(y._destroy).toEqual(true);
        expect(z._destroy).toEqual(true);
    });

    it('Should notify subscribers on push', function () {
        testObservableArray.push("Some new value");
        expect(notifiedValues).toEqual([[1, 2, 3, "Some new value"]]);
    });

    it('Should notify "beforeChange" subscribers before push', function () {
        testObservableArray.push("Some new value");
        expect(beforeNotifiedValues).toEqual([[1, 2, 3]]);
    });

    it('Should notify subscribers on pop', function () {
        var popped = testObservableArray.pop();
        expect(popped).toEqual(3);
        expect(notifiedValues).toEqual([[1, 2]]);
    });

    it('Should notify "beforeChange" subscribers before pop', function () {
        var popped = testObservableArray.pop();
        expect(popped).toEqual(3);
        expect(beforeNotifiedValues).toEqual([[1, 2, 3]]);
    });

    it('Should notify subscribers on splice', function () {
        var spliced = testObservableArray.splice(1, 1);
        expect(spliced).toEqual([2]);
        expect(notifiedValues).toEqual([[1, 3]]);
    });

    it('Should notify "beforeChange" subscribers before splice', function () {
        var spliced = testObservableArray.splice(1, 1);
        expect(spliced).toEqual([2]);
        expect(beforeNotifiedValues).toEqual([[1, 2, 3]]);
    });

    it('Should notify subscribers on remove by value', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.remove("Beta");
        expect(removed).toEqual(["Beta"]);
        expect(notifiedValues).toEqual([["Alpha", "Gamma"]]);
    });

    it('Should notify subscribers on remove by predicate', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.remove(function (value) { return value == "Beta"; });
        expect(removed).toEqual(["Beta"]);
        expect(notifiedValues).toEqual([["Alpha", "Gamma"]]);
    });

    it('Should notify subscribers on remove multiple by value', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.removeAll(["Gamma", "Alpha"]);
        expect(removed).toEqual(["Alpha", "Gamma"]);
        expect(notifiedValues).toEqual([["Beta"]]);
    });

    it('Should clear observable array entirely if you pass no args to removeAll()', function() {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.removeAll();
        expect(removed).toEqual(["Alpha", "Beta", "Gamma"]);
        expect(notifiedValues).toEqual([[]]);
    });

    it('Should notify "beforeChange" subscribers before remove', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        beforeNotifiedValues = [];
        var removed = testObservableArray.remove("Beta");
        expect(removed).toEqual(["Beta"]);
        expect(beforeNotifiedValues).toEqual([["Alpha", "Beta", "Gamma"]]);
    });

    it('Should not notify subscribers on remove by value with no match', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        var removed = testObservableArray.remove("Delta");
        expect(removed).toEqual([]);
        expect(notifiedValues).toEqual([]);
    });

    it('Should not notify "beforeChange" subscribers before remove by value with no match', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        beforeNotifiedValues = [];
        var removed = testObservableArray.remove("Delta");
        expect(removed).toEqual([]);
        expect(beforeNotifiedValues).toEqual([]);
    });

    it('Should modify original array on remove', function () {
        var originalArray = ["Alpha", "Beta", "Gamma"];
        testObservableArray(originalArray);
        notifiedValues = [];
        var removed = testObservableArray.remove("Beta");
        expect(originalArray).toEqual(["Alpha", "Gamma"]);
    });

    it('Should modify original array on removeAll', function () {
        var originalArray = ["Alpha", "Beta", "Gamma"];
        testObservableArray(originalArray);
        notifiedValues = [];
        var removed = testObservableArray.removeAll();
        expect(originalArray).toEqual([]);
    });

    it('Should remove matching observable items', function() {
        var x = ko.observable(), y = ko.observable();
        testObservableArray([x, y]);
        notifiedValues = [];
        var removed = testObservableArray.remove(y);
        expect(testObservableArray()).toEqual([x]);
        expect(removed).toEqual([y]);
        expect(notifiedValues).toEqual([[x]]);
    });

    it('Should notify subscribers on replace', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        notifiedValues = [];
        testObservableArray.replace("Beta", "Delta");
        expect(notifiedValues).toEqual([["Alpha", "Delta", "Gamma"]]);
    });

    it('Should notify "beforeChange" subscribers before replace', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        beforeNotifiedValues = [];
        testObservableArray.replace("Beta", "Delta");
        expect(beforeNotifiedValues).toEqual([["Alpha", "Beta", "Gamma"]]);
    });

    it('Should notify subscribers after marking items as destroyed', function () {
        var x = {}, y = {}, didNotify = false;
        testObservableArray([x, y]);
        testObservableArray.subscribe(function(value) {
            expect(x._destroy).toEqual(undefined);
            expect(y._destroy).toEqual(true);
            didNotify = true;
        });
        testObservableArray.destroy(y);
        expect(didNotify).toEqual(true);
    });

    it('Should notify "beforeChange" subscribers before marking items as destroyed', function () {
        var x = {}, y = {}, didNotify = false;
        testObservableArray([x, y]);
        testObservableArray.subscribe(function(value) {
            expect(x._destroy).toEqual(undefined);
            expect(y._destroy).toEqual(undefined);
            didNotify = true;
        }, null, "beforeChange");
        testObservableArray.destroy(y);
        expect(didNotify).toEqual(true);
    });

    it('Should be able to return first index of item', function () {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        expect(testObservableArray.indexOf("Beta")).toEqual(1);
        expect(testObservableArray.indexOf("Gamma")).toEqual(2);
        expect(testObservableArray.indexOf("Alpha")).toEqual(0);
        expect(testObservableArray.indexOf("fake")).toEqual(-1);
    });

    it('Should return 0 when you call myArray.length, and the true length when you call myArray().length', function() {
        testObservableArray(["Alpha", "Beta", "Gamma"]);
        expect(testObservableArray.length).toEqual(0); // Because JavaScript won't let us override "length" directly
        expect(testObservableArray().length).toEqual(3);
    });

    it('Should be able to call standard mutators without creating a subscription', function() {
        var timesEvaluated = 0,
            newArray = ko.observableArray(["Alpha", "Beta", "Gamma"]);

        var computed = ko.computed(function() {
            // Make a few standard mutations
            newArray.push("Delta");
            newArray.remove("Beta");
            newArray.splice(2, 1);

            // Peek to ensure we really had the intended effect
            expect(newArray.peek()).toEqual(["Alpha", "Gamma"]);

            // Also make use of the KO delete/destroy functions to check they don't cause subscriptions
            newArray([{ someProp: 123 }]);
            newArray.destroyAll();
            expect(newArray.peek()[0]._destroy).toEqual(true);
            newArray.removeAll();
            expect(newArray.peek()).toEqual([]);

            timesEvaluated++;
        });

        // Verify that we haven't caused a subscription
        expect(timesEvaluated).toEqual(1);
        expect(newArray.getSubscriptionsCount()).toEqual(0);

        // Don't just trust getSubscriptionsCount - directly verify that mutating newArray doesn't cause a re-eval
        newArray.push("Another");
        expect(timesEvaluated).toEqual(1);
    });
})
<|endoftext|>


<commit_before>'use strict';

class Employee {
  constructor(status) {
    this.status = status;
  }

  isDead() {
    return this.status === 'DEAD';
  }

  isSeparated() {
    return this.status === 'SEPARATED';
  }

  isRetired() {
    return this.status === 'RETIRED';
  }

  getPaymentAmount() {
    let result='';
    if (this.isDead()) {
      result = deadAmount()
    } else {
      if (this.isSeparated()) {
        result = separatedAmount()
      } else {
        if (this.isRetired()) {
          result = retiredAmount()
        } else {
          result = normalPayAmount()
        }
      }
    }
    return result
  }
}

function deadAmount() {
  return 'deadAmount';
}
function separatedAmount() {
  return 'separatedAmount';
}
function retiredAmount() {
  return 'retiredAmount';
}
function normalPayAmount() {
  return 'normalPayAmount';
}

module.exports = Employee;<commit_msg>[jiefeng] [Replace Nested Conditional with Guard Clauses] replace with Guard Clauses.<commit_after>'use strict';

class Employee {
  constructor(status) {
    this.status = status;
  }

  isDead() {
    return this.status === 'DEAD';
  }

  isSeparated() {
    return this.status === 'SEPARATED';
  }

  isRetired() {
    return this.status === 'RETIRED';
  }

  getPaymentAmount() {
    let result = '';
    if (this.isDead()) return deadAmount();
    if (this.isSeparated()) {
      result = separatedAmount()
    } else {
      if (this.isRetired()) {
        result = retiredAmount()
      } else {
        result = normalPayAmount()
      }
    }
    return result
  }
}

function deadAmount() {
  return 'deadAmount';
}
function separatedAmount() {
  return 'separatedAmount';
}
function retiredAmount() {
  return 'retiredAmount';
}
function normalPayAmount() {
  return 'normalPayAmount';
}

module.exports = Employee;<|endoftext|>


<commit_before>//META{"name":"EvenBetterDiscord"}*//

let request = require('request');
let fs = require('fs');

let EvenBetterDiscord = function ()
{
    this.targetAPI = "https://api.github.com/repos/DeathStrikeV/BetterDiscordApp/commits/master";
    this.targetURL = "https://raw.githubusercontent.com/DeathStrikeV/BetterDiscordApp/master/data/emotedata_ffz.json";

    this.bdPath = (process.platform == "win32" ?
        process.env.APPDATA : process.platform == "darwin" ?
        process.env.HOME + "/Library/Preferences/" : "/var/local/") + "/BetterDiscord/";

    this.preferencesFile = this.bdPath + "/EBD_Preferences.json";
    this.emotesFile = this.bdPath + "/EBD_Emotes.json";
    this.defaultEmotesFile = this.bdPath + "/emotes_ffz.json";
};

EvenBetterDiscord.prototype.start = function ()
{
    this.loadEBDFiles();
};

EvenBetterDiscord.prototype.loadEBDFiles = function ()
{
    let readPreferencesFile = function (err, data)
    {
        if (data)
            this.currentHash = JSON.parse(data).currentHash;
        else
            this.currentHash = "";

        if (this.currentHash === "ignore")
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        request({ url: this.targetAPI, headers: { "User-Agent": "DeathStrikeV" } }, requestRepoHash.bind(this));
    };

    let requestRepoHash = function (error, response, body)
    {
        if (response.statusCode !== 200)
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        this.latestHash = JSON.parse(body).sha;

        if (this.currentHash === this.latestHash)
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        request(this.targetURL, downloadEmotesFile.bind(this));
    };

    let downloadEmotesFile = function (error, response, body)
    {
        if (response.statusCode !== 200)
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        fs.writeFile(this.emotesFile, body, saveEmotesFile.bind(this));
    };

    let saveEmotesFile = function (err)
    {
        if (!err)
        {
            //console.log("Retreived new emotes file!");
            fs.writeFile(this.preferencesFile, JSON.stringify({ currentHash: this.latestHash }), null);
        }

        this.loadEmotes(this.emotesFile);
    }

    fs.readFile(this.preferencesFile, "utf8", readPreferencesFile.bind(this));
};

EvenBetterDiscord.prototype.loadEmotes = function (targetFile)
{
    fs.readFile(targetFile, "utf8", (err, data) =>
    {
        if (data)
        {
            let emoteData = JSON.parse(data);

            if (!emoteData)
            {
                //console.log("Failed to parse emotes file!");
                return;
            }

            window.emotesFfz = emoteData;
            //console.log("Loaded emotes file!");

            //TODO: Replace localstorage
            //this.fixBrokenFavorites();
        }
    });
};

EvenBetterDiscord.prototype.fixBrokenFavorites = function ()
{
    if (typeof localStorage !== "undefined")
        return;

    let result;
    let regex = new RegExp("\"([\\w!]+(?:~\\d+)?)\":\"https:\\/\\/cdn\\.frankerfacez\\.com\\/emoticon\\/\\d*\\/", "g");
    let brokenFavorites = atob(localStorage.bdfavemotes);
    let fixedFavorites = brokenFavorites;

    while (result = regex.exec(brokenFavorites))
    {
        if (!emotesFfz[result[1]])
            continue;

        let replacementRegex = new RegExp("\"" + result[1] + "\":\"https:\\/\\/cdn\\.frankerfacez\\.com\\/emoticon\\/\\d*\\/", "g");
        let replacementString = "\"" + result[1] + "\":\"https://cdn.frankerfacez.com/emoticon/" + emotesFfz[result[1]] + "/";
        fixedFavorites = fixedFavorites.replace(replacementRegex, replacementString);
    }

    localStorage.bdfavemotes = btoa(fixedFavorites);
    quickEmoteMenu.favoriteEmotes = JSON.parse(fixedFavorites);
    quickEmoteMenu.updateFavorites();
};

EvenBetterDiscord.prototype.stop = function ()
{
    this.removeEBDFiles();
    this.loadEmotes(this.defaultEmotesFile);
};

EvenBetterDiscord.prototype.removeEBDFiles = function ()
{
    fs.stat(this.preferencesFile, (err, stats) =>
    {
        if (err)
            return;

        fs.unlink(this.preferencesFile, (err) => { });
    });

    fs.stat(this.emotesFile, (err, stats) =>
    {
        if (err)
            return;

        fs.unlink(this.emotesFile, (err) => { });
    });
};

EvenBetterDiscord.prototype.load = function () { };
EvenBetterDiscord.prototype.unload = function () { };
EvenBetterDiscord.prototype.onMessage = function () { };
EvenBetterDiscord.prototype.onSwitch = function () { };

EvenBetterDiscord.prototype.getName = function ()
{
    return "EvenBetterDiscord";
};

EvenBetterDiscord.prototype.getDescription = function ()
{
    return "Loads FFZ emotes from alternate repository";
};

EvenBetterDiscord.prototype.getVersion = function ()
{
    return "1.1.1";
};

EvenBetterDiscord.prototype.getAuthor = function ()
{
    return "DeathStrikeV";
};<commit_msg>Updated plugin<commit_after>//META{"name":"EvenBetterDiscord"}*//

let request = require('request');
let fs = require('fs');

let EvenBetterDiscord = function ()
{
    this.targetAPI = "https://api.github.com/repos/DeathStrikeV/BetterDiscordApp/commits/master";
    this.targetURL = "https://raw.githubusercontent.com/DeathStrikeV/BetterDiscordApp/master/data/emotedata_ffz.json";

    this.bdPath = (process.platform == "win32" ?
        process.env.APPDATA : process.platform == "darwin" ?
        process.env.HOME + "/Library/Preferences/" : "/var/local/") + "/BetterDiscord/";

    this.preferencesFile = this.bdPath + "/EBD_Preferences.json";
    this.emotesFile = this.bdPath + "/EBD_Emotes.json";
    this.defaultEmotesFile = this.bdPath + "/emotes_ffz.json";
};

EvenBetterDiscord.prototype.start = function ()
{
    this.loadEBDFiles();
};

EvenBetterDiscord.prototype.loadEBDFiles = function ()
{
    let readPreferencesFile = function (err, data)
    {
        if (data)
            this.currentHash = JSON.parse(data).currentHash;
        else
            this.currentHash = "";

        if (this.currentHash === "ignore")
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        request({ url: this.targetAPI, headers: { "User-Agent": "DeathStrikeV" } }, requestRepoHash.bind(this));
    };

    let requestRepoHash = function (error, response, body)
    {
        if (response.statusCode !== 200)
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        this.latestHash = JSON.parse(body).sha;

        if (this.currentHash === this.latestHash)
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        request(this.targetURL, downloadEmotesFile.bind(this));
    };

    let downloadEmotesFile = function (error, response, body)
    {
        if (response.statusCode !== 200)
        {
            this.loadEmotes(this.emotesFile);
            return;
        }

        fs.writeFile(this.emotesFile, body, saveEmotesFile.bind(this));
    };

    let saveEmotesFile = function (err)
    {
        if (!err)
        {
            //console.log("Retreived new emotes file!");
            fs.writeFile(this.preferencesFile, JSON.stringify({ currentHash: this.latestHash }), null);
        }

        this.loadEmotes(this.emotesFile);
    }

    fs.readFile(this.preferencesFile, "utf8", readPreferencesFile.bind(this));
};

EvenBetterDiscord.prototype.loadEmotes = function (targetFile)
{
    fs.readFile(targetFile, "utf8", (err, data) =>
    {
        if (data)
        {
            let emoteData = JSON.parse(data);

            if (!emoteData)
            {
                //console.log("Failed to parse emotes file!");
                return;
            }

            window.emotesFfz = emoteData;
            //console.log("Loaded emotes file!");

            this.fixBrokenFavorites();
        }
    });
};

EvenBetterDiscord.prototype.fixBrokenFavorites = function ()
{
    if (typeof localStorage !== "undefined")
        return;

    let result;
    let regex = new RegExp("\"([\\w!]+(?:~\\d+)?)\":\"https:\\/\\/cdn\\.frankerfacez\\.com\\/emoticon\\/\\d*\\/", "g");
    let brokenFavorites = atob(localStorage.bdfavemotes);
    let fixedFavorites = brokenFavorites;

    while (result = regex.exec(brokenFavorites))
    {
        if (!emotesFfz[result[1]])
            continue;

        let replacementRegex = new RegExp("\"" + result[1] + "\":\"https:\\/\\/cdn\\.frankerfacez\\.com\\/emoticon\\/\\d*\\/", "g");
        let replacementString = "\"" + result[1] + "\":\"https://cdn.frankerfacez.com/emoticon/" + emotesFfz[result[1]] + "/";
        fixedFavorites = fixedFavorites.replace(replacementRegex, replacementString);
    }

    localStorage.bdfavemotes = btoa(fixedFavorites);
    quickEmoteMenu.favoriteEmotes = JSON.parse(fixedFavorites);
    quickEmoteMenu.updateFavorites();
};

EvenBetterDiscord.prototype.stop = function ()
{
    this.removeEBDFiles();
    this.loadEmotes(this.defaultEmotesFile);
};

EvenBetterDiscord.prototype.removeEBDFiles = function ()
{
    fs.stat(this.preferencesFile, (err, stats) =>
    {
        if (err)
            return;

        fs.unlink(this.preferencesFile, (err) => { });
    });

    fs.stat(this.emotesFile, (err, stats) =>
    {
        if (err)
            return;

        fs.unlink(this.emotesFile, (err) => { });
    });
};

EvenBetterDiscord.prototype.load = function () { };
EvenBetterDiscord.prototype.unload = function () { };
EvenBetterDiscord.prototype.onMessage = function () { };
EvenBetterDiscord.prototype.onSwitch = function () { };

EvenBetterDiscord.prototype.getName = function ()
{
    return "EvenBetterDiscord";
};

EvenBetterDiscord.prototype.getDescription = function ()
{
    return "Loads FFZ emotes from alternate repository";
};

EvenBetterDiscord.prototype.getVersion = function ()
{
    return "1.1.2";
};

EvenBetterDiscord.prototype.getAuthor = function ()
{
    return "DeathStrikeV";
};<|endoftext|>


<commit_before>// @flow weak
import React, { PureComponent, PropTypes } from 'react';
import transition from './transition';
import stop from './stop';
import { getDisplayName } from './helpers';
import { APPEAR, UPDATE, REMOVE } from '../core/types';

const propTypes = {
  type: PropTypes.string.isRequired,
  udid: PropTypes.string.isRequired,
  node: PropTypes.object.isRequired,
  removeUDID: PropTypes.func.isRequired,
};

function withTransitions(Component) {
  class Transition extends PureComponent {
    static propTypes = propTypes;

    static displayName = `withTransition(${getDisplayName(Component)})`

    constructor(props) {
      super(props);

      (this:any).getNodeRef = this.getNodeRef.bind(this);
      (this:any).removeNode = this.removeNode.bind(this);
    }

    componentDidMount() {
      this.invokeMethodIfExists('onAppear');
    }

    componentDidUpdate(prev) {
      const { props } = this;

      if (
        prev.node !== props.node ||
        prev.type !== props.type
      ) {
        const prevProps = Object.assign({}, prev, {
          data: prev.node,
        });

        Object.keys(propTypes).forEach((p) => {
          delete prevProps[p];
        });

        switch (props.type) {
          case APPEAR:
            this.invokeMethodIfExists('onAppear', prevProps);
            break;
          case UPDATE:
            this.invokeMethodIfExists('onUpdate', prevProps);
            break;
          case REMOVE:
            this.invokeMethodIfExists('onRemove', prevProps);
            break;
          default:
            break;
        }
      }
    }

    componentWillUnmount() {
      stop.call(this.node);
    }

    node = null; // ref for wrapped component

    invokeMethodIfExists(method, prevProps) {
      const { node } = this;
      if (node && node[method]) {
        transition.call(node, node[method](prevProps || node.props));
      }
    }

    removeNode() {
      const { removeUDID, udid } = this.props;
      removeUDID(udid);
    }

    getNodeRef(d) {
      this.node = d;
    }

    render() {
      const props = Object.assign({}, this.props);

      Object.keys(propTypes).forEach((p) => {
        delete props[p];
      });

      return (
        <Component
          ref={this.getNodeRef}
          type={this.props.type}
          data={this.props.node}
          removeNode={this.removeNode}
          {...props}
        />
      );
    }
  }

  return Transition;
}

export default withTransitions;
<commit_msg>fix displayname<commit_after>// @flow weak
import React, { PureComponent, PropTypes } from 'react';
import transition from './transition';
import stop from './stop';
import { getDisplayName } from './helpers';
import { APPEAR, UPDATE, REMOVE } from '../core/types';

const propTypes = {
  type: PropTypes.string.isRequired,
  udid: PropTypes.string.isRequired,
  node: PropTypes.object.isRequired,
  removeUDID: PropTypes.func.isRequired,
};

function withTransitions(Component) {
  class Transition extends PureComponent {
    static propTypes = propTypes;

    static displayName = `withTransitions(${getDisplayName(Component)})`

    constructor(props) {
      super(props);

      (this:any).getNodeRef = this.getNodeRef.bind(this);
      (this:any).removeNode = this.removeNode.bind(this);
    }

    componentDidMount() {
      this.invokeMethodIfExists('onAppear');
    }

    componentDidUpdate(prev) {
      const { props } = this;

      if (
        prev.node !== props.node ||
        prev.type !== props.type
      ) {
        const prevProps = Object.assign({}, prev, {
          data: prev.node,
        });

        Object.keys(propTypes).forEach((p) => {
          delete prevProps[p];
        });

        switch (props.type) {
          case APPEAR:
            this.invokeMethodIfExists('onAppear', prevProps);
            break;
          case UPDATE:
            this.invokeMethodIfExists('onUpdate', prevProps);
            break;
          case REMOVE:
            this.invokeMethodIfExists('onRemove', prevProps);
            break;
          default:
            break;
        }
      }
    }

    componentWillUnmount() {
      stop.call(this.node);
    }

    node = null; // ref for wrapped component

    invokeMethodIfExists(method, prevProps) {
      const { node } = this;
      if (node && node[method]) {
        transition.call(node, node[method](prevProps || node.props));
      }
    }

    removeNode() {
      const { removeUDID, udid } = this.props;
      removeUDID(udid);
    }

    getNodeRef(d) {
      this.node = d;
    }

    render() {
      const props = Object.assign({}, this.props);

      Object.keys(propTypes).forEach((p) => {
        delete props[p];
      });

      return (
        <Component
          ref={this.getNodeRef}
          type={this.props.type}
          data={this.props.node}
          removeNode={this.removeNode}
          {...props}
        />
      );
    }
  }

  return Transition;
}

export default withTransitions;
<|endoftext|>


<commit_before>/*global describe, it, expect, require, jasmine */
'use strict';
var reply = require('../../lib/twilio/reply'),
  qs = require('querystring'),
  https = require('https');

describe('Twilio Reply', () => {

  it('includes the Twilio Authorization and Content type x-www-form-urlencoded in the header', done => {
    https.request.pipe(callOptions => {
      var data = qs.encode({ To: '+4444444444', From: '+333333333', Body: 'SMS Twilio'});
      expect(callOptions).toEqual(jasmine.objectContaining({
        method: 'POST',
        hostname: 'api.twilio.com',
        path: '/2010-04-01/Accounts/someRandomTwilioAccountSID/Messages.json',
        headers: {
          'Authorization': `Basic ${new Buffer('someRandomTwilioAccountSID' + ':' + 'RandomTwilioAuthToken').toString('base64')}`,
          'content-type': 'application/x-www-form-urlencoded',
          'content-length': Buffer.byteLength(data)
        },
        body: data
      }));
      done();
    });
    reply('someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio');
  });

  it('sends text messages as a string', done => {
    https.request.pipe(callOptions => {
      expect(JSON.parse(JSON.stringify(qs.parse(callOptions.body)))).toEqual({
        To: '+4444444444',
        From: '+333333333',
        Body: 'SMS Twilio'
      });
      done();
    });
    reply('someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio');
  });

  it('does not resolve before the https endpoint responds', done => {
    https.request.pipe(done);
    reply(
      'someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio'
    ).then(done.fail, done.fail);
  });

  it('resolves when the https endpoint responds with 200', done => {
    https.request.pipe(() => {
      setTimeout(() => {
        https.request.calls[0].respond('200', 'OK', 'SMS Twilio');
      }, 10);
    });
    reply(
      'someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio'
    ).then(done, done.fail);
  });

});
<commit_msg>Fix/spec object comparison (#80)<commit_after>/*global describe, it, expect, require, jasmine */
'use strict';
var reply = require('../../lib/twilio/reply'),
  qs = require('querystring'),
  https = require('https');

describe('Twilio Reply', () => {

  it('includes the Twilio Authorization and Content type x-www-form-urlencoded in the header', done => {
    https.request.pipe(callOptions => {
      var data = qs.encode({ To: '+4444444444', From: '+333333333', Body: 'SMS Twilio'});
      expect(callOptions).toEqual(jasmine.objectContaining({
        method: 'POST',
        hostname: 'api.twilio.com',
        path: '/2010-04-01/Accounts/someRandomTwilioAccountSID/Messages.json',
        headers: {
          'Authorization': `Basic ${new Buffer('someRandomTwilioAccountSID' + ':' + 'RandomTwilioAuthToken').toString('base64')}`,
          'content-type': 'application/x-www-form-urlencoded',
          'content-length': Buffer.byteLength(data)
        },
        body: data
      }));
      done();
    });
    reply('someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio');
  });

  it('sends text messages as a string', done => {
    https.request.pipe(callOptions => {
      expect(qs.parse(callOptions.body)).toEqual(jasmine.objectContaining({
        To: '+4444444444',
        From: '+333333333',
        Body: 'SMS Twilio'
      }));
      done();
    });
    reply('someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio');
  });

  it('does not resolve before the https endpoint responds', done => {
    https.request.pipe(done);
    reply(
      'someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio'
    ).then(done.fail, done.fail);
  });

  it('resolves when the https endpoint responds with 200', done => {
    https.request.pipe(() => {
      setTimeout(() => {
        https.request.calls[0].respond('200', 'OK', 'SMS Twilio');
      }, 10);
    });
    reply(
      'someRandomTwilioAccountSID', 'RandomTwilioAuthToken',
      '+333333333', '+4444444444', 'SMS Twilio'
    ).then(done, done.fail);
  });

});
<|endoftext|>


<commit_before>describe('filetree', function(){
  var controller;
  var $filetreeService;
  var filetreeCtrl;
  var httpBackend;
  var dirs = [{
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }, {
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "root",
        "is_accessible": false,
        "perm": "-rw-r--r--",
        "perm_string": "644",
        "size": "4.0 KiB",
        "type": "dir"
      },
      {
        "filepath": "/home/saurabh/dir3",
        "filename": "dir3",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }];
  beforeEach(module('oide'));
  beforeEach(module('oide.editor'));

  beforeEach(inject(function($controller, $rootScope, $log, $document, FiletreeService, $httpBackend){
    scope = $rootScope.$new();
    httpBackend = $httpBackend;
    httpBackend.whenGET('/filebrowser/filetree/a/dir').respond(function(){
      return [200, dirs];
    });
    controller = $controller;
    $filetreeService = FiletreeService;
    filetreeCtrl = $controller('FiletreeCtrl', {
      $scope: scope,
      $document: $document,
      $log: $log,
      FileTreeService: $filetreeService
    });
    scope.ctrl = controller;
    scope.$apply();
  }));

  //Expect Filetree service to be defined
  describe('Whether the filetree is working as expected or not', function(){
    it('Controller initialization should be proper', function(){
      httpBackend.flush();
      expect($filetreeService).toBeDefined();
      expect($filetreeService.treeData).toBeDefined();
    });
  });

});
<commit_msg>add spec to test getDirContents method of controller<commit_after>describe('filetree', function(){
  var controller;
  var $filetreeService;
  var filetreeCtrl;
  var httpBackend;
  var dirs = [{
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }, {
        "filepath": "/home/saurabh/dir2",
        "filename": "dir2",
        "group": "root",
        "is_accessible": false,
        "perm": "-rw-r--r--",
        "perm_string": "644",
        "size": "4.0 KiB",
        "type": "dir"
      },
      {
        "filepath": "/home/saurabh/dir3",
        "filename": "dir3",
        "group": "saurabh",
        "is_accessible": true,
        "perm": "-rw-rw-r--",
        "perm_string": "664",
        "size": "4.0 KiB",
        "type": "dir"
      }];

    var files = [{
          "filepath": "/home/saurabh/file1",
          "filename": "file1",
          "group": "saurabh",
          "is_accessible": true,
          "perm": "-rw-rw-r--",
          "perm_string": "664",
          "size": "4.0 KiB",
          "type": "dir"
        }, {
          "filepath": "/home/saurabh/file2",
          "filename": "file2",
          "group": "root",
          "is_accessible": false,
          "perm": "-rw-r--r--",
          "perm_string": "644",
          "size": "4.0 KiB",
          "type": "dir"
        }];

  beforeEach(module('oide'));
  beforeEach(module('oide.editor'));

  beforeEach(inject(function($controller, $rootScope, $log, $document, FiletreeService, $httpBackend){
    scope = $rootScope.$new();
    httpBackend = $httpBackend;
    httpBackend.whenGET('/filebrowser/filetree/a/dir').respond(function(){
      return [200, dirs];
    });
    controller = $controller;
    $filetreeService = FiletreeService;
    controller = $controller('FiletreeCtrl', {
      $scope: scope,
      $document: $document,
      $log: $log,
      FileTreeService: $filetreeService
    });
    scope.ctrl = controller;
    scope.$apply();
  }));

  describe('Whether the filetree is working as expected or not', function(){
    //Expect Filetree service to be defined
    it('Controller initialization should be proper', function(){
      httpBackend.flush();
      expect($filetreeService).toBeDefined();
      expect(scope.ctrl.treeData).toBeDefined();
      expect(scope.ctrl.treeData.filetreeContents).toBeDefined();
      expect(scope.ctrl.treeData.filetreeContents.length).toBe(3);
    });

    it('should return directory contents', function(){
      httpBackend.flush();
      httpBackend.whenGET(/\/filebrowser\/filetree\/a\/dir\?dirpath=.*/).respond(function(){
        return [200, files];
      });
      scope.ctrl.getDirContents(scope.ctrl.treeData.filetreeContents[0]);
      httpBackend.flush();
      // Retrieved files should be set as the childrens object of the 0th node
      expect(scope.ctrl.treeData.filetreeContents[0].children).toBeDefined();
      // Length of the children for the node should be 2
      expect(scope.ctrl.treeData.filetreeContents[0].children.length).toBe(2);
    });

  });

});
<|endoftext|>


<commit_before>var RmodulesView = function () {
    this.droppable_divs = {
        "categorical": ["divGroupByVariable", "divDependentVariable", "divIndependentVariable", "divCategoryVariable", "divCensoringVariable"],
        "numerical": ["divTimeVariable"]
    };
}

RmodulesView.prototype.clear_high_dimensional_input = function (div) {
    //Clear the drag and drop div.
    var qc = Ext.get(div);

    for (var i = qc.dom.childNodes.length - 1; i >= 0; i--) {
        var child = qc.dom.childNodes[i];
        qc.dom.removeChild(child);
    }
    clearHighDimDataSelections(div);
    clearSummaryDisplay(div);
}

RmodulesView.prototype.register_drag_drop = function () {

    /**
     * Register div as drop zone
     * @param divs
     * @private
     */
    var _register_drop_zone = function (divs) {
        for (var i = 0, maxLength = divs.length; i < maxLength; i++) {
            var _el, _dtgI;

            if (_el = Ext.get(divs[i])) {
                _dtgI = new Ext.dd.DropTarget(_el, {ddGroup: 'makeQuery'});
                if (key == 'categorical') {
                    _dtgI.notifyDrop = dropOntoCategorySelection;
                } else if (key == 'numerical') {
                    _dtgI.notifyDrop = dropNumericOntoCategorySelection;
                }
            }
        }
    }

    for (var key in this.droppable_divs) {
        if (this.droppable_divs.hasOwnProperty(key)) {
            _register_drop_zone(this.droppable_divs[key]);
        }
    }
}

RmodulesView.prototype.get_parameters_for_mrna = function (constraints) {

    // TODO : to be filled in with values expected by analysis job in the backend
    constraints['dataConstraints']['gene_signatures'] = null;
    constraints['dataConstraints']['genes'] = null;
    constraints['dataConstraints']['disjunction'] = null;
    constraints['dataConstraints']['pathways'] = null;
    constraints['dataConstraints']['proteins'] = null;
    constraints['dataConstraints']['homologenes'] = null;

    return constraints;
}

RmodulesView.prototype.read_concept_variables = function () {

    var _el;
    var _ontology_terms = [];

    /**
     * get ontology terms
     * @param el
     * @returns {Array}
     * @private
     */
    var _add_ontology_terms = function (el, type) {
        var _type;

        for (var i = 0; i < el.dom.childNodes.length; i++) {

            var _term = getQuerySummaryItem(el.dom.childNodes[i]).trim();

            // map the term type
            switch (type) {
                case 'divDependentVariable':
                    _type = 'dependent';
                    break;
                case 'divIndependentVariable':
                    _type = 'independent';
                    break;
                default :
                    _type = 'default';
                    break;
            }

            _ontology_terms.push({
                'term': _term,
                'options': {'type': _type}
            });
        }
    }

    // register all as drop zone ..

    for (var i = 0; i < this.droppable_divs['categorical'].length; i++) {
        if (_el = Ext.get(this.droppable_divs['categorical'][i])) {
            _add_ontology_terms(_el, this.droppable_divs['categorical'][i]);
        }
    }

    return _ontology_terms;
}

RmodulesView.prototype.get_parameters_for_mirna = function (constraints) {

    // TODO : to be filled in with values expected by analysis job in the backend
    constraints['dataConstraints']['disjunction'] = null;
    constraints['dataConstraints']['mirna'] = null;

    return constraints;
}

RmodulesView.prototype.get_parameters_for_rbm = function (constraints) {

    // TODO : to be filled in with values expected by analysis job in the backend
    constraints['dataConstraints']['genes'] = null;
    constraints['dataConstraints']['disjunction'] = null;
    constraints['dataConstraints']['proteins'] = null;

    return constraints;
}

RmodulesView.prototype.get_analysis_constraints = function (jobType) {

    var _data_type = GLOBAL.HighDimDataType;
    var _returnVal;

    var _this = this;

    // construct constraints object
    var _get_constraints_obj = function () {

        var _ontology_terms = _this.read_concept_variables();

        return  {
            "job_type": jobType,
            "data_type": _data_type,
            "assayConstraints": {
                "patient_set": [GLOBAL.CurrentSubsetIDs[1], GLOBAL.CurrentSubsetIDs[2]],
                "assay_id_list": null,
                "ontology_term": _ontology_terms,
                "trial_name": null
            },
            "dataConstraints": {
                "disjunction": null
            },
            "projections": ["default_real_projection"]
        }
    }
    _returnVal = _get_constraints_obj();

    // do not create search_keyword_ids param if  pathway / gene is not selected
    // when gene / pathway is not selected, analysis will take up all pathways/genes.
    if (GLOBAL.CurrentPathway) {
        _returnVal['dataConstraints']['search_keyword_ids'] = [GLOBAL.CurrentPathway];
    }

    var cases = {
        'Gene Expression': this.get_parameters_for_mrna,
        'MIRNA_QPCR': this.get_parameters_for_mirna,
        'MIRNA_SEQ': this.get_parameters_for_mirna,
        'RBM': this.get_parameters_for_rbm,
        'PROTEOMICS': this.get_parameters_for_rbm,
        'RNASEQ': this.get_parameters_for_mrna
    }

    if (cases[_data_type]) {
        _returnVal = cases[_data_type](_returnVal);
    }

    return _returnVal;

}

RmodulesView.prototype.drop_onto_bin = function (source, e, data) {
    this.el.appendChild(data.ddel);
    return true;
}
<commit_msg>To clean high dimensional params<commit_after>var RmodulesView = function () {
    this.droppable_divs = {
        "categorical": ["divGroupByVariable", "divDependentVariable", "divIndependentVariable", "divCategoryVariable", "divCensoringVariable"],
        "numerical": ["divTimeVariable"]
    };
    this.independent_hidden_divs = ["independentVarDataType", "independentPathway"]
    this.dependent_hidden_divs = ["dependentVarDataType", "dependentPathway"];
    this.group_hidden_divs =["groupByVarDataType", "groupByPathway"]
}

RmodulesView.prototype.clear_high_dimensional_input = function (div) {
    //Clear the drag and drop div.
    var qc = Ext.get(div);

    for (var i = qc.dom.childNodes.length - 1; i >= 0; i--) {
        var child = qc.dom.childNodes[i];
        qc.dom.removeChild(child);
    }
    clearHighDimDataSelections(div);
    clearSummaryDisplay(div);

    var _cleanHiddenDivs = function (divArr) {
        for (var i = 0; i < divArr.length; i++) {
            if ( document.getElementById(divArr[i])) {
                document.getElementById(divArr[i]).value = "";
            }
        }
    }

    if (div == 'divDependentVariable' || div == 'divCategoryVariable') {
        _cleanHiddenDivs(this.dependent_hidden_divs);
    } else if (div == 'divIndependentVariable') {
        _cleanHiddenDivs(this.independent_hidden_divs);
    } else if (div == 'divGroupByVariable') {
        _cleanHiddenDivs(this.group_hidden_divs);
    }
}

RmodulesView.prototype.register_drag_drop = function () {

    /**
     * Register div as drop zone
     * @param divs
     * @private
     */
    var _register_drop_zone = function (divs) {
        for (var i = 0, maxLength = divs.length; i < maxLength; i++) {
            var _el, _dtgI;

            if (_el = Ext.get(divs[i])) {
                _dtgI = new Ext.dd.DropTarget(_el, {ddGroup: 'makeQuery'});
                if (key == 'categorical') {
                    _dtgI.notifyDrop = dropOntoCategorySelection;
                } else if (key == 'numerical') {
                    _dtgI.notifyDrop = dropNumericOntoCategorySelection;
                }
            }
        }
    }

    for (var key in this.droppable_divs) {
        if (this.droppable_divs.hasOwnProperty(key)) {
            _register_drop_zone(this.droppable_divs[key]);
        }
    }
}

RmodulesView.prototype.get_parameters_for_mrna = function (constraints) {

    // TODO : to be filled in with values expected by analysis job in the backend
    constraints['dataConstraints']['gene_signatures'] = null;
    constraints['dataConstraints']['genes'] = null;
    constraints['dataConstraints']['disjunction'] = null;
    constraints['dataConstraints']['pathways'] = null;
    constraints['dataConstraints']['proteins'] = null;
    constraints['dataConstraints']['homologenes'] = null;

    return constraints;
}

RmodulesView.prototype.read_concept_variables = function () {

    var _el;
    var _ontology_terms = [];

    /**
     * get ontology terms
     * @param el
     * @returns {Array}
     * @private
     */
    var _add_ontology_terms = function (el, type) {
        var _type;

        for (var i = 0; i < el.dom.childNodes.length; i++) {

            var _term = getQuerySummaryItem(el.dom.childNodes[i]).trim();

            // map the term type
            switch (type) {
                case 'divDependentVariable':
                    _type = 'dependent';
                    break;
                case 'divIndependentVariable':
                    _type = 'independent';
                    break;
                default :
                    _type = 'default';
                    break;
            }

            _ontology_terms.push({
                'term': _term,
                'options': {'type': _type}
            });
        }
    }

    // register all as drop zone ..

    for (var i = 0; i < this.droppable_divs['categorical'].length; i++) {
        if (_el = Ext.get(this.droppable_divs['categorical'][i])) {
            _add_ontology_terms(_el, this.droppable_divs['categorical'][i]);
        }
    }

    return _ontology_terms;
}

RmodulesView.prototype.get_parameters_for_mirna = function (constraints) {

    // TODO : to be filled in with values expected by analysis job in the backend
    constraints['dataConstraints']['disjunction'] = null;
    constraints['dataConstraints']['mirna'] = null;

    return constraints;
}

RmodulesView.prototype.get_parameters_for_rbm = function (constraints) {

    // TODO : to be filled in with values expected by analysis job in the backend
    constraints['dataConstraints']['genes'] = null;
    constraints['dataConstraints']['disjunction'] = null;
    constraints['dataConstraints']['proteins'] = null;

    return constraints;
}

RmodulesView.prototype.get_analysis_constraints = function (jobType) {

    var _data_type = GLOBAL.HighDimDataType;
    var _returnVal;

    var _this = this;

    // construct constraints object
    var _get_constraints_obj = function () {

        var _ontology_terms = _this.read_concept_variables();

        return  {
            "job_type": jobType,
            "data_type": _data_type,
            "assayConstraints": {
                "patient_set": [GLOBAL.CurrentSubsetIDs[1], GLOBAL.CurrentSubsetIDs[2]],
                "assay_id_list": null,
                "ontology_term": _ontology_terms,
                "trial_name": null
            },
            "dataConstraints": {
                "disjunction": null
            },
            "projections": ["default_real_projection"]
        }
    }
    _returnVal = _get_constraints_obj();

    // do not create search_keyword_ids param if  pathway / gene is not selected
    // when gene / pathway is not selected, analysis will take up all pathways/genes.
    if (GLOBAL.CurrentPathway) {
        _returnVal['dataConstraints']['search_keyword_ids'] = [GLOBAL.CurrentPathway];
    }

    var cases = {
        'Gene Expression': this.get_parameters_for_mrna,
        'MIRNA_QPCR': this.get_parameters_for_mirna,
        'MIRNA_SEQ': this.get_parameters_for_mirna,
        'RBM': this.get_parameters_for_rbm,
        'PROTEOMICS': this.get_parameters_for_rbm,
        'RNASEQ': this.get_parameters_for_mrna
    }

    if (cases[_data_type]) {
        _returnVal = cases[_data_type](_returnVal);
    }

    return _returnVal;

}

RmodulesView.prototype.drop_onto_bin = function (source, e, data) {
    this.el.appendChild(data.ddel);
    return true;
}
<|endoftext|>


<commit_before>/**
 * Visual Blocks Editor
 *
 * Copyright 2011 Google Inc.
 * http://blockly.googlecode.com/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview scroll-blockspace-on-mousewheel interaction handler
 */
'use strict';

goog.provide('Blockly.ScrollOnWheelHandler');

/**
 * @param {!Blockly.BlockSpace} blockSpace
 * @constructor
 */
Blockly.ScrollOnWheelHandler = function (blockSpace) {
  /**
   * @type {Blockly.BlockSpace}
   * @private
   */
  this.blockSpace_ = blockSpace;

  /**
   * @type {BindData}
   * @private
   */
  this.wheelEventBindData_ = null;

  /**
   * (for Safari)
   * @type {BindData}
   * @private
   */
  this.mousewheelEventBindData_ = null;
};

/**
 * Establish a mousewheel handler on the given wheelTarget that will
 * @param {!EventTarget} wheelTarget
 */
Blockly.ScrollOnWheelHandler.prototype.bindTo = function (wheelTarget) {
  this.unbindWheelScrollHandler();

  this.wheelEventBindData_ = Blockly.bindEvent_(wheelTarget,
      'wheel', this, this.onWheel_);

  // Safari uses 'mousewheel'
  this.mousewheelEventBindData_ = Blockly.bindEvent_(
      wheelTarget, 'mousewheel', this, this.onWheel_);
};

/**
 * Unbinds previously bound handler to begin pan-drag.  Safe to call if no
 * such handler is bound.
 */
Blockly.ScrollOnWheelHandler.prototype.unbindWheelScrollHandler = function () {
  if (this.wheelEventBindData_) {
    Blockly.unbindEvent_(this.wheelEventBindData_);
    this.wheelEventBindData_ = null;
  }

  if (this.mousewheelEventBindData_) {
    Blockly.unbindEvent_(this.mousewheelEventBindData_);
    this.mousewheelEventBindData_ = null;
  }
};

/**
 * Scroll the BlockSpace up or down based on wheel scrolling.
 * @param {!Event} e Mouse wheel scroll event.
 * @private
 */
Blockly.ScrollOnWheelHandler.prototype.onWheel_ = function(e) {
  if (!this.blockSpace_.scrollbarPair) {
    return;
  }

  // + is down
  var wheelDelta = Blockly.getNormalizedWheelDeltaY(e);
  if (wheelDelta) {
    this.blockSpace_.scrollWithAnySelectedBlock(
      this.blockSpace_.getScrollOffsetX(),
      this.blockSpace_.getScrollOffsetY() + wheelDelta,
      e.clientX, e.clientY);

    // Don't scroll the page.
    e.stopPropagation();
    e.preventDefault();
  }
};
<commit_msg>Capitalization, change @type @privates to @private [ci skip]<commit_after>/**
 * Visual Blocks Editor
 *
 * Copyright 2011 Google Inc.
 * http://blockly.googlecode.com/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Scroll-BlockSpace-on-mousewheel interaction handler.
 */
'use strict';

goog.provide('Blockly.ScrollOnWheelHandler');

/**
 * @param {!Blockly.BlockSpace} blockSpace
 * @constructor
 */
Blockly.ScrollOnWheelHandler = function (blockSpace) {
  /**
   * @private {Blockly.BlockSpace}
   */
  this.blockSpace_ = blockSpace;

  /**
   * @private {BindData}
   */
  this.wheelEventBindData_ = null;

  /**
   * (for Safari)
   * @private {BindData}
   */
  this.mousewheelEventBindData_ = null;
};

/**
 * Establish a mousewheel handler on the given wheelTarget that will
 * @param {!EventTarget} wheelTarget
 */
Blockly.ScrollOnWheelHandler.prototype.bindTo = function (wheelTarget) {
  this.unbindWheelScrollHandler();

  this.wheelEventBindData_ = Blockly.bindEvent_(wheelTarget,
      'wheel', this, this.onWheel_);

  // Safari uses 'mousewheel'
  this.mousewheelEventBindData_ = Blockly.bindEvent_(
      wheelTarget, 'mousewheel', this, this.onWheel_);
};

/**
 * Unbinds previously bound handler to begin pan-drag.  Safe to call if no
 * such handler is bound.
 */
Blockly.ScrollOnWheelHandler.prototype.unbindWheelScrollHandler = function () {
  if (this.wheelEventBindData_) {
    Blockly.unbindEvent_(this.wheelEventBindData_);
    this.wheelEventBindData_ = null;
  }

  if (this.mousewheelEventBindData_) {
    Blockly.unbindEvent_(this.mousewheelEventBindData_);
    this.mousewheelEventBindData_ = null;
  }
};

/**
 * Scroll the BlockSpace up or down based on wheel scrolling.
 * @param {!Event} e Mouse wheel scroll event.
 * @private
 */
Blockly.ScrollOnWheelHandler.prototype.onWheel_ = function(e) {
  if (!this.blockSpace_.scrollbarPair) {
    return;
  }

  // + is down
  var wheelDelta = Blockly.getNormalizedWheelDeltaY(e);
  if (wheelDelta) {
    this.blockSpace_.scrollWithAnySelectedBlock(
      this.blockSpace_.getScrollOffsetX(),
      this.blockSpace_.getScrollOffsetY() + wheelDelta,
      e.clientX, e.clientY);

    // Don't scroll the page.
    e.stopPropagation();
    e.preventDefault();
  }
};
<|endoftext|>


<commit_before>require([
	'lib/V',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/shapes/Box',
	'goo/math/Vector3',
	'goo/math/Quaternion',
	'goo/math/MathUtils',
	'goo/renderer/MeshData',
	'goo/geometrypack/Surface',
	'goo/renderer/Camera',
	'goo/entities/components/MeshDataComponent',
	'goo/entities/components/MeshRendererComponent',
	'goo/renderer/TextureCreator',

	'goo/animationpack/components/AnimationComponent',
	'goo/animationpack/SkeletonPose',
	'goo/animationpack/Skeleton',
	'goo/animationpack/Joint',
	'goo/animationpack/state/SteadyState',
	'goo/animationpack/blendtree/ClipSource',
	'goo/animationpack/clip/AnimationClip',
	'goo/animationpack/clip/JointChannel',
	'goo/animationpack/clip/AbstractAnimationChannel',
	'goo/animationpack/systems/AnimationSystem'

], function (
	V,
	Material,
	ShaderLib,
	Box,
	Vector3,
	Quaternion,
	MathUtils,
	MeshData,
	Surface,
	Camera,
	MeshDataComponent,
	MeshRendererComponent,
	TextureCreator,

	AnimationComponent,
	SkeletonPose,
	Skeleton,
	Joint,
	SteadyState,
	ClipSource,
	AnimationClip,
	JointChannel,
	AbstractAnimationChannel,
	AnimationSystem
) {
	'use strict';

	V.describe('Origami Animation Test');

	function addSkeltonAttributeData(meshData, joints) {

		var skeletonMaps = MeshData.defaultMap([MeshData.JOINTIDS, MeshData.WEIGHTS]);
		meshData.attributeMap[MeshData.JOINTIDS] = skeletonMaps[MeshData.JOINTIDS];
		meshData.attributeMap[MeshData.WEIGHTS] = skeletonMaps[MeshData.WEIGHTS];
		// rebuildData generates dataviews on the new attributes.
		meshData.rebuildData(meshData.vertexCount, meshData.indexCount, true);
		// These are probably used somewhere.
		meshData.weightsPerVertex = 4; // Default weights count
		meshData.type = MeshData.SKINMESH;

		// Just map 1to1,
		meshData.paletteMap = [];
		for (var i =0; i < joints.length; i++) {
			meshData.paletteMap[i] = i;
		}

	}

	function getInvT(joint, joints, tArray) {

		if (joint._parentIndex != Joint.NO_PARENT) {
			var parentJoint = joints[joint._parentIndex];
			var invT = parentJoint._inverseBindPose.translation.data;
			tArray[0] -= invT[0];
			tArray[1] -= invT[1];
			tArray[2] -= invT[2];
			getInvT(parentJoint, joints, tArray);
		}

		return tArray;
	}

	function createJointChannel(joint, joints, times, t, r, s, blendType, channels) {

		// The channel's transform keyframes needs to be cobined with the joint's
		// inverse bind pose, it uses the offset from it to create the resulting transform

		// TODO : Rotation and scale.
		var invT = joint._inverseBindPose.translation.data;
		getInvT(joint, joints, invT);

		var translation = [];

		for (var i = 0; i < t.length; i+=3) {
			translation[i] = -invT[0] + t[i];
			translation[i+1] = -invT[1] + t[i+1];
			translation[i+2] = -invT[2] + t[i+2];
		}

		var channel = new JointChannel(
			joint._index,
			joint._name,
			times,
			r,
			translation,
			s,
			blendType
		);

		channels.push(channel);

		return channel
	}

	function setJointBindPose(joint, T, R) {

		var trans = joint._inverseBindPose;
		trans.setIdentity();

		if (T) {
			trans.translation.setDirect(T[0], T[1], T[2]);
		}

		if (R) {
			trans.setRotationXYZ(R[0], R[1], R[2]);
		}

		var it = trans.invert();
		it.update();
		joint._inverseBindPose = it;
	}

	function createNewJoint(jointName, jointIndex, parentJoint, joints, bindPosition) {

		var joint = new Joint(jointName);
		joint._index = jointIndex;
		if (parentJoint) {
			joint._parentIndex = parentJoint._index;
		} else {
			joint._parentIndex = Joint.NO_PARENT;
		}

		if (bindPosition) {
			setJointBindPose(joint, bindPosition);
		}

		joints.push(joint);

		return joint;
	}

	function smoothWeights(d, bleedD, weightData, quadIndex) {
		var b = MathUtils.clamp( d / bleedD, 0, 1);
		var w = MathUtils.scurve5(b);
		weightData[quadIndex] = w;
		weightData[quadIndex + 1] = 1.0 - w;
	}

	function loopSetJoints(joint, vertIndexArray, jointData) {
		var quadIndex;
		for (var i = 0; i < vertIndexArray.length; i++) {
			quadIndex = vertIndexArray[i] * 4;
			jointData[quadIndex] = joint._index;
			jointData[quadIndex + 1] = joint._parentIndex;
		}
	}

	/*
	* Adds AnimationComponent, MeshDataComponent, MeshRendererComponent to
	* an "empty" entity,
	*/
	function addFoldingPaper(entity, vertCount, diffuse, loopCount, timeScale) {

		if (entity.getComponent('AnimationComponent') || entity.getComponent('MeshDataComponent') || entity.getComponent('MeshRendererComponent')) {
			throw Error('The entity cannot have any prior animation- or meshdata/renderer- components');
		}

		var size = 1;

		var joints = [];

		// Create skeleton joint hierarchy
		var rootJoint = createNewJoint('RootJoint', 0, null, joints, [0, 0, 0]);

		var midJoint = createNewJoint('mid', 1, rootJoint, joints, [0, 0.5, 0]);

		var skeleton = new Skeleton('PaperSkeleton', joints);
		var skeletonPose = new SkeletonPose(skeleton);
		var animComp = new AnimationComponent(skeletonPose);

		var times = [0, 0.5, 1.2];
		var rots = [];
		var q1 = new Quaternion();
		var q2 = new Quaternion();
		q1.fromAngleNormalAxis(-0.05, new Vector3(1,0,0).normalize());
		q2.fromAngleNormalAxis(-MathUtils.HALF_PI, new Vector3(1,0,0).normalize());
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q1.data);
		Array.prototype.push.apply(rots, q1.data);

		var trans = [
			0,0,0,
			0,0,0,
			0,0,0,
		];

		var scales = [
			1,1,1,
			1,1,1,
			1,1,1,
		];

		var animChannels = [];

		var rootChannel = createJointChannel(
			rootJoint,
			joints,
			times,
			trans,
			rots,
			scales,
			AbstractAnimationChannel.BLENDTYPES.QUINTIC ||'SCurve5',
			animChannels
		);

		rots = [];
		q2.fromAngleNormalAxis(-Math.PI * 0.98, new Vector3(1,0,0).normalize());
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q1.data);
		var midChannel = createJointChannel(
			midJoint,
			joints,
			times,
			trans,
			rots,
			scales,
			AbstractAnimationChannel.BLENDTYPES.QUINTIC ||'SCurve5',
			animChannels
		);

		var clip = new AnimationClip('My animation Clip', animChannels);
		var clipSource = new ClipSource(clip);
		clipSource._clipInstance._loopCount = loopCount;  // -1 for looping infinetly
		clipSource.setTimeScale(timeScale);
		var animState = new SteadyState('My animation state');
		animState.setClipSource(clipSource);
		var animLayer = animComp.layers[0];  // Default animation layer
		animLayer.setState('RootRotateState', animState);
		animLayer.setCurrentState(animState, true);

		var bleedD = 0.0;
		var meshData = Surface.createTessellatedFlat(size, size, vertCount, vertCount);

		addSkeltonAttributeData(meshData, joints);

		var weightData = meshData.dataViews.WEIGHTS;
		for (var i = 0; i < weightData.length; i+=4) {
			weightData[i] = 1;
			weightData[i+1] = 0;
			weightData[i+2] = 0;
			weightData[i+3] = 0;
		}

		var midVerts = [];
		var positions = meshData.dataViews.POSITION;
		var posLen = positions.length;
		for (var i = 0; i < posLen; i+=3) {
			var x = positions[i];
			// Translate up to set mesh origin at entity's transform
			positions[i+1] += 0.5;
			var y = positions[i+1];

			var vertIndex = i/3;
			var quadIndex = vertIndex * 4;

			if (y > 0.5) {
				midVerts.push(vertIndex);
				smoothWeights(y, bleedD, weightData, quadIndex);
			}

		}

		var jointData = meshData.dataViews.JOINTIDS;

		loopSetJoints(midJoint, midVerts, jointData);

		var material = new Material(ShaderLib.uber);
		material.uniforms.materialDiffuse = diffuse;
		material.cullState.enabled = false;
		new TextureCreator().loadTexture2D('../../resources/check.png').then(function (texture) {
			material.setTexture('DIFFUSE_MAP', texture);
		});

		entity.setComponent(new MeshDataComponent(meshData));
		entity.setComponent(new MeshRendererComponent(material));

		entity.setComponent(animComp);
		entity.meshDataComponent.currentPose = entity.animationComponent._skeletonPose;
		return entity;
	}

	function init() {

		var goo = V.initGoo();
		goo._addDebugKeys();
		var world = goo.world;

		// The animationsystem calls the animation components, updating
		// the animation data every frame.
		var animSystem = new AnimationSystem();
		//animSystem.stop();
		world.setSystem(animSystem);

		paperEntity = world.createEntity().addToWorld();
		var color = [0.4, 0.8, 0.4, 1];
		var loopCount = -1;
		var timeScale = 1;
		var vertCount = 50;
		var paperEntity = addFoldingPaper(paperEntity, vertCount, color, loopCount, timeScale);
		var scale = 8;
		paperEntity.transformComponent.setScale(scale, scale, scale);

		var animT = 0;
		var tstep = 0.01;
		window.addEventListener('keydown', function(event) {
			switch (event.keyCode) {
				case 37:
					animT -= tstep;
					break;
				case 39:
					animT += tstep;
					break;
				case 40:
					animT = 0;
			}

			// If the animstate is updated to equal maxtime, the
			// animation loops to first keyframe
			animT = MathUtils.clamp(animT, 0, 0.999999);

			var animationComponent = paperEntity.animationComponent;
			var layer = animationComponent.layers[0];
			var animState = layer._currentState;
			var clipSource = animState._sourceTree;

			var maxTime = clipSource._clip._maxTime;
			var timeScale = clipSource._clipInstance._timeScale;
			var t = (animT * maxTime) / timeScale;
			animState.update(t);
			animationComponent.apply(paperEntity.transformComponent);
			animationComponent.postUpdate();
		});

		var meshData = Surface.createTessellatedFlat(1, 1, vertCount, vertCount);
		var material = new Material(ShaderLib.uber);
		material.cullState.enabled = false;
		new TextureCreator().loadTexture2D('../../resources/check.png').then(function (texture) {
			material.setTexture('DIFFUSE_MAP', texture);
		});

		world.createEntity(meshData, material, [5, 0, 0]).addToWorld();

		V.addLights();

		V.addOrbitCamera(new Vector3(15, Math.PI / 2, 0.3));
		//world.createEntity(new Camera(), [0, 1, 15]).addToWorld().lookAt([0, 0, 0]);

		V.process();
	}

	init();
});
<commit_msg>Changed according to new surface fixes.<commit_after>require([
	'lib/V',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/shapes/Box',
	'goo/math/Vector3',
	'goo/math/Quaternion',
	'goo/math/MathUtils',
	'goo/renderer/MeshData',
	'goo/geometrypack/Surface',
	'goo/renderer/Camera',
	'goo/entities/components/MeshDataComponent',
	'goo/entities/components/MeshRendererComponent',
	'goo/renderer/TextureCreator',

	'goo/animationpack/components/AnimationComponent',
	'goo/animationpack/SkeletonPose',
	'goo/animationpack/Skeleton',
	'goo/animationpack/Joint',
	'goo/animationpack/state/SteadyState',
	'goo/animationpack/blendtree/ClipSource',
	'goo/animationpack/clip/AnimationClip',
	'goo/animationpack/clip/JointChannel',
	'goo/animationpack/clip/AbstractAnimationChannel',
	'goo/animationpack/systems/AnimationSystem'

], function (
	V,
	Material,
	ShaderLib,
	Box,
	Vector3,
	Quaternion,
	MathUtils,
	MeshData,
	Surface,
	Camera,
	MeshDataComponent,
	MeshRendererComponent,
	TextureCreator,

	AnimationComponent,
	SkeletonPose,
	Skeleton,
	Joint,
	SteadyState,
	ClipSource,
	AnimationClip,
	JointChannel,
	AbstractAnimationChannel,
	AnimationSystem
) {
	'use strict';

	V.describe('Origami Animation Test');

	function addSkeltonAttributeData(meshData, joints) {

		var skeletonMaps = MeshData.defaultMap([MeshData.JOINTIDS, MeshData.WEIGHTS]);
		meshData.attributeMap[MeshData.JOINTIDS] = skeletonMaps[MeshData.JOINTIDS];
		meshData.attributeMap[MeshData.WEIGHTS] = skeletonMaps[MeshData.WEIGHTS];
		// rebuildData generates dataviews on the new attributes.
		meshData.rebuildData(meshData.vertexCount, meshData.indexCount, true);
		// These are probably used somewhere.
		meshData.weightsPerVertex = 4; // Default weights count
		meshData.type = MeshData.SKINMESH;

		// Just map 1to1,
		meshData.paletteMap = [];
		for (var i =0; i < joints.length; i++) {
			meshData.paletteMap[i] = i;
		}

	}

	function getInvT(joint, joints, tArray) {

		if (joint._parentIndex != Joint.NO_PARENT) {
			var parentJoint = joints[joint._parentIndex];
			var invT = parentJoint._inverseBindPose.translation.data;
			tArray[0] -= invT[0];
			tArray[1] -= invT[1];
			tArray[2] -= invT[2];
			getInvT(parentJoint, joints, tArray);
		}

		return tArray;
	}

	function createJointChannel(joint, joints, times, t, r, s, blendType, channels) {

		// The channel's transform keyframes needs to be cobined with the joint's
		// inverse bind pose, it uses the offset from it to create the resulting transform

		// TODO : Rotation and scale.
		var invT = joint._inverseBindPose.translation.data;
		getInvT(joint, joints, invT);

		var translation = [];

		for (var i = 0; i < t.length; i+=3) {
			translation[i] = -invT[0] + t[i];
			translation[i+1] = -invT[1] + t[i+1];
			translation[i+2] = -invT[2] + t[i+2];
		}

		var channel = new JointChannel(
			joint._index,
			joint._name,
			times,
			r,
			translation,
			s,
			blendType
		);

		channels.push(channel);

		return channel
	}

	function setJointBindPose(joint, T, R) {

		var trans = joint._inverseBindPose;
		trans.setIdentity();

		if (T) {
			trans.translation.setDirect(T[0], T[1], T[2]);
		}

		if (R) {
			trans.setRotationXYZ(R[0], R[1], R[2]);
		}

		var it = trans.invert();
		it.update();
		joint._inverseBindPose = it;
	}

	function createNewJoint(jointName, jointIndex, parentJoint, joints, bindPosition) {

		var joint = new Joint(jointName);
		joint._index = jointIndex;
		if (parentJoint) {
			joint._parentIndex = parentJoint._index;
		} else {
			joint._parentIndex = Joint.NO_PARENT;
		}

		if (bindPosition) {
			setJointBindPose(joint, bindPosition);
		}

		joints.push(joint);

		return joint;
	}

	function smoothWeights(d, bleedD, weightData, quadIndex) {
		var b = MathUtils.clamp( d / bleedD, 0, 1);
		var w = MathUtils.scurve5(b);
		weightData[quadIndex] = w;
		weightData[quadIndex + 1] = 1.0 - w;
	}

	function loopSetJoints(joint, vertIndexArray, jointData) {
		var quadIndex;
		for (var i = 0; i < vertIndexArray.length; i++) {
			quadIndex = vertIndexArray[i] * 4;
			jointData[quadIndex] = joint._index;
			jointData[quadIndex + 1] = joint._parentIndex;
		}
	}

	/*
	* Adds AnimationComponent, MeshDataComponent, MeshRendererComponent to
	* an "empty" entity,
	*/
	function addFoldingPaper(entity, vertCount, diffuse, loopCount, timeScale) {

		if (entity.getComponent('AnimationComponent') || entity.getComponent('MeshDataComponent') || entity.getComponent('MeshRendererComponent')) {
			throw Error('The entity cannot have any prior animation- or meshdata/renderer- components');
		}

		var size = 1;

		var joints = [];

		// Create skeleton joint hierarchy
		var rootJoint = createNewJoint('RootJoint', 0, null, joints, [0, 0, 0]);

		var midJoint = createNewJoint('mid', 1, rootJoint, joints, [0, 0, -0.5]);

		var skeleton = new Skeleton('PaperSkeleton', joints);
		var skeletonPose = new SkeletonPose(skeleton);
		var animComp = new AnimationComponent(skeletonPose);

		var times = [0, 0.5, 1.2];
		var rots = [];
		var q1 = new Quaternion();
		var q2 = new Quaternion();
		q1.fromAngleNormalAxis(MathUtils.HALF_PI * 0.95, new Vector3(1,0,0).normalize());
		q2.fromAngleNormalAxis(0.04, new Vector3(1,0,0).normalize());
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q1.data);
		Array.prototype.push.apply(rots, q1.data);

		var trans = [
			0,0,0,
			0,0,0,
			0,0,0,
		];

		var scales = [
			1,1,1,
			1,1,1,
			1,1,1,
		];

		var animChannels = [];

		var rootChannel = createJointChannel(
			rootJoint,
			joints,
			times,
			trans,
			rots,
			scales,
			AbstractAnimationChannel.BLENDTYPES.QUINTIC ||'SCurve5',
			animChannels
		);

		rots = [];
		q1.fromAngleNormalAxis(-0.05, new Vector3(1,0,0).normalize());
		q2.fromAngleNormalAxis(-Math.PI * 0.98, new Vector3(1,0,0).normalize());
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q1.data);
		var midChannel = createJointChannel(
			midJoint,
			joints,
			times,
			trans,
			rots,
			scales,
			AbstractAnimationChannel.BLENDTYPES.QUINTIC ||'SCurve5',
			animChannels
		);

		var clip = new AnimationClip('My animation Clip', animChannels);
		var clipSource = new ClipSource(clip);
		clipSource._clipInstance._loopCount = loopCount;  // -1 for looping infinetly
		clipSource.setTimeScale(timeScale);
		var animState = new SteadyState('My animation state');
		animState.setClipSource(clipSource);
		var animLayer = animComp.layers[0];  // Default animation layer
		animLayer.setState('RootRotateState', animState);
		animLayer.setCurrentState(animState, true);

		var bleedD = 0.0;
		var meshData = Surface.createTessellatedFlat(size, size, vertCount, vertCount);

		addSkeltonAttributeData(meshData, joints);

		var weightData = meshData.dataViews.WEIGHTS;
		for (var i = 0; i < weightData.length; i+=4) {
			weightData[i] = 1;
			weightData[i+1] = 0;
			weightData[i+2] = 0;
			weightData[i+3] = 0;
		}

		var midVerts = [];
		var positions = meshData.dataViews.POSITION;
		var posLen = positions.length;
		for (var i = 0; i < posLen; i+=3) {
			var x = positions[i];
			// Translate up to set mesh origin at entity's transform
			positions[i+2] -= 0.5;
			var z = positions[i+2];

			var vertIndex = i/3;
			var quadIndex = vertIndex * 4;

			if (z < -0.5) {
				midVerts.push(vertIndex);
				smoothWeights(-z, bleedD, weightData, quadIndex);
			}

		}

		var jointData = meshData.dataViews.JOINTIDS;

		loopSetJoints(midJoint, midVerts, jointData);

		var material = new Material(ShaderLib.uber);
		material.uniforms.materialDiffuse = diffuse;
		material.cullState.enabled = false;
		new TextureCreator().loadTexture2D('../../resources/check.png').then(function (texture) {
			material.setTexture('DIFFUSE_MAP', texture);
		});

		entity.setComponent(new MeshDataComponent(meshData));
		entity.setComponent(new MeshRendererComponent(material));

		entity.setComponent(animComp);
		entity.meshDataComponent.currentPose = entity.animationComponent._skeletonPose;
		return entity;
	}

	function init() {

		var goo = V.initGoo();
		goo._addDebugKeys();
		var world = goo.world;

		// The animationsystem calls the animation components, updating
		// the animation data every frame.
		var animSystem = new AnimationSystem();
		animSystem.stop();
		world.setSystem(animSystem);

		paperEntity = world.createEntity().addToWorld();
		var color = [1, 1, 1, 1];
		var loopCount = -1;
		var timeScale = 1;
		var vertCount = 50;
		var paperEntity = addFoldingPaper(paperEntity, vertCount, color, loopCount, timeScale);
		var scale = 8;
		paperEntity.transformComponent.setScale(scale, scale, scale);

		var animT = 0;
		var tstep = 0.01;
		window.addEventListener('keydown', function(event) {
			switch (event.keyCode) {
				case 37:
					animT -= tstep;
					break;
				case 39:
					animT += tstep;
					break;
				case 40:
					animT = 0;
			}

			// If the animstate is updated to equal maxtime, the
			// animation loops to first keyframe
			animT = MathUtils.clamp(animT, 0, 0.999999);

			var animationComponent = paperEntity.animationComponent;
			var layer = animationComponent.layers[0];
			var animState = layer._currentState;
			var clipSource = animState._sourceTree;

			var maxTime = clipSource._clip._maxTime;
			var timeScale = clipSource._clipInstance._timeScale;
			var t = (animT * maxTime) / timeScale;
			animState.update(t);
			animationComponent.apply(paperEntity.transformComponent);
			animationComponent.postUpdate();
		});

		V.addLights();

		V.addOrbitCamera(new Vector3(25, Math.PI / 2, 1));
		//world.createEntity(new Camera(), [0, 1, 15]).addToWorld().lookAt([0, 0, 0]);

		V.process();
	}

	init();
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import moment from 'moment';

import CalendarDay from './day';

export default class Calendar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selected: this.props.selected,
      startDay: moment().format(),
      visibleMonths: this.props.visibleMonths
    };
  }

  onDaySelect = (date) => {
    this.setState({ selected: date }, () => {
      if (this.state.selected) {
        this.props.onSelect(date);
      }
    });
  };

  getDaysForMonth(date) {
    const days = [];
    const monthStart = date.startOf('month');
    const diff = monthStart.weekday();

    for (let i = 1; i < diff; i++) {
      const day = moment(monthStart.format()).subtract(i, 'days');
      days.push({ day, className: 'prev-month', disabled: true });
    }

    const numberOfDays = date.daysInMonth();

    for (let i = 1; i <= numberOfDays; i++) {
      const day = moment([date.year(), date.month(), i]);
      let disabled = false;

      if (this.props.minDate) {
        disabled = day.isBefore(this.props.minDate);
      }

      if (this.props.maxDate) {
        disabled = day.isAfter(this.props.maxDate);
      }

      if (this.props.minDate && this.props.maxDate) {
        disabled = !day.isBetween(this.props.minDate, this.props.maxDate);
      }

      days.push({ day, disabled, className: 'current-month' });
    }

    let i = 1;
    while (days.length % 7 !== 0) {
      const day = moment(date.endOf('month').format()).add(i, 'days');
      days.push({ day, className: 'disabled next-month', disabled: true });
      i++;
    }

    return days;
  }

  getMonths() {
    const months = [];
    const startDay = moment(this.state.startDay);

    months.push({
      date: startDay,
      days: this.getDaysForMonth(startDay)
    });

    if (this.props.visibleMonths) {
      for (let i = 1; i < this.props.visibleMonths; i++) {
        const nextMonth = moment(startDay.format()).add(i, 'months');

        months.push({
          date: nextMonth,
          days: this.getDaysForMonth(nextMonth)
        });
      }
    }

    return months;
  }

  daysOfWeek() {
    const daysOfWeek = [];

    for (let i = 1; i < 8; i++) {
      daysOfWeek.push(moment().weekday(i).format('dd'));
    }

    return daysOfWeek;
  }

  switchMonth(i) {
    const interval = i * parseInt(this.props.visibleMonths, 10);
    const startDay = moment(this.state.startDay).add(interval, 'months');
    this.setState({ startDay: startDay.format(this.props.dateFormat) }, () => {
      if (this.props.onMonthChange) {
        this.props.onMonthChange(startDay.month() + 1);
      }
    });
  }

  showPrevMonth = () => {
    this.switchMonth(-1);
  };

  showNextMonth = () => {
    this.switchMonth(1);
  };

  renderDay = (date, i) => {
    const key = date.day.format(this.props.dateFormat);

    const options = {
      className: date.className,
      disabled: date.disabled
    };

    const isSelected = date.day.isSame(this.state.selected);

    if (this.props.days[key]) {
      const day = this.props.days[key];
      options.className += day.className || '';
      options.event = day.event || null;

      if (day.hasOwnProperty('disabled')) {
        options.disabled = day.disabled;
      }
    }

    return (
      <CalendarDay
        date={date.day}
        selected={isSelected}
        format={this.props.dayFormat}
        returnFormat={this.props.dateFormat}
        options={options}
        key={i}
        onClick={this.onDaySelect}
      />
    );
  };

  renderWeekDay(date, i) {
    let className = 'calendar-day week-day';
    if (i === 0) className += ' left-border';

    return (

        {date}

    );
  }

  renderMonth = (month, i) => {
    let width = `${98 / this.props.monthsInRow}%`;
    let marginLeft = 0;

    if (this.props.monthsInRow === 3) {
      marginLeft = (i % this.props.monthsInRow > 0) ? '1%' : 0;
    }

    if (this.props.monthsInRow === 2) {
      marginLeft = (i % this.props.monthsInRow > 0) ? '2%' : 0;
    }

    if (this.props.visibleMonths === 1 || this.props.monthsInRow === 1) {
      width = '100%';
    }

    const styles = {
      width,
      marginLeft
    };

    let className = `month month-${this.props.monthsInRow}`;

    if (i % this.monthsInRow > 0) {
      className += ' with-margin';
    }

    return (

{month.date.format('MMMM YYYY')}

        {this.daysOfWeek().map(this.renderWeekDay)}
        {month.days.map(this.renderDay)}

    );
  };

  renderControls() {
    return (

          {this.props.leftArrow}

          {this.props.rightArrow}

    );
  }

  render() {
    return (

        {this.renderControls()}
        {this.getMonths().map(this.renderMonth)}

    );
  }
}

Calendar.propTypes = {
  selected: PropTypes.string,
  dateFormat: PropTypes.string,
  dayFormat: PropTypes.string,
  minDate: PropTypes.string,
  maxDate: PropTypes.string,
  days: PropTypes.object,
  visibleMonths: PropTypes.number,
  monthsInRow: React.PropTypes.oneOf([1, 2, 3]),
  leftArrow: PropTypes.node,
  rightArrow: PropTypes.node,
  onSelect: PropTypes.func,
  onMonthChange: PropTypes.func
};

Calendar.defaultProps = {
  selected: moment().format('YYYY-MM-DD'),
  dateFormat: 'YYYY-MM-DD',
  dayFormat: 'D',
  minDate: '2016-01-15',
  visibleMonths: 12,
  monthsInRow: 3,
  days: {
    '2016-01-29': {
      disabled: true,
      event: {
        className: 'event-2',
        text: 2
      }
    }
  },
  onSelect: (date) => { console.log(date); },
  onMonthChange: (date) => { console.log(date); },
  leftArrow: ,
  rightArrow:
};
<commit_msg>Update calendar skeleton<commit_after>import React, { Component, PropTypes } from 'react';
import moment from 'moment';

import CalendarDay from './day';

export default class Calendar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selected: this.getSelectedDay(),
      startDay: this.getFirstDisplayDate(),
      visibleMonths: this.props.visibleMonths
    };
  }

  onDaySelect = (date) => {
    this.setState({ selected: date }, () => {
      if (this.state.selected) {
        this.props.onSelect(date);
      }
    });
  };

  getSelectedDay() {
    if (this.props.minDate && moment(this.props.minDate).isAfter(this.props.selected)) {
      return moment(this.props.minDate).format();
    }

    return this.props.selected;
  }

  getFirstDisplayDate() {
    const today = moment();

    if (this.props.mode === 'YEAR_VIEW') {
      const i = today.month();
      const january = today.subtract(i, 'months');
      return moment(january.format());
    }

    return today.format();
  }

  getDaysForMonth(date) {
    const days = [];
    const monthStart = date.startOf('month');
    const diff = monthStart.weekday();

    for (let i = 1; i < diff; i++) {
      const day = moment(monthStart.format()).subtract(i, 'days');
      days.push({ day, className: 'prev-month', disabled: true });
    }

    const numberOfDays = date.daysInMonth();

    for (let i = 1; i <= numberOfDays; i++) {
      const day = moment([date.year(), date.month(), i]);
      let disabled = false;

      if (this.props.minDate) {
        disabled = day.isBefore(this.props.minDate);
      }

      if (this.props.maxDate) {
        disabled = day.isAfter(this.props.maxDate);
      }

      if (this.props.minDate && this.props.maxDate) {
        disabled = !day.isBetween(this.props.minDate, this.props.maxDate);
      }

      days.push({ day, disabled, className: 'current-month' });
    }

    let i = 1;
    while (days.length % 7 !== 0) {
      const day = moment(date.endOf('month').format()).add(i, 'days');
      days.push({ day, className: 'disabled next-month', disabled: true });
      i++;
    }

    return days;
  }

  getMonths() {
    const months = [];
    const startDay = moment(this.state.startDay);

    months.push({
      date: startDay,
      days: this.getDaysForMonth(startDay)
    });

    if (this.props.visibleMonths) {
      for (let i = 1; i < this.props.visibleMonths; i++) {
        const nextMonth = moment(startDay.format()).add(i, 'months');

        months.push({
          date: nextMonth,
          days: this.getDaysForMonth(nextMonth)
        });
      }
    }

    return months;
  }

  daysOfWeek() {
    const daysOfWeek = [];

    for (let i = 1; i < 8; i++) {
      daysOfWeek.push(moment().weekday(i).format('dd'));
    }

    return daysOfWeek;
  }

  switchMonth(i) {
    const interval = i * parseInt(this.props.visibleMonths, 10);
    const startDay = moment(this.state.startDay).add(interval, 'months');
    this.setState({ startDay: startDay.format(this.props.dateFormat) }, () => {
      if (this.props.onMonthChange) {
        this.props.onMonthChange(startDay.month() + 1);
      }
    });
  }

  showPrevMonth = () => {
    this.switchMonth(-1);
  };

  showNextMonth = () => {
    this.switchMonth(1);
  };

  renderDay = (date, i) => {
    const key = date.day.format(this.props.dateFormat);

    const options = {
      className: date.className,
      disabled: date.disabled
    };

    const isSelected = date.day.isSame(this.state.selected);

    if (this.props.days[key]) {
      const day = this.props.days[key];
      options.className += day.className || '';
      options.event = day.event || null;

      if (day.hasOwnProperty('disabled')) {
        options.disabled = day.disabled;
      }
    }

    return (
      <CalendarDay
        date={date.day}
        selected={isSelected}
        format={this.props.dayFormat}
        returnFormat={this.props.dateFormat}
        options={options}
        key={i}
        onClick={this.onDaySelect}
      />
    );
  };

  renderWeekDay(date, i) {
    let className = 'calendar-day week-day';
    if (i === 0) className += ' left-border';

    return (

        {date}

    );
  }

  renderMonth = (month, i) => {
    let width = `${98 / this.props.monthsInRow}%`;
    let marginLeft = 0;

    if (this.props.monthsInRow === 3) {
      marginLeft = (i % this.props.monthsInRow > 0) ? '1%' : 0;
    }

    if (this.props.monthsInRow === 2) {
      marginLeft = (i % this.props.monthsInRow > 0) ? '2%' : 0;
    }

    if (this.props.visibleMonths === 1 || this.props.monthsInRow === 1) {
      width = '100%';
    }

    const styles = {
      width,
      marginLeft
    };

    let className = `month month-${this.props.monthsInRow}`;

    if (i % this.monthsInRow > 0) {
      className += ' with-margin';
    }

    return (

{month.date.format('MMMM YYYY')}

        {this.daysOfWeek().map(this.renderWeekDay)}
        {month.days.map(this.renderDay)}

    );
  };

  renderControls() {
    return (

          {this.props.leftArrow}

          {this.props.rightArrow}

    );
  }

  render() {
    return (

        {this.renderControls()}
        {this.getMonths().map(this.renderMonth)}

    );
  }
}

Calendar.propTypes = {
  selected: PropTypes.string,
  dateFormat: PropTypes.string,
  dayFormat: PropTypes.string,
  minDate: PropTypes.string,
  maxDate: PropTypes.string,
  days: PropTypes.object,
  visibleMonths: PropTypes.number,
  monthsInRow: React.PropTypes.oneOf([1, 2, 3]),
  leftArrow: PropTypes.node,
  rightArrow: PropTypes.node,
  onSelect: PropTypes.func,
  onMonthChange: PropTypes.func,
  mode: PropTypes.oneOf([null, 'YEAR_VIEW'])
};

Calendar.defaultProps = {
  selected: moment().format('YYYY-MM-DD'),
  dateFormat: 'YYYY-MM-DD',
  dayFormat: 'D',
  minDate: moment().add(1, 'days').format('YYYY-MM-DD'),
  visibleMonths: 12,
  monthsInRow: 3,
  mode: 'WEEK_VIEW',
  days: {
    '2016-01-29': {
      disabled: true,
      event: {
        className: 'event-2',
        text: 2
      }
    }
  },
  onSelect: (date) => { console.log(date); },
  onMonthChange: (date) => { console.log(date); },
  leftArrow: ,
  rightArrow:
};
<|endoftext|>