<commit_before>var test = require('tap').test;
var tokenize = require('../../lib/tokenize');

test('spec', function (t) {
    t.type(tokenize, 'function');
    t.type(tokenize('foo'), 'object');
    t.equal(tokenize('foo bar').length, 2);

    t.throws(function () {
        tokenize(123);
    });
    t.throws(function () {
        tokenize({});
    });
    t.throws(function () {
        tokenize([]);
    });

    t.end();
});

test('english', function (t) {
    t.deepEqual(
        tokenize('The cat went over the wall.'),
        ['the', 'cat', 'went', 'over', 'the', 'wall']
    );
    t.deepEqual(
        tokenize('That\'ll cause problems for the farmer\'s pigs'),
        ['that\'ll', 'cause', 'problems', 'for', 'the', 'farmer\'s', 'pigs']
    );
    t.deepEqual(
        tokenize(' If you are    Razr owner...you must have this!  '),
        ['if', 'you', 'are', 'razr', 'owner', 'you', 'must', 'have', 'this']
    );
    t.deepEqual(
        tokenize('Tied to charger for conversations lasting more than 45 minutes.MAJOR PROBLEMS!!'),
        ['tied', 'to', 'charger', 'for', 'conversations', 'lasting', 'more', 'than', '45', 'minutes', 'major', 'problems']
    );
    t.end();
});

test('diacritic', function (t) {
    t.deepEqual(
        tokenize('This approach is naïve.'),
        ['this', 'approach', 'is', 'naïve']
    );
    t.deepEqual(
        tokenize('The puppy bowl team was very coöperative.'),
        ['the', 'puppy', 'bowl', 'team', 'was', 'very', 'coöperative']
    );
    t.deepEqual(
        tokenize('The soufflé was delicious!'),
        ['the', 'soufflé', 'was', 'delicious']
    );
    t.end();
});
<commit_msg>Fix for eslint max-len in tests<commit_after>var test = require('tap').test;
var tokenize = require('../../lib/tokenize');

test('spec', function (t) {
    t.type(tokenize, 'function');
    t.type(tokenize('foo'), 'object');
    t.equal(tokenize('foo bar').length, 2);

    t.throws(function () {
        tokenize(123);
    });
    t.throws(function () {
        tokenize({});
    });
    t.throws(function () {
        tokenize([]);
    });

    t.end();
});

test('english', function (t) {
    t.deepEqual(
        tokenize('The cat went over the wall.'),
        ['the', 'cat', 'went', 'over', 'the', 'wall']
    );
    t.deepEqual(
        tokenize('That\'ll cause problems for the farmer\'s pigs'),
        ['that\'ll', 'cause', 'problems', 'for', 'the', 'farmer\'s', 'pigs']
    );
    t.deepEqual(
        tokenize(' If you are    Razr owner...you must have this!  '),
        ['if', 'you', 'are', 'razr', 'owner', 'you', 'must', 'have', 'this']
    );
    t.deepEqual(
        // eslint-disable-next-line max-len
        tokenize('Tied to charger for conversations lasting more than 45 minutes.MAJOR PROBLEMS!!'),
        // eslint-disable-next-line max-len
        ['tied', 'to', 'charger', 'for', 'conversations', 'lasting', 'more', 'than', '45', 'minutes', 'major', 'problems']
    );
    t.end();
});

test('diacritic', function (t) {
    t.deepEqual(
        tokenize('This approach is naïve.'),
        ['this', 'approach', 'is', 'naïve']
    );
    t.deepEqual(
        tokenize('The puppy bowl team was very coöperative.'),
        ['the', 'puppy', 'bowl', 'team', 'was', 'very', 'coöperative']
    );
    t.deepEqual(
        tokenize('The soufflé was delicious!'),
        ['the', 'soufflé', 'was', 'delicious']
    );
    t.end();
});
<|endoftext|>


<commit_before>var axios = require('axios');

class PremiumPlugin {
  constructor() {
    this.var = "VAR!#!#!##"
  }
  default(command) { // This is the default command that is ran when you do your bot prefix and your plugin prefix example   !ping
    var self = this;

    self.disnode.platform.GetUserRole(command.msg.userID).then(function (role) {

      if(role){
        self.disnode.bot.SendCompactEmbed(command.msg.channel, "Ultra", ":white_check_mark: You Have Ultra!");
      }else{
        self.disnode.bot.SendCompactEmbed(command.msg.channel, "Ultra", ":x: Ultra Disabled!");
      }

    }).catch(function(err){
      self.disnode.bot.SendCompactEmbed(command.msg.channel, "Error :warning: ", "Error With Request: " + err );
    });

  }

}
module.exports = PremiumPlugin;
<commit_msg>Fixed Prem Plugin (not plat;js)<commit_after>var axios = require('axios');

class PremiumPlugin {
  constructor() {
    this.var = "VAR!#!#!##"
  }
  default(command) { // This is the default command that is ran when you do your bot prefix and your plugin prefix example   !ping
    var self = this;

    self.disnode.platform.GetUserUltra(command.msg.userID).then(function (role) {

      if(role){
        self.disnode.bot.SendCompactEmbed(command.msg.channel, "Ultra", ":white_check_mark: You Have Ultra!");
      }else{
        self.disnode.bot.SendCompactEmbed(command.msg.channel, "Ultra", ":x: Ultra Disabled!");
      }

    }).catch(function(err){
      self.disnode.bot.SendCompactEmbed(command.msg.channel, "Error :warning: ", "Error With Request: " + err );
    });

  }

}
module.exports = PremiumPlugin;
<|endoftext|>


<commit_before>module.exports = function(x) {
    x.module.loaders.push({
        test: /\.glsl$/,
        include: [],
        loader: 'shader',
    });
    x.module.loaders.push({
        test: /\.json$/,
        include: [],
        loader: 'json',
    });
    return x;
}
<commit_msg>use vtk.js loaders<commit_after>var vtkLoaders = require('../../node_modules/vtk.js/Utilities/config/webpack.loaders.js');

module.exports = function(x) {
    for (var i = 0; i < vtkLoaders.length; i++) {
        vtkLoaders[i].include = ['node_modules'];
        x.module.loaders.push(vtkLoaders[i]);
    }
    return x;
}
<|endoftext|>


<commit_before>// JS -> Dart
export var typeMapping = {
  'number': 'num',
  'boolean': 'bool',
  'string': 'String',
  'any': 'dynamic',
  'Promise': 'Future',
  'Observable': 'Stream',
  'ObservableController': 'StreamController',
  'Date': 'DateTime',
  'StringMap': 'Map'
};
<commit_msg>cleanup: remove an unused type<commit_after>// JS -> Dart
export var typeMapping = {
  'number': 'num',
  'boolean': 'bool',
  'string': 'String',
  'any': 'dynamic',
  'Promise': 'Future',
  'Observable': 'Stream',
  'Date': 'DateTime',
  'StringMap': 'Map'
};
<|endoftext|>


<commit_before>var xhr = function(url, callback) {
    var oReq = new XMLHttpRequest();
    oReq.onload = function(e){
        callback(this.responseText, e);
    };
    oReq.open("get", url, true);
    oReq.send();
};

var colonSeparateDuration = function(num) { // in seconds
    if (typeof num == "number" && !(Number.isNaN || isNaN)(num)) {
        var minutes = Math.floor(num / 60);
        var seconds = Math.floor(num % 60);
        return "" + minutes + ":" + zpad(seconds, 2);
    } else {
        return "--:--";
    }
};

var zpad = function pad(n, width, z) { // by user Pointy on SO: stackoverflow.com/a/10073788
    z = z || "0";
    n = n + "";
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
};

window.AudioContext = window.AudioContext || window.webkitAudioContext;

var cbus = {};

cbus.audio = {
    DEFAULT_JUMP_AMOUNT_BACKWARD: -10,
    DEFAULT_JUMP_AMOUNT_FORWARD: 30,

    element: null,

    setElement: function(elem) {
        if (cbus.audio.element) {
            cbus.audio.pause();
            cbus.audio.element.onseeked = null;
            cbus.audio.element.onloadedmetadata = null;
            cbus.audio.element.onended = null;
        }

        if (cbus.audio.queue.indexOf(elem) !== -1) {
            cbus.audio.queue.splice(cbus.audio.queue.indexOf(elem), 1);
        }

        cbus.audio.element = elem;
        cbus.audio.element.currentTime = 0;

        cbus.audio.element.onseeked = function() {
            cbus.audio.updatePlayerTime();
        };
        cbus.audio.element.onloadedmetadata = function() {
            cbus.audio.updatePlayerTime(true);
        };
        cbus.audio.element.onended = cbus.audio.playNextInQueue;

        var episodeElem = elem.parentElement.parentElement.parentElement.parentElement;

        var episodeTitle = episodeElem.querySelector(".episode_title").textContent;
        var episodeFeedTitle = episodeElem.querySelector(".episode_feed-title").textContent;
        var episodeImage = episodeElem.querySelector(".episode_background").style.backgroundImage;

        $(".player_time--total").text(colonSeparateDuration(cbus.audio.element.duration));

        document.querySelector("cbus-queue-item").title = episodeTitle;
        document.querySelector("cbus-queue-item").feedTitle = episodeFeedTitle;
        document.querySelector("cbus-queue-item").image = episodeImage;
    },

    updatePlayerTime: function(updateTotalLength) {
        if (cbus.audio.element && !cbus.audio.element.paused) {
            var currentTime = cbus.audio.element.currentTime;
            /* slider */
            var percentage = currentTime / cbus.audio.element.duration;
            $(".player_slider").val(Math.round(1000 * percentage) || 0);

            /* time indicator */
            $(".player_time--now").text(colonSeparateDuration(currentTime));
            if (updateTotalLength === true) {
                $(".player_time--total").text(colonSeparateDuration(cbus.audio.element.duration));
            }
        }
    },
    sliderUpdateInterval: null,

    playNextInQueue: function() {
        if (cbus.audio.queue.length > 0) {
            cbus.audio.setElement(cbus.audio.queue[0]);
            cbus.audio.updatePlayerTime(true);
            cbus.audio.play();
        }
    },

    play: function() {
        cbus.audio.element.play();
        $(".player_button--play").html("pause");
        $(".player_time--total")
    },
    pause: function() {
        cbus.audio.element.pause();
        $(".player_button--play").html("play_arrow");
    },
    stop: function() {
        cbus.audio.element.pause();
        cbus.audio.element.currentTime = 0;
    },
    jump: function(amount) {
        cbus.audio.element.currentTime += amount;
    },

    queue: [],

    enqueue: function(elem) {
        cbus.audio.queue.push(elem);
    }
};

cbus.audio.sliderUpdateInterval = setInterval(cbus.audio.updatePlayerTime, 500);

cbus.display = function(thing) {
    switch (thing) {
        case "feeds":
            $(".filters_feeds").html("");
            cbus.feeds.forEach(function(feed) {
                $(".filters_feeds").append("
\
");
            });
            break;
        case "episodes":
            $(".list--episodes").html("");

            for (var i = 0; i < Math.min(50, cbus.episodes.length); i++) {
                var episode = cbus.episodes[i];

                var episodeElem = document.createElement("cbus-episode");

                episodeElem.title = episode.title;
                episodeElem.image = episode.feed.image;
                episodeElem.feedTitle = episode.feed.title;
                episodeElem.url = episode.url;
                episodeElem.description = episode.description;

                $(".list--episodes").append(episodeElem);
            };

            break;
    }
};

cbus.update = function() {
    $(".list--episodes").html("");
    xhr("update?feeds=" + encodeURIComponent(JSON.stringify(cbus.feeds)), function(r) {
        var feedContents = JSON.parse(r);
        var episodes = [];

        console.log(feedContents);

        Object.keys(feedContents).forEach(function(feedUrl) {
            feedContents[feedUrl].items.forEach(function(episode) {
                var feed = cbus.feeds.filter(function(feed) {
                    return feed.url === feedUrl;
                })[0];

                episodes.push({
                    url: episode.url,
                    title: episode.title,
                    description: episode.description,
                    date: (new Date(episode.date).getTime() ? new Date(episode.date) : null), // check if date is valid
                    feed: feed
                });
            });
        });

        cbus.episodes = episodes.sort(function(a, b) {
            if (a.date > b.date) return -1;
            if (a.date < b.date) return 1;
            return 0;
        });
        cbus.display("episodes");
    });
};

cbus.feeds = (localStorage.getItem("cbus_feeds") ? JSON.parse(localStorage.getItem("cbus_feeds")) : []);

cbus.display("feeds");

$(".filters_control--add-feed").click(function() {
    Ply.dialog("prompt", {
        title: "Add feed",
        form: { title: "Some Random Podcast" }
    }).always(function (ui) {
        if (ui.state) {
            console.log(ui.widget);
            var feedTitle = ui.data.title;
            xhr("feedinfo?term=" + feedTitle, function(res) {
                var json = JSON.parse(res);
                console.log(json);

                var feedInfo = json[0];

                var feedTitle = feedInfo.title;
                var feedImage = feedInfo.image;
                var feedUrl = feedInfo.url;

                var feedAlreadyAdded = false;
                for (var i = 0; i < cbus.feeds.length; i++) {
                    var lfeed = cbus.feeds[i];
                    var lfeedUrl = lfeed.url;
                    if (lfeedUrl === feedUrl) {
                        feedAlreadyAdded = true;
                        break;
                    }
                }

                if (feedAlreadyAdded) {
                    Ply.dialog("alert", "You already have that feed.");
                } else {
                    cbus.feeds.push({
                        url: feedUrl,
                        title: feedTitle,
                        image: feedImage
                    });
                    localStorage.setItem("cbus_feeds", JSON.stringify(cbus.feeds));
                    Ply.dialog("alert", "Added feed.");
                }
            });
        }
    });
});

$(".list--episodes").on("click", function(e) {
    var classList = e.target.classList;
    var audioElem = e.target.parentElement.parentElement.querySelector(".episode_audio_player");
    if (classList.contains("episode_audio_button--play")) {
        cbus.audio.setElement(audioElem);
        cbus.audio.play();
    } else if (classList.contains("episode_audio_button--enqueue")) {
        cbus.audio.enqueue(audioElem);
    }
});

$(".player").on("click", function(e) {
    var classList = e.target.classList;
    if (classList.contains("player_button")) {
        if (classList.contains("player_button--backward")) {
            cbus.audio.jump(cbus.audio.DEFAULT_JUMP_AMOUNT_BACKWARD);
        } else if (classList.contains("player_button--forward")) {
            cbus.audio.jump(cbus.audio.DEFAULT_JUMP_AMOUNT_FORWARD);
        } else if (classList.contains("player_button--play")) {
            if (!cbus.audio.element) {
                if (cbus.audio.queue.length > 0) {
                    cbus.audio.setElement(cbus.audio.queue[0]);
                } else {
                    cbus.audio.setElement($(".episode_audio_player")[0]);
                }
                cbus.audio.play();
            } else if (cbus.audio.element.paused) {
                cbus.audio.play();
            } else {
                cbus.audio.pause();
            }
        } else if (classList.contains("player_button--next")) {
            cbus.audio.playNextInQueue();
        }
    }
});

$(".player_button--next").on("mouseenter click", function(e) {
    var nextEpisodeString = "Nothing in queue.";

    if (cbus.audio.queue.length !== 0) {
        nextEpisodeString = $("" + cbus.audio.queue[0].parentElement.parentElement.querySelector(".episode_title").textContent + "
" +  cbus.audio.queue[0].parentElement.parentElement.querySelector(".episode_feed-title").textContent + "");
    }

    $(this).tooltipster("content", nextEpisodeString);
});

$(".player_slider").on("input", function() {
    var proportion = this.value / this.max;
    cbus.audio.element.currentTime = cbus.audio.element.duration * proportion;
});

$(".filter--time").on("change", function() {
    var timeCategory = this.value;
    $(".episode").each(function(i, elem) {
        var matchableTimes = elem.dataset.time.split(",");
        if (matchableTimes.indexOf(timeCategory) !== -1) {
            elem.classList.remove("hidden");
        } else {
            elem.classList.add("hidden");
        }
    });
});

/* header actions */

$(".header_actions").on("click", function(e) {
    var classList = e.target.classList;
    if (classList.contains("header_action")) {
        if (classList.contains("header_action--show-filters")) {
            $(".content-container")[0].classList.toggle("filters-visible");
            e.target.classList.toggle("md-inactive");
        }
        if (classList.contains("header_action--refresh-episodes")) {
            cbus.update();
        }
    }
});

/* do the thing */

cbus.update();

/* initialize tooltipster */

$(".tooltip").tooltipster({
    theme: "tooltipster-cbus"
});
<commit_msg>Sort podcasts (not episodes) alphabetically<commit_after>var xhr = function(url, callback) {
    var oReq = new XMLHttpRequest();
    oReq.onload = function(e){
        callback(this.responseText, e);
    };
    oReq.open("get", url, true);
    oReq.send();
};

var colonSeparateDuration = function(num) { // in seconds
    if (typeof num == "number" && !(Number.isNaN || isNaN)(num)) {
        var minutes = Math.floor(num / 60);
        var seconds = Math.floor(num % 60);
        return "" + minutes + ":" + zpad(seconds, 2);
    } else {
        return "--:--";
    }
};

var zpad = function pad(n, width, z) { // by user Pointy on SO: stackoverflow.com/a/10073788
    z = z || "0";
    n = n + "";
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
};

window.AudioContext = window.AudioContext || window.webkitAudioContext;

var cbus = {};

cbus.audio = {
    DEFAULT_JUMP_AMOUNT_BACKWARD: -10,
    DEFAULT_JUMP_AMOUNT_FORWARD: 30,

    element: null,

    setElement: function(elem) {
        if (cbus.audio.element) {
            cbus.audio.pause();
            cbus.audio.element.onseeked = null;
            cbus.audio.element.onloadedmetadata = null;
            cbus.audio.element.onended = null;
        }

        if (cbus.audio.queue.indexOf(elem) !== -1) {
            cbus.audio.queue.splice(cbus.audio.queue.indexOf(elem), 1);
        }

        cbus.audio.element = elem;
        cbus.audio.element.currentTime = 0;

        cbus.audio.element.onseeked = function() {
            cbus.audio.updatePlayerTime();
        };
        cbus.audio.element.onloadedmetadata = function() {
            cbus.audio.updatePlayerTime(true);
        };
        cbus.audio.element.onended = cbus.audio.playNextInQueue;

        var episodeElem = elem.parentElement.parentElement.parentElement.parentElement;

        var episodeTitle = episodeElem.querySelector(".episode_title").textContent;
        var episodeFeedTitle = episodeElem.querySelector(".episode_feed-title").textContent;
        var episodeImage = episodeElem.querySelector(".episode_background").style.backgroundImage;

        $(".player_time--total").text(colonSeparateDuration(cbus.audio.element.duration));

        document.querySelector("cbus-queue-item").title = episodeTitle;
        document.querySelector("cbus-queue-item").feedTitle = episodeFeedTitle;
        document.querySelector("cbus-queue-item").image = episodeImage;
    },

    updatePlayerTime: function(updateTotalLength) {
        if (cbus.audio.element && !cbus.audio.element.paused) {
            var currentTime = cbus.audio.element.currentTime;
            /* slider */
            var percentage = currentTime / cbus.audio.element.duration;
            $(".player_slider").val(Math.round(1000 * percentage) || 0);

            /* time indicator */
            $(".player_time--now").text(colonSeparateDuration(currentTime));
            if (updateTotalLength === true) {
                $(".player_time--total").text(colonSeparateDuration(cbus.audio.element.duration));
            }
        }
    },
    sliderUpdateInterval: null,

    playNextInQueue: function() {
        if (cbus.audio.queue.length > 0) {
            cbus.audio.setElement(cbus.audio.queue[0]);
            cbus.audio.updatePlayerTime(true);
            cbus.audio.play();
        }
    },

    play: function() {
        cbus.audio.element.play();
        $(".player_button--play").html("pause");
        $(".player_time--total")
    },
    pause: function() {
        cbus.audio.element.pause();
        $(".player_button--play").html("play_arrow");
    },
    stop: function() {
        cbus.audio.element.pause();
        cbus.audio.element.currentTime = 0;
    },
    jump: function(amount) {
        cbus.audio.element.currentTime += amount;
    },

    queue: [],

    enqueue: function(elem) {
        cbus.audio.queue.push(elem);
    }
};

cbus.audio.sliderUpdateInterval = setInterval(cbus.audio.updatePlayerTime, 500);

cbus.display = function(thing) {
    switch (thing) {
        case "feeds":
            $(".filters_feeds").html("");
            cbus.feeds.forEach(function(feed) {
                $(".filters_feeds").append("
\
");
            });
            break;
        case "episodes":
            $(".list--episodes").html("");

            for (var i = 0; i < Math.min(50, cbus.episodes.length); i++) {
                var episode = cbus.episodes[i];

                var episodeElem = document.createElement("cbus-episode");

                episodeElem.title = episode.title;
                episodeElem.image = episode.feed.image;
                episodeElem.feedTitle = episode.feed.title;
                episodeElem.url = episode.url;
                episodeElem.description = episode.description;

                $(".list--episodes").append(episodeElem);
            };

            break;
    }
};

cbus.update = function() {
    $(".list--episodes").html("");
    xhr("update?feeds=" + encodeURIComponent(JSON.stringify(cbus.feeds)), function(r) {
        var feedContents = JSON.parse(r);
        var episodes = [];

        console.log(feedContents);

        Object.keys(feedContents).forEach(function(feedUrl) {
            feedContents[feedUrl].items.forEach(function(episode) {
                var feed = cbus.feeds.filter(function(feed) {
                    return feed.url === feedUrl;
                })[0];

                episodes.push({
                    url: episode.url,
                    title: episode.title,
                    description: episode.description,
                    date: (new Date(episode.date).getTime() ? new Date(episode.date) : null), // check if date is valid
                    feed: feed
                });
            });
        });

        cbus.episodes = episodes.sort(function(a, b) {
            if (a.date > b.date) return -1;
            if (a.date < b.date) return 1;
            return 0;
        });
        cbus.display("episodes");
    });
};

cbus.feeds = (localStorage.getItem("cbus_feeds") ?
    JSON.parse(localStorage.getItem("cbus_feeds")).sort(function(a, b) {
        var aTitle = a.title.toLowerCase();
        var bTitle = b.title.toLowerCase();

        if (aTitle < bTitle) return -1;
        if (aTitle > bTitle) return 1;
        return 0;
    })
    : []);

cbus.display("feeds");

$(".filters_control--add-feed").click(function() {
    Ply.dialog("prompt", {
        title: "Add feed",
        form: { title: "Some Random Podcast" }
    }).always(function (ui) {
        if (ui.state) {
            console.log(ui.widget);
            var feedTitle = ui.data.title;
            xhr("feedinfo?term=" + feedTitle, function(res) {
                var json = JSON.parse(res);
                console.log(json);

                var feedInfo = json[0];

                var feedTitle = feedInfo.title;
                var feedImage = feedInfo.image;
                var feedUrl = feedInfo.url;

                var feedAlreadyAdded = false;
                for (var i = 0; i < cbus.feeds.length; i++) {
                    var lfeed = cbus.feeds[i];
                    var lfeedUrl = lfeed.url;
                    if (lfeedUrl === feedUrl) {
                        feedAlreadyAdded = true;
                        break;
                    }
                }

                if (feedAlreadyAdded) {
                    Ply.dialog("alert", "You already have that feed.");
                } else {
                    cbus.feeds.push({
                        url: feedUrl,
                        title: feedTitle,
                        image: feedImage
                    });
                    localStorage.setItem("cbus_feeds", JSON.stringify(cbus.feeds));
                    Ply.dialog("alert", "Added feed.");
                }
            });
        }
    });
});

$(".list--episodes").on("click", function(e) {
    var classList = e.target.classList;
    var audioElem = e.target.parentElement.parentElement.querySelector(".episode_audio_player");
    if (classList.contains("episode_audio_button--play")) {
        cbus.audio.setElement(audioElem);
        cbus.audio.play();
    } else if (classList.contains("episode_audio_button--enqueue")) {
        cbus.audio.enqueue(audioElem);
    }
});

$(".player").on("click", function(e) {
    var classList = e.target.classList;
    if (classList.contains("player_button")) {
        if (classList.contains("player_button--backward")) {
            cbus.audio.jump(cbus.audio.DEFAULT_JUMP_AMOUNT_BACKWARD);
        } else if (classList.contains("player_button--forward")) {
            cbus.audio.jump(cbus.audio.DEFAULT_JUMP_AMOUNT_FORWARD);
        } else if (classList.contains("player_button--play")) {
            if (!cbus.audio.element) {
                if (cbus.audio.queue.length > 0) {
                    cbus.audio.setElement(cbus.audio.queue[0]);
                } else {
                    cbus.audio.setElement($(".episode_audio_player")[0]);
                }
                cbus.audio.play();
            } else if (cbus.audio.element.paused) {
                cbus.audio.play();
            } else {
                cbus.audio.pause();
            }
        } else if (classList.contains("player_button--next")) {
            cbus.audio.playNextInQueue();
        }
    }
});

$(".player_button--next").on("mouseenter click", function(e) {
    var nextEpisodeString = "Nothing in queue.";

    if (cbus.audio.queue.length !== 0) {
        nextEpisodeString = $("" + cbus.audio.queue[0].parentElement.parentElement.querySelector(".episode_title").textContent + "
" +  cbus.audio.queue[0].parentElement.parentElement.querySelector(".episode_feed-title").textContent + "");
    }

    $(this).tooltipster("content", nextEpisodeString);
});

$(".player_slider").on("input", function() {
    var proportion = this.value / this.max;
    cbus.audio.element.currentTime = cbus.audio.element.duration * proportion;
});

$(".filter--time").on("change", function() {
    var timeCategory = this.value;
    $(".episode").each(function(i, elem) {
        var matchableTimes = elem.dataset.time.split(",");
        if (matchableTimes.indexOf(timeCategory) !== -1) {
            elem.classList.remove("hidden");
        } else {
            elem.classList.add("hidden");
        }
    });
});

/* header actions */

$(".header_actions").on("click", function(e) {
    var classList = e.target.classList;
    if (classList.contains("header_action")) {
        if (classList.contains("header_action--show-filters")) {
            $(".content-container")[0].classList.toggle("filters-visible");
            e.target.classList.toggle("md-inactive");
        }
        if (classList.contains("header_action--refresh-episodes")) {
            cbus.update();
        }
    }
});

/* do the thing */

cbus.update();

/* initialize tooltipster */

$(".tooltip").tooltipster({
    theme: "tooltipster-cbus"
});
<|endoftext|>


<commit_before>import JobStatus from 'girder_plugins/jobs/JobStatus';

JobStatus.registerStatus({
    WORKER_FETCHING_INPUT: {
        value: 820,
        text: 'Fetching input',
        icon: 'icon-download'
    },
    WORKER_CONVERTING_INPUT: {
        value: 821,
        text: 'Converting input',
        icon: 'icon-shuffle'
    },
    WORKER_CONVERTING_OUTPUT: {
        value: 822,
        text: 'Converting output',
        icon: 'icon-shuffle'
    },
    WORKER_PUSHING_OUTPUT: {
        value: 823,
        text: 'Pushing output',
        icon: 'icon-upload'
    }
});
<commit_msg>Cannot modify plugin globals via static imports<commit_after>girder.plugins.jobs.JobStatus.registerStatus({
    WORKER_FETCHING_INPUT: {
        value: 820,
        text: 'Fetching input',
        icon: 'icon-download'
    },
    WORKER_CONVERTING_INPUT: {
        value: 821,
        text: 'Converting input',
        icon: 'icon-shuffle'
    },
    WORKER_CONVERTING_OUTPUT: {
        value: 822,
        text: 'Converting output',
        icon: 'icon-shuffle'
    },
    WORKER_PUSHING_OUTPUT: {
        value: 823,
        text: 'Pushing output',
        icon: 'icon-upload'
    }
});
<|endoftext|>


<commit_before>//the javascript for the game logic
jQuery(document).ready(function(){

	swiper = new Swiper('.swiper-container', {
	    pagination: '.swiper-pagination',
	    paginationClickable: true,
	    onTransitionEnd: function(){
			proceedGame();
		}
	});

	//add the game status button
	jQuery.get("cards/status.html", function(data){
		jQuery('body').append(data);
		console.log(data);
	});

	//load the status html popup
	//add the game status button
	jQuery.get("cards/status_display.html", function(data){
		jQuery('body').append(data);
		console.log(data);
	});

	jQuery('body').on('click', '.game_butt', function () {
		nextPage();
	});

	jQuery('body').on('click', '#wolf_butt', function(){
		var arr =  jQuery('#wolf_identity').val();
		//set the identity of the wolf
		for (var i =0 ; i < arr.length; i++){
			data.players[arr[i]-1].role = "werewolf";
		}
		//set the target to kill
		var to_kill = jQuery("#wolf_kill").val();
		data.players[to_kill].die(arr);
		for (var i=0; i<data.players.length;i++){
			if (i!=to_kill){
				data.players[i].reset();
			}
		}
	});

	jQuery('body').on('click', '#game_status', function(){
		document.getElementById('light').style.display='block';
		document.getElementById('fade').style.display='block';
		jQuery("#wolf_count").html("狼 "+data.role_count.werewolf);
		jQuery("#god_count").html("神 "+data.role_count.god);
		jQuery("#people_count").html("民 "+data.role_count.people);
	});

	jQuery('body').on('click', '#prophet_butt', function(){
			var play_id = jQuery("#prophet_check").val();
			if (data.players[play_id-1].role =="werewolf"){
				alert("这玩家是坏人");
			}else{
				alert("这玩家是好人");
			}
	});

	jQuery('body').on('click', "#morning_next_round", function(){
		nextRound();
	});
});

function activeCardName(){
	return jQuery('.swiper-slide-active')[0].className;
}

function nextPage(){
	swiper.slideNext();
}

function proceedGame(){
	num_wolf = data.role_count.werewolf;
	num_god = data.role_count.god;
	num_people = data.role_count.people;
	num_total = parseInt(num_wolf)+ parseInt(num_god) + parseInt(num_people);
	if(activeCardName().includes("wolf")){
		//we are at the wolf page
		//count the numeber of wolves and populate the option box
		document.getElementById('wolf_identity').innerHTML = "<optgroup disabled hidden></optgroup>";
		document.getElementById('wolf_kill').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('wolf_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('wolf_kill').appendChild(opt);
		}
	} else if (activeCardName().includes("witch")){
		//we are at the witch page
		document.getElementById('witch_identity').innerHTML = "";
		document.getElementById('witch_save').innerHTML = "";
		document.getElementById('witch_kill').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_save').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_kill').appendChild(opt);
		}
	} else if (activeCardName().includes("prophet")) {
		document.getElementById('prophet_identity').innerHTML = "";
		document.getElementById('prophet_check').innerHTML = "";
		console.log(num_total);
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('prophet_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('prophet_check').appendChild(opt);
		}
	} else if (activeCardName().includes("hunter"))  {
		document.getElementById('hunter_identity').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('hunter_identity').appendChild(opt);
		}
	}
}

/*
 * The function to move the game to next round and check if the game is over
 */
function nextRound(){
	if(ifGameOver()){
		alert("游戏结束!");
	} else {
		data.roundCount++;
		jQuery(".setup_hidden").hide();
		swiper.slideTo("0");
	}
}

/*
 * The function to check if the game is over
 */
function ifGameOver(){
	return false;
}
<commit_msg>improved the selection box's performance<commit_after>//the javascript for the game logic
jQuery(document).ready(function(){

	swiper = new Swiper('.swiper-container', {
	    pagination: '.swiper-pagination',
	    paginationClickable: true,
	    onTransitionEnd: function(){
			proceedGame();
		}
	});

	//add the game status button
	jQuery.get("cards/status.html", function(data){
		jQuery('body').append(data);
		console.log(data);
	});

	//load the status html popup
	//add the game status button
	jQuery.get("cards/status_display.html", function(data){
		jQuery('body').append(data);
		console.log(data);
	});

	jQuery('body').on('click', '.game_butt', function () {
		nextPage();
	});

	jQuery('body').on('click', '#wolf_butt', function(){
		var arr =  jQuery('#wolf_identity').val();
		//set the identity of the wolf
		for (var i =0 ; i < arr.length; i++){
			data.players[arr[i]-1].role = "werewolf";
		}
		//set the target to kill
		var to_kill = jQuery("#wolf_kill").val();
		data.players[to_kill].die(arr);
		for (var i=0; i<data.players.length;i++){
			if (i!=to_kill){
				data.players[i].reset();
			}
		}
	});

	jQuery('body').on('click', '#game_status', function(){
		document.getElementById('light').style.display='block';
		document.getElementById('fade').style.display='block';
		jQuery("#wolf_count").html("狼 "+data.role_count.werewolf);
		jQuery("#god_count").html("神 "+data.role_count.god);
		jQuery("#people_count").html("民 "+data.role_count.people);
	});

	jQuery('body').on('click', '#prophet_butt', function(){
			var play_id = jQuery("#prophet_check").val();
			if (data.players[play_id-1].role =="werewolf"){
				alert("这玩家是坏人");
			}else{
				alert("这玩家是好人");
			}
	});

	jQuery('body').on('click', "#morning_next_round", function(){
		nextRound();
	});
});

function activeCardName(){
	return jQuery('.swiper-slide-active')[0].className;
}

function nextPage(){
	swiper.slideNext();
}

function proceedGame(){
	num_wolf = data.role_count.werewolf;
	num_god = data.role_count.god;
	num_people = data.role_count.people;
	num_total = parseInt(num_wolf)+ parseInt(num_god) + parseInt(num_people);
	if(activeCardName().includes("wolf")){
		if(data.roundCount==0){
			//we are at the wolf page
			//count the numeber of wolves and populate the option box
			document.getElementById('wolf_identity').innerHTML = "<optgroup disabled hidden></optgroup>";
			document.getElementById('wolf_kill').innerHTML = "";
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('wolf_identity').appendChild(opt);
			}
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('wolf_kill').appendChild(opt);
			}
		}
	} else if (activeCardName().includes("witch")){
		if(data.roundCount==0) {
			//we are at the witch page
			document.getElementById('witch_identity').innerHTML = "";
			document.getElementById('witch_save').innerHTML = "";
			document.getElementById('witch_kill').innerHTML = "";
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('witch_identity').appendChild(opt);
			}
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('witch_save').appendChild(opt);
			}
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('witch_kill').appendChild(opt);
			}
		}
	} else if (activeCardName().includes("prophet")) {
		if(data.roundCount==0) {
			document.getElementById('prophet_identity').innerHTML = "";
			document.getElementById('prophet_check').innerHTML = "";
			console.log(num_total);
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('prophet_identity').appendChild(opt);
			}
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('prophet_check').appendChild(opt);
			}
		}
	} else if (activeCardName().includes("hunter"))  {
		if(data.roundCount==0){
			document.getElementById('hunter_identity').innerHTML = "";
			for (var i=0;i<num_total;i++){
			    var opt = document.createElement('option');
			    opt.value = i+1;
			    opt.innerHTML = (i+1).toString() + " 号";
			 	document.getElementById('hunter_identity').appendChild(opt);
			}
		}
	}
}

/*
 * The function to move the game to next round and check if the game is over
 */
function nextRound(){
	if(ifGameOver()){
		alert("游戏结束!");
	} else {
		data.roundCount++;
		jQuery(".setup_hidden").hide();
		swiper.slideTo("0");
	}
}

/*
 * The function to check if the game is over
 */
function ifGameOver(){
	return false;
}
<|endoftext|>


<commit_before>$(document).ready(function () {

    var columnForm = $("#columnSize").val();
    var rowForm = $("#rowSize").val();

    newGame(columnForm, rowForm);

    $("form").submit(function (event) {
        event.preventDefault();

        $(".table1").empty();

        columnForm = $("#columnSize").val();
        rowForm = $("#rowSize").val();

        newGame(columnForm, rowForm);
    });

    $(document).keydown(function (key) {
        switch (parseInt(key.which, 10)) {
            case 37:
                game.moveLeft()
                break;
            case 38:
                game.moveUp()
                break;
            case 39:
                game.moveRight()
                break;
            case 40:
                game.moveDown()
                break;
            default:
                break;
        }
        refreshData();
    });
});

var newGame = function (columnForm, rowForm) {
    window.game = new Game(columnForm, rowForm);
    window.game.start();

    appendData();
    refreshData();
}

var appendData = function () {
    for (var i = 0; i < game.rowLength; i++) {
        $('.table1').append("

")
        for (var j = 0; j < game.colLength; j++) {
            $('.row' + i).append("	")
        }
    }
}

var refreshData = function () {
    for (var i = 0; i < game.rowLength; i++) {
        for (var j = 0; j < game.colLength; j++) {
            switch (game.board[i][j]) {
                case 0:
                    $('.data' + i + j).html(" ")
                    $('.data' + i + j).css('background-color', '#CDC1B4')
                    break;
                case 2:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#FAF8EF')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 4:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#EDE0C8')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 8:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#F2B179')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 16:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#F59563')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 32:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#F67C5E')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 64:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#F5633D')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 128:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#EDCF72')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 256:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#EDCC61')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 512:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#EDC850')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 1024:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#18EC9E')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 2048:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#18EC9E')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 4096:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#18EC9E')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 8192:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', '#18EC9E')
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
            }
        }
    }
}
<commit_msg>Add color object<commit_after>var colors = {
    0: '#CDC1B4',
    2: '#FAF8EF',
    4: '#EDE0C8',
    8: '#F2B179',
    16: '#F59563',
    32: '#F67C5E',
    64: '#F5633D',
    128: '#EDCF72',
    256: '#EDC850',
    512: '#EDC850',
    1024: '#18EC9E',
    2048: '#18EC9E',
    4096: '#18EC9E',
    8192: '#18EC9E'
}

$(document).ready(function () {

    var columnForm = $("#columnSize").val();
    var rowForm = $("#rowSize").val();

    newGame(columnForm, rowForm);

    $("form").submit(function (event) {
        event.preventDefault();

        $(".table1").empty();

        columnForm = $("#columnSize").val();
        rowForm = $("#rowSize").val();

        newGame(columnForm, rowForm);
    });

    $(document).keydown(function (key) {
        switch (parseInt(key.which, 10)) {
            case 37:
                game.moveLeft()
                break;
            case 38:
                game.moveUp()
                break;
            case 39:
                game.moveRight()
                break;
            case 40:
                game.moveDown()
                break;
            default:
                break;
        }
        refreshData();
    });
});

var newGame = function (columnForm, rowForm) {
    window.game = new Game(columnForm, rowForm);
    window.game.start();

    appendData();
    refreshData();
}

var appendData = function () {
    for (var i = 0; i < game.rowLength; i++) {
        $('.table1').append("

")
        for (var j = 0; j < game.colLength; j++) {
            $('.row' + i).append("	")
        }
    }
}

var refreshData = function () {
    for (var i = 0; i < game.rowLength; i++) {
        for (var j = 0; j < game.colLength; j++) {
            switch (game.board[i][j]) {
                case 0:
                    $('.data' + i + j).html(" ")
                    $('.data' + i + j).css('background-color', colors[0])
                    break;
                case 2:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[2])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 4:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[4])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 8:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[8])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 16:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[16])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 32:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[32])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 64:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[64])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 128:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[128])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 256:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[256])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 512:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[512])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 1024:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[1024])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 2048:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[2048])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 4096:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[4096])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
                case 8192:
                    $('.data' + i + j).html(game.board[i][j])
                    $('.data' + i + j).css('background-color', colors[8192])
                    $('.data' + i + j).css('opacity', '1.0')
                    break;
            }
        }
    }
}
<|endoftext|>


<commit_before>App = Ember.Application.create();

App.ApplicationView = Ember.View.extend({
  templateName: 'application'
});
App.ApplicationController = Ember.Controller.extend();

// Index view to display all posts on the page
App.PostsView = Ember.View.extend({
  templateName: 'post-list-view'
});

// Create new post text field. Separate view to be able to bind events
App.CreatePostView = Ember.TextArea.extend(Ember.TargetActionSupport, {
  attributeBindings: ['class'],

  // TODO: Extract value from controller
  valueBinding: 'App.postsController.body',

  insertNewline: function() {
    this.triggerAction();
  },

  didInsertElement: function() {
    this.$().focus();
  }
})

// View to display single post. Post has following subviews (defined below):
//  - link to show a comment form
//  - form to add a new comment
App.PostContainerView = Ember.View.extend({
  templateName: 'post-view',
  isFormVisible: false,

  toggleVisibility: function() {
    this.toggleProperty('isFormVisible');
  },

  didInsertElement: function() {
    this.$().hide().slideDown('slow');
  },

  willDestroyElement: function() {
    var clone = this.$().clone();
    this.$().replaceWith(clone);
    clone.fadeOut('slow')
  }
});

App.CommentContainerView = Ember.View.extend({
  templateName: 'comment-view'
})

// Create new post text field. Separate view to be able to bind events
App.CommentPostView = Ember.View.extend(Ember.TargetActionSupport, {
  tagName: "a",

  click: function() {
    this.triggerAction();
  }
})

// Text field to post a comment. Separate view to make it hideable
App.CommentForm = Ember.View.extend({
  // I'd no success to use isVisibleBinding property...
  classNameBindings: 'isVisible visible:invisible',
  body: '',

  isVisible: function() {
    return this.get('parentView.isFormVisible') == true;
  }.property('parentView.isFormVisible'),

  autoFocus: function () {
    if (this.get('parentView.isFormVisible') == true) {
      this.$().hide().show("fast");
      this.$('input').focus();
    }
  }.observes('parentView.isFormVisible'),

  submitComment: function() {
    if (this.body) {
      // XXX: rather strange bit of code here -- potentially a defect
      var post = this.bindingContext.content || this.bindingContext;
      App.commentsController.createComment(post, this.body)
      this.set('parentView.isFormVisible', false)
      this.set('body', '')
    }
  },

  // XXX: this is a dup of App.PostContainerView.toggleVisibility()
  // function. I just do not know how to access it from UI bindings
  toggleVisibility: function() {
    this.toggleProperty('parentView.isFormVisible');
  }
});

// Create new post text field. Separate view to be able to bind events
App.CreateCommentView = Ember.TextField.extend(Ember.TargetActionSupport, {
  attributeBindings: ['class'],

  insertNewline: function() {
    this.triggerAction();
  }
})

// Separate page for a single post
App.OnePostController = Ember.ObjectController.extend();
App.OnePostView = Ember.View.extend({
  templateName: 'a-post',
  isFormVisible: false,

  toggleVisibility: function(){
    this.toggleProperty('isFormVisible');
  }
});

App.Comment = Ember.Object.extend({
  body: null,
  createdAt: null,
  user: null
});

App.CommentsController = Ember.ArrayController.extend({
  createComment: function(post, body) {
    var comment = App.Comment.create({
      body: body,
      post_id: post.id
    });

    $.ajax({
      url: '/v1/comments',
      type: 'post',
      data: { body: body, post_id: post.id }, // XXX: we've already defined a model above
      context: comment,
      success: function(response) {
        this.setProperties(response);
        // We do not insert comment right now, but wait for a socket event
        // post.comments.pushObject(comment)
      }
    })
    return comment;
  }
})
App.commentsController = App.CommentsController.create()

App.Post = Ember.Object.extend({
  body: null,
  createdAt: null,
  updatedAt: null,
  comments: [],
  user: null,

  createdAgo: function() {
    return moment(this.get('createdAt')).fromNow();
  }.property('createdAt')
});

App.PostsController = Ember.ArrayController.extend(Ember.SortableMixin, {
  content: [],
  body: '',

  sortProperties: ['updatedAt'],
  sortAscending: false,

  // XXX: a bit strange having this method here.
  submitPost: function() {
    if (this.body) {
      App.postsController.createPost(this.body);
      this.set('body', '')
    }
  },

  removePost: function(propName, value) {
    var obj = this.findProperty(propName, value);
    this.removeObject(obj);
  },

  createPost: function(body) {
    var post = App.Post.create({
      body: body
    });

    $.ajax({
      url: '/v1/posts',
      type: 'post',
      data: { body: body }, // XXX: we've already defined a model above
      context: post,
      success: function(response) {
        this.setProperties(response);
        // We do not insert post right now, but wait for a socket event
        // App.postsController.insertAt(0, post)
      }
    })
    return post;
  },

  findAll: function() {
    this.set('content', [])

    $.ajax({
      url: '/v1/timeline/anonymous',
      dataType: 'jsonp',
      context: this,
      success: function(response){
        response.posts.forEach(function(attrs) {
          var post = App.Post.create(attrs)
          this.addObject(post)
        }, this)
      }
    })
    return this
  },

  findOne: function(postId) {
    var post = App.Post.create({
      id: postId
    });

    $.ajax({
      url: '/v1/posts/' + postId,
      dataType: 'jsonp',
      context: post,
      success: function(response){
        this.setProperties(response)
      }
    })
    return post;
  }
})
App.postsController = App.PostsController.create()

App.Router = Ember.Router.extend({
  // enableLogging: true,

  root: Ember.Route.extend({
    posts: Ember.Route.extend({
      route: '/',

      showPost: Ember.Route.transitionTo('aPost'),
      showAllPosts: Ember.Route.transitionTo('posts'),

      connectOutlets: function(router){
        router.get('applicationController').connectOutlet('posts', App.postsController.findAll());
      }
    }),

    aPost: Ember.Route.extend({
      route: '/:postId',

      showAllPosts: Ember.Route.transitionTo('posts'),

      connectOutlets: function(router, context) {
        router.get('applicationController').connectOutlet('onePost', context);
      },

      serialize: function(router, context){
        return {postId: context.get('id')}
      },

      deserialize: function(router, urlParams) {
        return App.postsController.findOne(urlParams.postId);
      }
    })
  })
});

App.initialize();

<commit_msg>Adds animation effect on new comment event.<commit_after>App = Ember.Application.create();

App.ApplicationView = Ember.View.extend({
  templateName: 'application'
});
App.ApplicationController = Ember.Controller.extend();

// Index view to display all posts on the page
App.PostsView = Ember.View.extend({
  templateName: 'post-list-view'
});

// Create new post text field. Separate view to be able to bind events
App.CreatePostView = Ember.TextArea.extend(Ember.TargetActionSupport, {
  attributeBindings: ['class'],

  // TODO: Extract value from controller
  valueBinding: 'App.postsController.body',

  insertNewline: function() {
    this.triggerAction();
  },

  didInsertElement: function() {
    this.$().focus();
  }
})

// View to display single post. Post has following subviews (defined below):
//  - link to show a comment form
//  - form to add a new comment
App.PostContainerView = Ember.View.extend({
  templateName: 'post-view',
  isFormVisible: false,

  toggleVisibility: function() {
    this.toggleProperty('isFormVisible');
  },

  didInsertElement: function() {
    this.$().hide().slideDown('slow');
  },

  willDestroyElement: function() {
    var clone = this.$().clone();
    this.$().replaceWith(clone);
    clone.fadeOut('slow')
  }
});

App.CommentContainerView = Ember.View.extend({
  templateName: 'comment-view',

  didInsertElement: function() {
    this.$().hide().slideDown();
  }
})

// Create new post text field. Separate view to be able to bind events
App.CommentPostView = Ember.View.extend(Ember.TargetActionSupport, {
  tagName: "a",

  click: function() {
    this.triggerAction();
  }
})

// Text field to post a comment. Separate view to make it hideable
App.CommentForm = Ember.View.extend({
  // I'd no success to use isVisibleBinding property...
  classNameBindings: 'isVisible visible:invisible',
  body: '',

  isVisible: function() {
    return this.get('parentView.isFormVisible') == true;
  }.property('parentView.isFormVisible'),

  autoFocus: function () {
    if (this.get('parentView.isFormVisible') == true) {
      this.$().hide().show("fast");
      this.$('input').focus();
    }
  }.observes('parentView.isFormVisible'),

  submitComment: function() {
    if (this.body) {
      // XXX: rather strange bit of code here -- potentially a defect
      var post = this.bindingContext.content || this.bindingContext;
      App.commentsController.createComment(post, this.body)
      this.set('parentView.isFormVisible', false)
      this.set('body', '')
    }
  },

  // XXX: this is a dup of App.PostContainerView.toggleVisibility()
  // function. I just do not know how to access it from UI bindings
  toggleVisibility: function() {
    this.toggleProperty('parentView.isFormVisible');
  }
});

// Create new post text field. Separate view to be able to bind events
App.CreateCommentView = Ember.TextField.extend(Ember.TargetActionSupport, {
  attributeBindings: ['class'],

  insertNewline: function() {
    this.triggerAction();
  }
})

// Separate page for a single post
App.OnePostController = Ember.ObjectController.extend();
App.OnePostView = Ember.View.extend({
  templateName: 'a-post',
  isFormVisible: false,

  toggleVisibility: function(){
    this.toggleProperty('isFormVisible');
  }
});

App.Comment = Ember.Object.extend({
  body: null,
  createdAt: null,
  user: null
});

App.CommentsController = Ember.ArrayController.extend({
  createComment: function(post, body) {
    var comment = App.Comment.create({
      body: body,
      post_id: post.id
    });

    $.ajax({
      url: '/v1/comments',
      type: 'post',
      data: { body: body, post_id: post.id }, // XXX: we've already defined a model above
      context: comment,
      success: function(response) {
        this.setProperties(response);
        // We do not insert comment right now, but wait for a socket event
        // post.comments.pushObject(comment)
      }
    })
    return comment;
  }
})
App.commentsController = App.CommentsController.create()

App.Post = Ember.Object.extend({
  body: null,
  createdAt: null,
  updatedAt: null,
  comments: [],
  user: null,

  createdAgo: function() {
    return moment(this.get('createdAt')).fromNow();
  }.property('createdAt')
});

App.PostsController = Ember.ArrayController.extend(Ember.SortableMixin, {
  content: [],
  body: '',

  sortProperties: ['updatedAt'],
  sortAscending: false,

  // XXX: a bit strange having this method here.
  submitPost: function() {
    if (this.body) {
      App.postsController.createPost(this.body);
      this.set('body', '')
    }
  },

  removePost: function(propName, value) {
    var obj = this.findProperty(propName, value);
    this.removeObject(obj);
  },

  createPost: function(body) {
    var post = App.Post.create({
      body: body
    });

    $.ajax({
      url: '/v1/posts',
      type: 'post',
      data: { body: body }, // XXX: we've already defined a model above
      context: post,
      success: function(response) {
        this.setProperties(response);
        // We do not insert post right now, but wait for a socket event
        // App.postsController.insertAt(0, post)
      }
    })
    return post;
  },

  findAll: function() {
    this.set('content', [])

    $.ajax({
      url: '/v1/timeline/anonymous',
      dataType: 'jsonp',
      context: this,
      success: function(response){
        response.posts.forEach(function(attrs) {
          var post = App.Post.create(attrs)
          this.addObject(post)
        }, this)
      }
    })
    return this
  },

  findOne: function(postId) {
    var post = App.Post.create({
      id: postId
    });

    $.ajax({
      url: '/v1/posts/' + postId,
      dataType: 'jsonp',
      context: post,
      success: function(response){
        this.setProperties(response)
      }
    })
    return post;
  }
})
App.postsController = App.PostsController.create()

App.Router = Ember.Router.extend({
  // enableLogging: true,

  root: Ember.Route.extend({
    posts: Ember.Route.extend({
      route: '/',

      showPost: Ember.Route.transitionTo('aPost'),
      showAllPosts: Ember.Route.transitionTo('posts'),

      connectOutlets: function(router){
        router.get('applicationController').connectOutlet('posts', App.postsController.findAll());
      }
    }),

    aPost: Ember.Route.extend({
      route: '/:postId',

      showAllPosts: Ember.Route.transitionTo('posts'),

      connectOutlets: function(router, context) {
        router.get('applicationController').connectOutlet('onePost', context);
      },

      serialize: function(router, context){
        return {postId: context.get('id')}
      },

      deserialize: function(router, urlParams) {
        return App.postsController.findOne(urlParams.postId);
      }
    })
  })
});

App.initialize();

<|endoftext|>


<commit_before>$(document).ready(function() {

    $(".view_more_comments").on("click",function() {

        var avatar = $(this).data('avatar');

        try {

            var numOfComments = $(".load_comment").find("div#show_comment");

            alert(numOfComments.size());

            $.ajax({

            url:'/comment',
            type:'GET',
            data:{'offset': 10},

            success: function(data) {

                for(i = 0 ; i < data.comments.length; i++)
                {
                    var comments = data.comments[i];

                    console.log("data", data.comments[i]);

                    $('#comment-count').html(' ' + numOfComments);

                     var newComment = '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '' + comments.comments + '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '

';

                     $('.load_comment').last().append(newComment);
                     $('#new-comment-field').val('');

                }
            }

        });

        } catch (e) {

            console.log(e);
        }

        return false;
    });

    $('.comment-submit').on('click', function() {

        var comment = $('#new-comment-field').val();
        var avatar = $(this).data('avatar');
        var comment_count = parseInt($(this).data('comment-count')) + 1;
        var token = $(this).data('token');

        var url = '/comment';
        var user_id = $('#user_id').val();
        var episode_id = $('#episode_id').val();

        var data = {
            parameter: {
                _token: token,
                episode_id: episode_id,
                comment: comment
            }
        }
        if (comment.length > 0) {
            //Process AJAX request
            $.ajax({
                url: url,
                type: 'POST',
                data: data.parameter,

                success: function(response) {

                    switch (response.status_code) {
                        case 200:

                            //Increment comment upon successful submission
                            $('#comment-count').html(' ' + comment_count);

                            var newComment = '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '' + comment + '';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '

';

                            $('.load_comment').last().append(newComment);
                            $('#new-comment-field').val('');

                            break;

                        default:
                            return false;
                    }
                }
            });
        }

        return false;
    });

});
<commit_msg>[feature #113846287] Load previous comments and append them to existing comments<commit_after>$(document).ready(function() {

    $(".view_more_comments").on("click",function() {

        var avatar = $(this).data('avatar');

        try {

            var numOfComments = $(".load_comment").find("div#show_comment");

            $.ajax({

            url:'/comment',
            type:'GET',
            data:{'offset': 10},

            success: function(data) {

                for (i = 0 ; i < data.comments.length; i++)
                {
                    var comments = data.comments[i];

                    console.log("data", data.comments[i]);

                    $('#comment-count').html(' ' + numOfComments);

                     var newComment = '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '' + comments.comments + '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '

';

                     $('.load_comment').last().append(newComment);
                     $('#new-comment-field').val('');

                }
            }

        });

        } catch (e) {

            console.log(e);
        }

        return false;
    });

    $('.comment-submit').on('click', function() {

        var comment = $('#new-comment-field').val();
        var avatar = $(this).data('avatar');
        var comment_count = parseInt($(this).data('comment-count')) + 1;
        var token = $(this).data('token');

        var url = '/comment';
        var user_id = $('#user_id').val();
        var episode_id = $('#episode_id').val();

        var data = {
            parameter: {
                _token: token,
                episode_id: episode_id,
                comment: comment
            }
        }
        if (comment.length > 0) {
            //Process AJAX request
            $.ajax({
                url: url,
                type: 'POST',
                data: data.parameter,

                success: function(response) {

                    switch (response.status_code) {
                        case 200:

                            //Increment comment upon successful submission
                            $('#comment-count').html(' ' + comment_count);

                            var newComment = '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '' + comment + '';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '

';

                            $('.load_comment').last().append(newComment);
                            $('#new-comment-field').val('');

                            break;

                        default:
                            return false;
                    }
                }
            });
        }

        return false;
    });

});
<|endoftext|>


<commit_before>// TODO: a separate JS file for this since it's needed at all times
// and the editor is not (see editor.js vs. content.js). Letting people
// edit tends to sneak into sites so much that we might not bother
// with the distinction much in practice

apos.widgetPlayers.twitter = function($widget) {
  var account = $widget.attr('data-account');
  $.getJSON(
    // Note the trailing ? is significant. It tells jQuery to automatically
    // create a JSONP callback function and obtain the result via a cross-domain
    // script tag so we can talk to twitter in older browsers without a
    // security error
    '/apos-twitter/feed/' + account + '?count=5',
    function(tweets) {
      var $tweets = $widget.find('.apos-tweets');
      if (!tweets.length) {
        return;
      }
      $tweets.find('.apos-tweet:not(.apos-template)').remove();
      _.each(tweets, function(tweet) {
        var text = tweet.text;
        var $li = $tweets.find('.apos-tweet.apos-template').clone();
        var when = parseTwitterDate(tweet.created_at);
        // Months start at zero for use in arrays.
        var month = when.getMonth() + 1;
        if (month < 10) {
          month = '0' + month;
        }
        var day = when.getDate();
        if (day < 10) {
          day = '0' + day;
        }
        when = '' + month + '/' + day + '';
        $li.find('.apos-tweet-date').append(when);
        // Linkify URLs
        text = text.replace(/(https?\:\/\/[^ ]\S+)/g, '$1');
        // Tweets are pre-escaped for some reason in the JSON responses
        $li.find('.apos-tweet-text').html(text);
        $li.removeClass('apos-template');
        $tweets.append($li);
      });
    }
  );

  // Per http://stackoverflow.com/questions/3243546/problem-with-javascript-date-function-in-ie-7-returns-nan
  // Without this IE bombs
  function parseTwitterDate(str) {
    console.log(str);
    var v = str.split(' ');
    return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
  }
};

<commit_msg>Run quiet<commit_after>// TODO: a separate JS file for this since it's needed at all times
// and the editor is not (see editor.js vs. content.js). Letting people
// edit tends to sneak into sites so much that we might not bother
// with the distinction much in practice

apos.widgetPlayers.twitter = function($widget) {
  var account = $widget.attr('data-account');
  $.getJSON(
    // Note the trailing ? is significant. It tells jQuery to automatically
    // create a JSONP callback function and obtain the result via a cross-domain
    // script tag so we can talk to twitter in older browsers without a
    // security error
    '/apos-twitter/feed/' + account + '?count=5',
    function(tweets) {
      var $tweets = $widget.find('.apos-tweets');
      if (!tweets.length) {
        return;
      }
      $tweets.find('.apos-tweet:not(.apos-template)').remove();
      _.each(tweets, function(tweet) {
        var text = tweet.text;
        var $li = $tweets.find('.apos-tweet.apos-template').clone();
        var when = parseTwitterDate(tweet.created_at);
        // Months start at zero for use in arrays.
        var month = when.getMonth() + 1;
        if (month < 10) {
          month = '0' + month;
        }
        var day = when.getDate();
        if (day < 10) {
          day = '0' + day;
        }
        when = '' + month + '/' + day + '';
        $li.find('.apos-tweet-date').append(when);
        // Linkify URLs
        text = text.replace(/(https?\:\/\/[^ ]\S+)/g, '$1');
        // Tweets are pre-escaped for some reason in the JSON responses
        $li.find('.apos-tweet-text').html(text);
        $li.removeClass('apos-template');
        $tweets.append($li);
      });
    }
  );

  // Per http://stackoverflow.com/questions/3243546/problem-with-javascript-date-function-in-ie-7-returns-nan
  // Without this IE bombs
  function parseTwitterDate(str) {
    var v = str.split(' ');
    return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
  }
};

<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Bars', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
          var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "100%");

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);

          // define render function
          scope.render = function(data){
            // remove all previous items before render
            svg.selectAll("*").remove();

            // setup variables
            var width, height, max;
            width = d3.select(iElement[0])[0][0].offsetWidth - 20;
              // 20 is for margins and can be changed
            height = scope.data.length * 35;
              // 35 = 30(bar height) + 5(margin between bars)
            max = 98;
              // this can also be found dynamically when the data is not static
              // max = Math.max.apply(Math, _.map(data, ((val)-> val.count)))

            // set the height based on the calculations above
            svg.attr('height', height);

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .attr("height", 30) // height of each bar
                .attr("width", 0) // initial width of 0 for transition
                .attr("x", 10) // half of the 20 side margin specified above
                .attr("y", function(d, i){
                  return i * 35;
                }) // height + margin between bars
                .transition()
                  .duration(1000) // time of duration
                  .attr("width", function(d){
                    return d.value/(max/width);
                  }); // width based on scale

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());

// -- by e-Coucou

(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Lines', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          moyn: "=",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
        // Dimensions.
        var margin = {top: 20, right: 20, bottom: 30, left: 40},
            width = 800 - margin.right-margin.left,
            height = 400 - margin.top - margin.bottom;
        // creation du contenair
        var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "100%")
//              .attr("width", width + margin.left + margin.right)
              .attr("height", height + margin.top + margin.bottom)
//              .attr("height", "100%")
            .append("g")
              .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
console.log(d3.select(iElement[0])[0][0].offsetWidth);
console.log(d3.select(iElement[0])[0][0].offsetHeight);

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);
          // define render function
          scope.render = function(data,moyn){

            // setup variables
            var max,maxi, min,mini;
            var padding = 1;

            // accessor
            function x(d,i) { return i * (width / data.length);}
            function y(d) { return (height - (d.value-min)/((max-min)/height)); }
            function h(d) { return ((d.value-min)/((max-min)/height));}

            // fonction
            function info(d,i) {
              var s_date = d.date.split('/');
              var s_heure = d.heure.split(':');
              var date_text = s_date[1]+'/'+s_date[0]+'\n'+s_heure[0]+':'+s_heure[1];
              label.text(Math.round(d.value*100)/100) ;
              var datac = [ { "x" : x(d,i), "y" : 20 }, { "x" : x(d,i), "y" : height } ];
              d3.selectAll(".curseur").remove();
              d3.selectAll(".date").remove();
              var datadate = [{"x" : x(d,i), "text":d.heure}];
              svg.append("text")
                 .data(datadate)
                 .attr("class", "date label")
                 .attr("text-anchor", "middle")
                 .attr("x",  function(d) {return d.x;} )
                 .attr("y", 0)
                 .text(function(d) {return date_text;});

              svg.append("path")
                .datum(datac)
                .attr("class", "curseur")
                .attr("d", curseur);
              }
            // remove all previous items before render
            svg.selectAll("*").remove();

//            console.log(height,width);
              // 20 is for margins and can be changed
//            width = 1160 ;//scope.data.length * 35;
//            width = 1000;
//            height = 450 ;
            if (data.length > 500 ) { padding = 0; } // no padding si trop de data
            maxi = Math.max.apply(Math, data.map(function(x) {return x.value; }));
            mini = Math.min.apply(Math, data.map(function(x) {return x.value; }));
//            console.log("max: ",maxi,"min: ",mini, "moyenne: ",scope.moyn);

            max = maxi + 0.07 * (maxi-mini);
            min = mini - 0.15 * (maxi-mini);

            // set the height based on the calculations above
            svg.attr('height', height)
               .attr('width',  width);

// Add the year label; the value is set on transition.
var label = svg.append("text")
    .attr("class", "year label")
    .attr("text-anchor", "end")
    .attr("y",  55)
    .attr("x", width)
    .text('VALEUR');

var curseur = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_min = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_max = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_moy = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

// Add a y-axis label.
var yScale = d3.scale.linear().domain([max, min]).range([0,height]),
    yAxis = d3.svg.axis().scale(yScale).orient("left");

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("mesure");

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .on("mouseover",function (d,i) { return info(d,i);})
                .attr("height", 0) // height of each bar
                .attr("width", width / data.length - padding)
                .attr("x", function(d,i) { return x(d, i);})  // height + margin between bars
                .attr("fill","yellow")
                .transition()
                  .duration(3000) // time of duration
                  .attr("stroke-width",0)
                  .attr("fill", function(d) {
                    var val = ((d.value -min)/((max-min)/16));
                    return "rgb(10, 160, " + val*16 + ")";
                    })
                  .attr("height", function (d) { return h(d); }) // half of the 20 side margin specified above
                  .attr("y", function (d) { return y(d);}); // width based on scale

            // position des repères
            var ordonne = height - (mini-min)/((max-min)/height);
            var datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_min").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_min);
            ordonne = height - (maxi-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_max").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_max);
            ordonne = height - (scope.moyn-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_moy").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_moy);

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());<commit_msg>width<commit_after>(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Bars', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
          var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "100%");

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);

          // define render function
          scope.render = function(data){
            // remove all previous items before render
            svg.selectAll("*").remove();

            // setup variables
            var width, height, max;
            width = d3.select(iElement[0])[0][0].offsetWidth - 20;
              // 20 is for margins and can be changed
            height = scope.data.length * 35;
              // 35 = 30(bar height) + 5(margin between bars)
            max = 98;
              // this can also be found dynamically when the data is not static
              // max = Math.max.apply(Math, _.map(data, ((val)-> val.count)))

            // set the height based on the calculations above
            svg.attr('height', height);

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .attr("height", 30) // height of each bar
                .attr("width", 0) // initial width of 0 for transition
                .attr("x", 10) // half of the 20 side margin specified above
                .attr("y", function(d, i){
                  return i * 35;
                }) // height + margin between bars
                .transition()
                  .duration(1000) // time of duration
                  .attr("width", function(d){
                    return d.value/(max/width);
                  }); // width based on scale

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());

// -- by e-Coucou

(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Lines', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          moyn: "=",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
        // Dimensions.
        var margin = {top: 20, right: 20, bottom: 30, left: 40},
            width = d3.select(iElement[0])[0][0].offsetWidth - margin.right-margin.left,
            height = 400 - margin.top - margin.bottom;
        // creation du conteneur
        var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "100%")
//              .attr("width", width + margin.left + margin.right)
              .attr("height", height + margin.top + margin.bottom)
//              .attr("height", "100%")
            .append("g")
              .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
console.log(d3.select(iElement[0])[0][0].offsetWidth);
console.log(d3.select(iElement[0])[0][0].offsetHeight);

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);
          // define render function
          scope.render = function(data,moyn){

            // setup variables
            var max,maxi, min,mini;
            var padding = 1;

            // accessor
            function x(d,i) { return i * (width / data.length);}
            function y(d) { return (height - (d.value-min)/((max-min)/height)); }
            function h(d) { return ((d.value-min)/((max-min)/height));}

            // fonction
            function info(d,i) {
              var s_date = d.date.split('/');
              var s_heure = d.heure.split(':');
              var date_text = s_date[1]+'/'+s_date[0]+'\n'+s_heure[0]+':'+s_heure[1];
              label.text(Math.round(d.value*100)/100) ;
              var datac = [ { "x" : x(d,i), "y" : 20 }, { "x" : x(d,i), "y" : height } ];
              d3.selectAll(".curseur").remove();
              d3.selectAll(".date").remove();
              var datadate = [{"x" : x(d,i), "text":d.heure}];
              svg.append("text")
                 .data(datadate)
                 .attr("class", "date label")
                 .attr("text-anchor", "middle")
                 .attr("x",  function(d) {return d.x;} )
                 .attr("y", 0)
                 .text(function(d) {return date_text;});

              svg.append("path")
                .datum(datac)
                .attr("class", "curseur")
                .attr("d", curseur);
              }
            // remove all previous items before render
            svg.selectAll("*").remove();

//            console.log(height,width);
              // 20 is for margins and can be changed
//            width = 1160 ;//scope.data.length * 35;
//            width = 1000;
//            height = 450 ;
            if (data.length > 500 ) { padding = 0; } // no padding si trop de data
            maxi = Math.max.apply(Math, data.map(function(x) {return x.value; }));
            mini = Math.min.apply(Math, data.map(function(x) {return x.value; }));
//            console.log("max: ",maxi,"min: ",mini, "moyenne: ",scope.moyn);

            max = maxi + 0.07 * (maxi-mini);
            min = mini - 0.15 * (maxi-mini);

            // set the height based on the calculations above
            svg.attr('height', height)
               .attr('width',  width);

// Add the year label; the value is set on transition.
var label = svg.append("text")
    .attr("class", "year label")
    .attr("text-anchor", "end")
    .attr("y",  55)
    .attr("x", width)
    .text('VALEUR');

var curseur = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_min = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_max = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_moy = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

// Add a y-axis label.
var yScale = d3.scale.linear().domain([max, min]).range([0,height]),
    yAxis = d3.svg.axis().scale(yScale).orient("left");

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("mesure");

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .on("mouseover",function (d,i) { return info(d,i);})
                .attr("height", 0) // height of each bar
                .attr("width", width / data.length - padding)
                .attr("x", function(d,i) { return x(d, i);})  // height + margin between bars
                .attr("fill","yellow")
                .transition()
                  .duration(3000) // time of duration
                  .attr("stroke-width",0)
                  .attr("fill", function(d) {
                    var val = ((d.value -min)/((max-min)/16));
                    return "rgb(10, 160, " + val*16 + ")";
                    })
                  .attr("height", function (d) { return h(d); }) // half of the 20 side margin specified above
                  .attr("y", function (d) { return y(d);}); // width based on scale

            // position des repères
            var ordonne = height - (mini-min)/((max-min)/height);
            var datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_min").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_min);
            ordonne = height - (maxi-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_max").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_max);
            ordonne = height - (scope.moyn-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_moy").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_moy);

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());<|endoftext|>


<commit_before>window.sendMessage = function (message, type) {
  window.socket.send(JSON.stringify({ 'message': message, 'type': type }));
};<commit_msg>this file is unnecessary<commit_after><|endoftext|>