<commit_before>import { chai } from 'meteor/practicalmeteor:chai';
import chaiAsPromised from 'chai-as-promised';
import { createDummyUser, createDummyPost, createDummyComment, createDummyConversation, createDummyMessage } from '../../../testing/utils.js'
import { performSubscriptionAction } from '../../subscriptions/mutations.js';

import Users from 'meteor/vulcan:users';
import { Comments } from '../comments'
import Notifications from './collection.js';
import { waitUntilCallbacksFinished } from 'meteor/vulcan:core';

chai.should();
chai.use(chaiAsPromised);

describe('performSubscriptionAction', async () => {
  // it("correctly modifies the users subscribedItems when subscribing", async () => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //
  //   const response = performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  //   response.subscribedItems.Posts[0].itemId.should.be.equal(post._id);
  //   response.subscribedItems.Posts.should.have.lengthOf(1);
  // });
  // it("correctly modifies the users subscribedItems when unsubscribing", async (done) => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //   const unsubscribeTestCallback = async function(action, collection, itemId, updatedUser) {
  //     const response = performSubscriptionAction('unsubscribe', Posts, post._id, user)
  //     response.subscribedItems.Posts.should.be.empty;
  //   }
  //   addTestToCallbackOnce('users.subscribe.async', unsubscribeTestCallback, done);
  //   performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  // });
  // it("correctly modifies the subscribers of Posts when subscribing", async () => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //
  //   performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  //   const updatedPost = await Posts.findOne({_id: post._id});
  //
  //   updatedPost.subscribers.should.be.deep.equal([otherUser._id, user._id]);
  //   updatedPost.subscriberCount.should.equal(2);
  // });
  // it("correctly modifies the subscribers of Posts when unsubscribing", async (done) => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //
  //   const unsubscribeTestCallback = async function(action, collection, itemId, updatedUser, result) {
  //     const updatedPost = await Posts.findOne({_id: post._id});
  //     updatedPost.subscribers.should.have.lengthOf(1);
  //     updatedPost.subscriberCount.should.equal(1);
  //   }
  //   performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  //   addTestToCallbackOnce('users.unsubscribe.async', unsubscribeTestCallback, done);
  //   performSubscriptionAction('unsubscribe', Posts, post._id, otherUser)
  // });
});

describe('notification generation', async () => {
  it("generates notifications for new posts", async (done) => {
    const user = await createDummyUser()
    const otherUser = await createDummyUser()
    performSubscriptionAction('subscribe', Users, user._id, otherUser)
    await createDummyPost(user);
    await waitUntilCallbacksFinished();

    const notifications = await Notifications.find({userId: otherUser._id}).fetch();
    notifications.should.have.lengthOf(1);
    notifications[0].should.have.property('type', 'newPost');
    done();
  });
  it("generates notifications for new comments to post", async (done) => {
    const user = await createDummyUser()
    const otherUser = await createDummyUser()
    const post = await createDummyPost(user);
    await createDummyComment(otherUser, {postId: post._id});
    await waitUntilCallbacksFinished();

    const notifications = await Notifications.find({userId: user._id}).fetch();
    notifications.should.have.lengthOf(1);
    notifications[0].should.have.property('type', 'newComment');
    done();
  });
  it("generates notifications for comment replies", async (done) => {
    // user1 makes a post
    // user2 comments on it
    // user3 subscribes to user2's comment
    // user1 replies to user2
    //
    // Notifications:
    //   user1 notified of user2's comment
    //   user2 notified of user1's reply
    //   user3 notified of user1's reply

    const user1 = await createDummyUser()
    const user2 = await createDummyUser()
    const user3 = await createDummyUser()
    const post = await createDummyPost(user1);
    const comment = await createDummyComment(user2, {postId: post._id});
    performSubscriptionAction('subscribe', Comments, comment._id, user3)
    await waitUntilCallbacksFinished();
    await createDummyComment(user1, {postId: post._id, parentCommentId: comment._id});
    await waitUntilCallbacksFinished();

    const notifications1 = await Notifications.find({userId: user1._id}).fetch();
    const notifications2 = await Notifications.find({userId: user2._id}).fetch();
    const notifications3 = await Notifications.find({userId: user3._id}).fetch();

    notifications1.should.have.lengthOf(1);
    // FIXME: After shuffling this test around, getting wrong documentIds here
    // (is this supposed to be ID of the comment, or of the thing it's a reply
    // to?) Possibly this was assigning the correct ID all along, but the test
    // wasn't actually running like it was supposed to.
    //notifications1[0].should.not.have.property('documentId', comment._id);
    notifications1[0].should.have.property('type', 'newComment');

    notifications2.should.have.lengthOf(1);
    //notifications2[0].should.have.property('documentId', comment._id);
    notifications2[0].should.have.property('type', 'newReplyToYou');

    notifications3.should.have.lengthOf(1);
    //notifications3[0].should.have.property('documentId', comment._id);
    notifications3[0].should.have.property('type', 'newReply');
    done();
  });
  it("generates notifications for new private messages", async (done) => {
    const user = await createDummyUser()
    const otherUser = await createDummyUser()
    const conversation = await createDummyConversation(user, {participantIds: [user._id, otherUser._id]});
    const message1 = await createDummyMessage(user, {conversationId: conversation._id});
    await createDummyMessage(otherUser, {conversationId: conversation._id});
    await waitUntilCallbacksFinished();

    const notifications = await Notifications.find({userId: otherUser._id}).fetch();

    notifications.should.have.lengthOf(1);
    notifications[0].should.have.property('documentId', message1._id);
    notifications[0].should.have.property('type', 'newMessage');
    done();
  });
});
<commit_msg>add waitCallbacks<commit_after>import { chai } from 'meteor/practicalmeteor:chai';
import chaiAsPromised from 'chai-as-promised';
import { createDummyUser, createDummyPost, createDummyComment, createDummyConversation, createDummyMessage } from '../../../testing/utils.js'
import { performSubscriptionAction } from '../../subscriptions/mutations.js';

import Users from 'meteor/vulcan:users';
import { Comments } from '../comments'
import Notifications from './collection.js';
import { waitUntilCallbacksFinished } from 'meteor/vulcan:core';

chai.should();
chai.use(chaiAsPromised);

describe('performSubscriptionAction', async () => {
  // it("correctly modifies the users subscribedItems when subscribing", async () => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //
  //   const response = performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  //   response.subscribedItems.Posts[0].itemId.should.be.equal(post._id);
  //   response.subscribedItems.Posts.should.have.lengthOf(1);
  // });
  // it("correctly modifies the users subscribedItems when unsubscribing", async (done) => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //   const unsubscribeTestCallback = async function(action, collection, itemId, updatedUser) {
  //     const response = performSubscriptionAction('unsubscribe', Posts, post._id, user)
  //     response.subscribedItems.Posts.should.be.empty;
  //   }
  //   addTestToCallbackOnce('users.subscribe.async', unsubscribeTestCallback, done);
  //   performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  // });
  // it("correctly modifies the subscribers of Posts when subscribing", async () => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //
  //   performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  //   const updatedPost = await Posts.findOne({_id: post._id});
  //
  //   updatedPost.subscribers.should.be.deep.equal([otherUser._id, user._id]);
  //   updatedPost.subscriberCount.should.equal(2);
  // });
  // it("correctly modifies the subscribers of Posts when unsubscribing", async (done) => {
  //   const user = await createDummyUser()
  //   const otherUser = await createDummyUser()
  //   const post = await createDummyPost(user)
  //
  //   const unsubscribeTestCallback = async function(action, collection, itemId, updatedUser, result) {
  //     const updatedPost = await Posts.findOne({_id: post._id});
  //     updatedPost.subscribers.should.have.lengthOf(1);
  //     updatedPost.subscriberCount.should.equal(1);
  //   }
  //   performSubscriptionAction('subscribe', Posts, post._id, otherUser)
  //   addTestToCallbackOnce('users.unsubscribe.async', unsubscribeTestCallback, done);
  //   performSubscriptionAction('unsubscribe', Posts, post._id, otherUser)
  // });
});

describe('notification generation', async () => {
  it("generates notifications for new posts", async (done) => {
    const user = await createDummyUser()
    const otherUser = await createDummyUser()
    performSubscriptionAction('subscribe', Users, user._id, otherUser)
    await waitUntilCallbacksFinished();
    await createDummyPost(user);
    await waitUntilCallbacksFinished();

    const notifications = await Notifications.find({userId: otherUser._id}).fetch();
    notifications.should.have.lengthOf(1);
    notifications[0].should.have.property('type', 'newPost');
    done();
  });
  it("generates notifications for new comments to post", async (done) => {
    const user = await createDummyUser()
    const otherUser = await createDummyUser()
    const post = await createDummyPost(user);
    await waitUntilCallbacksFinished();
    await createDummyComment(otherUser, {postId: post._id});
    await waitUntilCallbacksFinished();

    const notifications = await Notifications.find({userId: user._id}).fetch();
    notifications.should.have.lengthOf(1);
    notifications[0].should.have.property('type', 'newComment');
    done();
  });
  it("generates notifications for comment replies", async (done) => {
    // user1 makes a post
    // user2 comments on it
    // user3 subscribes to user2's comment
    // user1 replies to user2
    //
    // Notifications:
    //   user1 notified of user2's comment
    //   user2 notified of user1's reply
    //   user3 notified of user1's reply

    const user1 = await createDummyUser()
    const user2 = await createDummyUser()
    const user3 = await createDummyUser()
    const post = await createDummyPost(user1);
    await waitUntilCallbacksFinished();
    const comment = await createDummyComment(user2, {postId: post._id});
    await waitUntilCallbacksFinished();
    performSubscriptionAction('subscribe', Comments, comment._id, user3)
    await waitUntilCallbacksFinished();
    await createDummyComment(user1, {postId: post._id, parentCommentId: comment._id});
    await waitUntilCallbacksFinished();

    const notifications1 = await Notifications.find({userId: user1._id}).fetch();
    const notifications2 = await Notifications.find({userId: user2._id}).fetch();
    const notifications3 = await Notifications.find({userId: user3._id}).fetch();

    notifications1.should.have.lengthOf(1);
    // FIXME: After shuffling this test around, getting wrong documentIds here
    // (is this supposed to be ID of the comment, or of the thing it's a reply
    // to?) Possibly this was assigning the correct ID all along, but the test
    // wasn't actually running like it was supposed to.
    //notifications1[0].should.not.have.property('documentId', comment._id);
    notifications1[0].should.have.property('type', 'newComment');

    notifications2.should.have.lengthOf(1);
    //notifications2[0].should.have.property('documentId', comment._id);
    notifications2[0].should.have.property('type', 'newReplyToYou');

    notifications3.should.have.lengthOf(1);
    //notifications3[0].should.have.property('documentId', comment._id);
    notifications3[0].should.have.property('type', 'newReply');
    done();
  });
  it("generates notifications for new private messages", async (done) => {
    const user = await createDummyUser()
    const otherUser = await createDummyUser()
    const conversation = await createDummyConversation(user, {participantIds: [user._id, otherUser._id]});
    const message1 = await createDummyMessage(user, {conversationId: conversation._id});
    await createDummyMessage(otherUser, {conversationId: conversation._id});
    await waitUntilCallbacksFinished();

    const notifications = await Notifications.find({userId: otherUser._id}).fetch();

    notifications.should.have.lengthOf(1);
    notifications[0].should.have.property('documentId', message1._id);
    notifications[0].should.have.property('type', 'newMessage');
    done();
  });
});
<|endoftext|>


<commit_before>//Import Artist List as this can be huge

var artists = getArtistsArray();

function Player() // {{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    // Get the focus to the visible playlist first
    //window._SBShowMainLibrary();

    // FIXME: need to test that we're playing - gMM.status.state
    // interval (seconds)
    function seek(interval, direction)
    {
        if (!gMM.playbackControl)
            return;

        interval = interval * 1000;

        let min = 0;
        let max = gMM.playbackControl.duration;

        let position = gMM.playbackControl.position + (direction ? interval : -interval);

        gMM.playbackControl.position = Math.min(Math.max(position, min), max);
    }

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// MAPPINGS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    mappings.add([modes.PLAYER],
        ["x"], "Play track",
        function () { player.play(); });

    mappings.add([modes.PLAYER],
        ["z"], "Previous track",
        function () { player.previous(); });

    mappings.add([modes.PLAYER],
        ["c"], "Pause/Unpause track",
        function () { player.togglePlayPause(); });

    mappings.add([modes.PLAYER],
        ["b"], "Next track",
        function () { player.next(); });

    mappings.add([modes.PLAYER],
        ["v"], "Stop track",
        function () { player.stop(); });

    mappings.add([modes.PLAYER],
        ["f"], "Filter Library",
        function () { commandline.open(":", "filter ", modes.EX); });

    mappings.add([modes.PLAYER],
        ["s"], "Toggle Shuffle",
        function () { player.toggleShuffle(); });

    mappings.add([modes.PLAYER],
        ["r"], "Toggle Repeat",
        function () { player.toggleRepeat(); });

    mappings.add([modes.PLAYER],
        ["h"], "Seek -10s",
        function (count) { player.seekBackward(Math.max(1, count) * 10); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
        ["l"], "Seek +10s",
        function (count) { player.seekForward(Math.max(1, count) * 10); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
        ["H"], "Seek -1m",
        function (count) { player.seekBackward(Math.max(1, count) * 60); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
        ["L"], "Seek +1m",
        function (count) { player.seekForward(Math.max(1, count) * 60); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
         ["=", "+"], "Increase Volume by 10%",
         function () { player.increaseVolume(); });

    mappings.add([modes.PLAYER],
         ["-"], "Decrease Volume by 10%",
         function () { player.decreaseVolume(); });

    ////////////////// ///////////////////////////////////////////////////////////}}}
    ////////////////////// COMMANDS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    // TODO: presumably this will eventually just filter the library view like cmus? --djk
    commands.add(["f[ilter]"],
        "Filter and play tracks",
        function (args)
        {
            //Store the old view
            //let prev_view = gMM.status.view;
            let library = LibraryUtils.mainLibrary;
            let mainView = library.createView();
            let sqncr = gMM.sequencer;
            let customProps = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"]
                                  .createInstance(Ci.sbIMutablePropertyArray);

            //args
            switch (args.length)
            {
                case 3:
                    customProps.appendProperty(SBProperties.trackName, args[2].toString());
                case 2:
                    customProps.appendProperty(SBProperties.albumName, args[1].toString());
                case 1:
                    customProps.appendProperty(SBProperties.artistName, args[0].toString());
                    break;
                default:
                    break;
            }

            sqncr.playView(mainView, mainView.getIndexForItem(library.getItemsByProperties(customProps).queryElementAt(0, Ci.sbIMediaItem)));
        },
        {
            argCount: "+",
            completer: function (context, args) completion.song(context, args)
        });

    // TODO: better off as a single command, or cmus compatible E.g. :player-next? --djk
    commands.add(["playerp[lay]"],
        "Play track",
        function () { player.play(); });

    commands.add(["playerpa[use]"],
        "Pause/unpause track",
        function () { player.togglePlayPause(); });

    commands.add(["playern[ext]"],
        "Play next track",
        function () { player.next(); });

    commands.add(["playerpr[ev]"],
        "Play previous track",
        function () { player.previous(); });

    commands.add(["players[top]"],
        "Stop track",
        function () { player.stop(); });

    commands.add(["vol[ume]"],
        "Set the volume",
        function (args)
        {
            let arg = args[0];

            if (!/^[+-]?\d+$/.test(arg))
            {
                liberator.echoerr("E488: Trailing characters");
                return;
            }

            let level = parseInt(arg, 10) / 100;

            if (/^[+-]/.test(arg))
                level = player.volume + level;

            player.volume = Math.min(Math.max(level, 0), 1);
        },
        { argCount: 1 });

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// PUBLIC SECTION //////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    return {

        // TODO: check bounds and round, 0 - 1 or 0 - 100?
        get volume() gMM.volumeControl.volume,
        set volume(value)
        {
            gMM.volumeControl.volume = value;
        },

        play: function play()
        {
            gMM.sequencer.play();
        },

        stop: function stop()
        {
            gMM.sequencer.stop();
        },

        next: function next()
        {
            gSongbirdWindowController.doCommand("cmd_control_next");
        },

        previous: function previous()
        {
            gSongbirdWindowController.doCommand("cmd_control_previous");
        },

        togglePlayPause: function togglePlayPause()
        {
            gSongbirdWindowController.doCommand("cmd_control_playpause");
        },

        toggleShuffle: function toggleShuffle()
        {
            if (gMM.sequencer.mode != gMM.sequencer.MODE_SHUFFLE)
                gMM.sequencer.mode = gMM.sequencer.MODE_SHUFFLE;
            else
                gMM.sequencer.mode = gMM.sequencer.MODE_FORWARD;
        },

        // FIXME: not really toggling - good enough for now.
        toggleRepeat: function toggleRepeat()
        {
            switch (gMM.sequencer.repeatMode)
            {
                case gMM.sequencer.MODE_REPEAT_NONE:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_ONE;
                    break;
                case gMM.sequencer.MODE_REPEAT_ONE:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_ALL;
                    break;
                case gMM.sequencer.MODE_REPEAT_ALL:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_NONE;
                    break;
                default:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_NONE;
                    break;
            }
        },

        seekForward: function seekForward(interval)
        {
            seek(interval, true);
        },

        seekBackward: function seekBackward(interval)
        {
            seek(interval, false);
        },

        //FIXME: 10% ?
        increaseVolume: function increaseVolume()
        {
            gMM.volumeControl.volume = gMM.volumeControl.volume * 1.1;
        },

        decreaseVolume: function decreaseVolume()
        {
            if (gMM.volumeControl.volume == 0)
                gMM.volumeControl.volume = 0.1;
            else
                gMM.volumeControl.volume = gMM.volumeControl.volume * 0.9;
        }
    };
    //}}}
} // }}}

function getArtists()
{
    return this.artists;
}

function getArtistsArray()
{
    var list = LibraryUtils.mainLibrary;

    //  Create an enumeration listener to count each item
    var listener = {
        count: 0,
        onEnumerationBegin: function (aMediaList) {
            this.count = 0;
        },
        onEnumeratedItem: function (aMediaList, aMediaItem) {
            this.count++;
        },
        onEnumerationEnd: function (aMediaList, aStatusCode) {}
    };

    var artistCounts = {};
    var artists = list.getDistinctValuesForProperty(SBProperties.artistName);
    var artist;
    var artistArray = [];
    var i = 0;
    // Count the number of media items for each distinct artist
    while (artists.hasMore())
    {
        artist = artists.getNext();
        artistArray[i] = [artist, artist];
        list.enumerateItemsByProperty(SBProperties.artistName,
            artist,
            listener,
            Ci.sbIMediaList.ENUMERATIONTYPE_LOCKING);
        artistCounts[artist] = listener.count;
        i++;
    }

    //liberator.dump("Count : "+artistCounts.toSource());
    return artistArray;
}

function getAlbums(artist)
{
    var list = LibraryUtils.mainLibrary;
    var albumArray = [], returnArray = [];
    var items = list.getItemsByProperty(SBProperties.artistName, artist).enumerate();
    var i = 0, j = 0;

    while (items.hasMoreElements())
    {
        album = items.getNext().getProperty(SBProperties.albumName);
        albumArray[i] = [album, album];

        if (i == 0)
        {
            returnArray[j] = albumArray[i];
            j++;
        }
        else if (albumArray[i-1].toString() != albumArray[i].toString())
        {
             returnArray[i] = albumArray[i];
             j++;
        }
        i++;
    }

    return returnArray;
}

function getTracks(artist, album)
{
    var list = LibraryUtils.mainLibrary;
    var tracksArray = [];
    var pa = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"]
                 .createInstance(Ci.sbIMutablePropertyArray);
    var i = 0;

    pa.appendProperty(SBProperties.artistName, artist.toString());
    pa.appendProperty(SBProperties.albumName, album.toString());
    var items = list.getItemsByProperties(pa).enumerate();

    while (items.hasMoreElements())
    {
        track = items.getNext().getProperty(SBProperties.trackName);
        tracksArray[i] = [track, track];
        i++;
    }

    return tracksArray;
}

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>Fixed play() to play first track of the visible view.<commit_after>//Import Artist List as this can be huge

var artists = getArtistsArray();

function Player() // {{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    // Get the focus to the visible playlist first
    //window._SBShowMainLibrary();

    // FIXME: need to test that we're playing - gMM.status.state
    // interval (seconds)
    function seek(interval, direction)
    {
        if (!gMM.playbackControl)
            return;

        interval = interval * 1000;

        let min = 0;
        let max = gMM.playbackControl.duration;

        let position = gMM.playbackControl.position + (direction ? interval : -interval);

        gMM.playbackControl.position = Math.min(Math.max(position, min), max);
    }

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// MAPPINGS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    mappings.add([modes.PLAYER],
        ["x"], "Play track",
        function () { player.play(); });

    mappings.add([modes.PLAYER],
        ["z"], "Previous track",
        function () { player.previous(); });

    mappings.add([modes.PLAYER],
        ["c"], "Pause/Unpause track",
        function () { player.togglePlayPause(); });

    mappings.add([modes.PLAYER],
        ["b"], "Next track",
        function () { player.next(); });

    mappings.add([modes.PLAYER],
        ["v"], "Stop track",
        function () { player.stop(); });

    mappings.add([modes.PLAYER],
        ["f"], "Filter Library",
        function () { commandline.open(":", "filter ", modes.EX); });

    mappings.add([modes.PLAYER],
        ["s"], "Toggle Shuffle",
        function () { player.toggleShuffle(); });

    mappings.add([modes.PLAYER],
        ["r"], "Toggle Repeat",
        function () { player.toggleRepeat(); });

    mappings.add([modes.PLAYER],
        ["h"], "Seek -10s",
        function (count) { player.seekBackward(Math.max(1, count) * 10); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
        ["l"], "Seek +10s",
        function (count) { player.seekForward(Math.max(1, count) * 10); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
        ["H"], "Seek -1m",
        function (count) { player.seekBackward(Math.max(1, count) * 60); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
        ["L"], "Seek +1m",
        function (count) { player.seekForward(Math.max(1, count) * 60); },
        { flags: Mappings.flags.COUNT });

    mappings.add([modes.PLAYER],
         ["=", "+"], "Increase Volume by 10%",
         function () { player.increaseVolume(); });

    mappings.add([modes.PLAYER],
         ["-"], "Decrease Volume by 10%",
         function () { player.decreaseVolume(); });

    ////////////////// ///////////////////////////////////////////////////////////}}}
    ////////////////////// COMMANDS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    // TODO: presumably this will eventually just filter the library view like cmus? --djk
    commands.add(["f[ilter]"],
        "Filter and play tracks",
        function (args)
        {
            //Store the old view
            //let prev_view = gMM.status.view;
            let library = LibraryUtils.mainLibrary;
            let mainView = library.createView();
            let sqncr = gMM.sequencer;
            let customProps = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"]
                                  .createInstance(Ci.sbIMutablePropertyArray);

            //args
            switch (args.length)
            {
                case 3:
                    customProps.appendProperty(SBProperties.trackName, args[2].toString());
                case 2:
                    customProps.appendProperty(SBProperties.albumName, args[1].toString());
                case 1:
                    customProps.appendProperty(SBProperties.artistName, args[0].toString());
                    break;
                default:
                    break;
            }

            sqncr.playView(mainView, mainView.getIndexForItem(library.getItemsByProperties(customProps).queryElementAt(0, Ci.sbIMediaItem)));
        },
        {
            argCount: "+",
            completer: function (context, args) completion.song(context, args)
        });

    // TODO: better off as a single command, or cmus compatible E.g. :player-next? --djk
    commands.add(["playerp[lay]"],
        "Play track",
        function () { player.play(); });

    commands.add(["playerpa[use]"],
        "Pause/unpause track",
        function () { player.togglePlayPause(); });

    commands.add(["playern[ext]"],
        "Play next track",
        function () { player.next(); });

    commands.add(["playerpr[ev]"],
        "Play previous track",
        function () { player.previous(); });

    commands.add(["players[top]"],
        "Stop track",
        function () { player.stop(); });

    commands.add(["vol[ume]"],
        "Set the volume",
        function (args)
        {
            let arg = args[0];

            if (!/^[+-]?\d+$/.test(arg))
            {
                liberator.echoerr("E488: Trailing characters");
                return;
            }

            let level = parseInt(arg, 10) / 100;

            if (/^[+-]/.test(arg))
                level = player.volume + level;

            player.volume = Math.min(Math.max(level, 0), 1);
        },
        { argCount: 1 });

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// PUBLIC SECTION //////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    return {

        // TODO: check bounds and round, 0 - 1 or 0 - 100?
        get volume() gMM.volumeControl.volume,
        set volume(value)
        {
            gMM.volumeControl.volume = value;
        },

        play: function play()
        {
            gMM.sequencer.playView(SBGetBrowser().currentMediaListView, 0);
        },

        stop: function stop()
        {
            gMM.sequencer.stop();
        },

        next: function next()
        {
            gSongbirdWindowController.doCommand("cmd_control_next");
        },

        previous: function previous()
        {
            gSongbirdWindowController.doCommand("cmd_control_previous");
        },

        togglePlayPause: function togglePlayPause()
        {
            gSongbirdWindowController.doCommand("cmd_control_playpause");
        },

        toggleShuffle: function toggleShuffle()
        {
            if (gMM.sequencer.mode != gMM.sequencer.MODE_SHUFFLE)
                gMM.sequencer.mode = gMM.sequencer.MODE_SHUFFLE;
            else
                gMM.sequencer.mode = gMM.sequencer.MODE_FORWARD;
        },

        // FIXME: not really toggling - good enough for now.
        toggleRepeat: function toggleRepeat()
        {
            switch (gMM.sequencer.repeatMode)
            {
                case gMM.sequencer.MODE_REPEAT_NONE:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_ONE;
                    break;
                case gMM.sequencer.MODE_REPEAT_ONE:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_ALL;
                    break;
                case gMM.sequencer.MODE_REPEAT_ALL:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_NONE;
                    break;
                default:
                    gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_NONE;
                    break;
            }
        },

        seekForward: function seekForward(interval)
        {
            seek(interval, true);
        },

        seekBackward: function seekBackward(interval)
        {
            seek(interval, false);
        },

        //FIXME: 10% ?
        increaseVolume: function increaseVolume()
        {
            gMM.volumeControl.volume = gMM.volumeControl.volume * 1.1;
        },

        decreaseVolume: function decreaseVolume()
        {
            if (gMM.volumeControl.volume == 0)
                gMM.volumeControl.volume = 0.1;
            else
                gMM.volumeControl.volume = gMM.volumeControl.volume * 0.9;
        }
    };
    //}}}
} // }}}

function getArtists()
{
    return this.artists;
}

function getArtistsArray()
{
    var list = LibraryUtils.mainLibrary;

    //  Create an enumeration listener to count each item
    var listener = {
        count: 0,
        onEnumerationBegin: function (aMediaList) {
            this.count = 0;
        },
        onEnumeratedItem: function (aMediaList, aMediaItem) {
            this.count++;
        },
        onEnumerationEnd: function (aMediaList, aStatusCode) {}
    };

    var artistCounts = {};
    var artists = list.getDistinctValuesForProperty(SBProperties.artistName);
    var artist;
    var artistArray = [];
    var i = 0;
    // Count the number of media items for each distinct artist
    while (artists.hasMore())
    {
        artist = artists.getNext();
        artistArray[i] = [artist, artist];
        list.enumerateItemsByProperty(SBProperties.artistName,
            artist,
            listener,
            Ci.sbIMediaList.ENUMERATIONTYPE_LOCKING);
        artistCounts[artist] = listener.count;
        i++;
    }

    //liberator.dump("Count : "+artistCounts.toSource());
    return artistArray;
}

function getAlbums(artist)
{
    var list = LibraryUtils.mainLibrary;
    var albumArray = [], returnArray = [];
    var items = list.getItemsByProperty(SBProperties.artistName, artist).enumerate();
    var i = 0, j = 0;

    while (items.hasMoreElements())
    {
        album = items.getNext().getProperty(SBProperties.albumName);
        albumArray[i] = [album, album];

        if (i == 0)
        {
            returnArray[j] = albumArray[i];
            j++;
        }
        else if (albumArray[i-1].toString() != albumArray[i].toString())
        {
             returnArray[i] = albumArray[i];
             j++;
        }
        i++;
    }

    return returnArray;
}

function getTracks(artist, album)
{
    var list = LibraryUtils.mainLibrary;
    var tracksArray = [];
    var pa = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"]
                 .createInstance(Ci.sbIMutablePropertyArray);
    var i = 0;

    pa.appendProperty(SBProperties.artistName, artist.toString());
    pa.appendProperty(SBProperties.albumName, album.toString());
    var items = list.getItemsByProperties(pa).enumerate();

    while (items.hasMoreElements())
    {
        track = items.getNext().getProperty(SBProperties.trackName);
        tracksArray[i] = [track, track];
        i++;
    }

    return tracksArray;
}

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>data_environment_obscurance = [
    {
        title: "Lightly obscured",
        icon: "bleeding-eye",
        subtitle: "Disadvantage on Perception",
        description: "Dim light, patchy fog, moderate foliage",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creatures have disadvantage on Wisdom (Perception) checks that rely on sight."
        ]
    },
    {
        title: "Heavily obscured",
        icon: "lightning-tear",
        subtitle: "Effectively blind",
        description: "Darkness, opaque fog, dense foliage",
        reference: "PHB, pg. 183.",
        bullets: [
            "A creature in a heavily obscured area effectively suffers from the blinded condition."
        ]
    }
]

data_environment_light = [
    {
        title: "Bright light",
        icon: "star-pupil",
        subtitle: "Normal vision",
        description: "Bright light lets most creatures see normally",
        reference: "PHB, pg. 183.",
        bullets: [
            "Gloomy days still provide bright light, as do torches, lanterns, fires, and other sources of illumination within a specific radius."
        ]
    },
    {
        title: "Dim light",
        icon: "semi-closed-eye",
        subtitle: "Lightly obscured",
        description: "Dim light, also called shadows",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creates a lightly obscured area.",
            "An area of dim light is usually a boundary between a source of bright light, such as a torch, and surrounding darkness.",
            "The soft light of twilight and dawn also counts as dim light. A particularly brilliant full moon might bathe the land in dim light."
        ]
    },
    {
        title: "Darkness",
        icon: "worried-eyes",
        subtitle: "Heavily obscured",
        description: "Darkness creates a heavily obscured area",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creates a heavily obscured area.",
            "Characters face darkness outdoors at night (even most moonlit nights), within the confines of an unlit dungeon or a subterranean vault, or in an area of magical darkness."
        ]
    }
]

data_environment_vision = [
    {
        title: "Blindsight",
        icon: "one-eyed",
        subtitle: "Perceive without sight",
        description: "Perceive your surroundings without relying on sight, within a certain radius",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creatures without eyes, such as oozes, and creatures with echolocation or heightened senses, such as bats and true dragons, have this sense."
        ]
    },
    {
        title: "Darkvision",
        icon: "semi-closed-eye",
        subtitle: "Limited vision in darkness",
        description: "A creature with Darkvision can see better in the dark or low light conditions, within a certain radius",
        reference: "PHB, pgs. 183-184.",
        bullets: [
            "Within a specified range, a creature with darkvision can see in darkness as if the darkness were dim light, so areas of darkness are only lightly obscured as far as that creature is concerned.",
            "However, the creature can’t discern color in darkness, only shades of gray.",
            "Many creatures in the worlds of D&D, especially those that dwell underground, have darkvision."
        ]
    },
    {
        title: "Truesight",
        icon: "eye-shield",
        subtitle: "See in darkness",
        description: "A creature with truesight can see everything in its true form, independent of the environment",
        reference: "PHB, pg. 184.",
        bullets: [
            "A creature with truesight can, out to a specific range, see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceives the original form of a shapechanger or a creature that is transformed by magic.",
            "Furthermore, the creature can see into the Ethereal Plane."
        ]
    }
]

data_environment_cover = [
    {
        title: "Half cover",
        icon: "broken-shield",
        subtitle: "Low wall, furniture",
        description: "A target has half cover if an obstacle blocks at least half of its body",
        reference: "PHB, pg. 196.",
        bullets: [
            "The obstacle might be a low wall, a large piece of furniture, a narrow tree trunk, or a creature, whether that creature is an enemy or a friend.",
            "A target with half cover has a +2 bonus to AC and Dexterity saving throws.",
            " If a target is behind multiple sources of cover, only the most protective degree of cover applies"
        ]
    },
    {
        title: "Three-quarters cover",
        icon: "cracked-shield",
        subtitle: "Portcullis, arrow slit",
        description: "A target has half cover if about three-quarters of it is covered by an obstacle",
        reference: "PHB, pg. 196.",
        bullets: [
            "The obstacle might be a portcullis, an arrow slit, or a thick tree trunk.",
            "A target with three-quarters cover has a +5 bonus to AC and Dexterity saving throws.",
            " If a target is behind multiple sources of cover, only the most protective degree of cover applies"
        ]
    },
    {
        title: "Full cover",
        icon: "shield",
        subtitle: "Completely concealed",
        description: "A target has total cover if it is completely concealed by an obstacle",
        reference: "PHB, pg. 196.",
        bullets: [
            "A target with total cover can’t be targeted directly by an attack or a spell, although some spells can reach such a target by including it in an area of effect.",
            "If a target is behind multiple sources of cover, only the most protective degree of cover applies"
        ]
    }
]
<commit_msg>Fix typo in Three-quaters cover, desc. says "half"<commit_after>data_environment_obscurance = [
    {
        title: "Lightly obscured",
        icon: "bleeding-eye",
        subtitle: "Disadvantage on Perception",
        description: "Dim light, patchy fog, moderate foliage",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creatures have disadvantage on Wisdom (Perception) checks that rely on sight."
        ]
    },
    {
        title: "Heavily obscured",
        icon: "lightning-tear",
        subtitle: "Effectively blind",
        description: "Darkness, opaque fog, dense foliage",
        reference: "PHB, pg. 183.",
        bullets: [
            "A creature in a heavily obscured area effectively suffers from the blinded condition."
        ]
    }
]

data_environment_light = [
    {
        title: "Bright light",
        icon: "star-pupil",
        subtitle: "Normal vision",
        description: "Bright light lets most creatures see normally",
        reference: "PHB, pg. 183.",
        bullets: [
            "Gloomy days still provide bright light, as do torches, lanterns, fires, and other sources of illumination within a specific radius."
        ]
    },
    {
        title: "Dim light",
        icon: "semi-closed-eye",
        subtitle: "Lightly obscured",
        description: "Dim light, also called shadows",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creates a lightly obscured area.",
            "An area of dim light is usually a boundary between a source of bright light, such as a torch, and surrounding darkness.",
            "The soft light of twilight and dawn also counts as dim light. A particularly brilliant full moon might bathe the land in dim light."
        ]
    },
    {
        title: "Darkness",
        icon: "worried-eyes",
        subtitle: "Heavily obscured",
        description: "Darkness creates a heavily obscured area",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creates a heavily obscured area.",
            "Characters face darkness outdoors at night (even most moonlit nights), within the confines of an unlit dungeon or a subterranean vault, or in an area of magical darkness."
        ]
    }
]

data_environment_vision = [
    {
        title: "Blindsight",
        icon: "one-eyed",
        subtitle: "Perceive without sight",
        description: "Perceive your surroundings without relying on sight, within a certain radius",
        reference: "PHB, pg. 183.",
        bullets: [
            "Creatures without eyes, such as oozes, and creatures with echolocation or heightened senses, such as bats and true dragons, have this sense."
        ]
    },
    {
        title: "Darkvision",
        icon: "semi-closed-eye",
        subtitle: "Limited vision in darkness",
        description: "A creature with Darkvision can see better in the dark or low light conditions, within a certain radius",
        reference: "PHB, pgs. 183-184.",
        bullets: [
            "Within a specified range, a creature with darkvision can see in darkness as if the darkness were dim light, so areas of darkness are only lightly obscured as far as that creature is concerned.",
            "However, the creature can’t discern color in darkness, only shades of gray.",
            "Many creatures in the worlds of D&D, especially those that dwell underground, have darkvision."
        ]
    },
    {
        title: "Truesight",
        icon: "eye-shield",
        subtitle: "See in darkness",
        description: "A creature with truesight can see everything in its true form, independent of the environment",
        reference: "PHB, pg. 184.",
        bullets: [
            "A creature with truesight can, out to a specific range, see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceives the original form of a shapechanger or a creature that is transformed by magic.",
            "Furthermore, the creature can see into the Ethereal Plane."
        ]
    }
]

data_environment_cover = [
    {
        title: "Half cover",
        icon: "broken-shield",
        subtitle: "Low wall, furniture",
        description: "A target has half cover if an obstacle blocks at least half of its body",
        reference: "PHB, pg. 196.",
        bullets: [
            "The obstacle might be a low wall, a large piece of furniture, a narrow tree trunk, or a creature, whether that creature is an enemy or a friend.",
            "A target with half cover has a +2 bonus to AC and Dexterity saving throws.",
            " If a target is behind multiple sources of cover, only the most protective degree of cover applies"
        ]
    },
    {
        title: "Three-quarters cover",
        icon: "cracked-shield",
        subtitle: "Portcullis, arrow slit",
        description: "A target has three-quarters cover if about three-quarters of it is covered by an obstacle",
        reference: "PHB, pg. 196.",
        bullets: [
            "The obstacle might be a portcullis, an arrow slit, or a thick tree trunk.",
            "A target with three-quarters cover has a +5 bonus to AC and Dexterity saving throws.",
            " If a target is behind multiple sources of cover, only the most protective degree of cover applies"
        ]
    },
    {
        title: "Full cover",
        icon: "shield",
        subtitle: "Completely concealed",
        description: "A target has total cover if it is completely concealed by an obstacle",
        reference: "PHB, pg. 196.",
        bullets: [
            "A target with total cover can’t be targeted directly by an attack or a spell, although some spells can reach such a target by including it in an area of effect.",
            "If a target is behind multiple sources of cover, only the most protective degree of cover applies"
        ]
    }
]
<|endoftext|>


<commit_before>Menubar.Edit = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu' );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'Edit' );
	container.add( title );

	var options = new UI.Panel();
	options.setClass( 'options' );
	container.add( options );

	// Clone

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Clone' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object.parent === undefined ) return; // avoid cloning the camera or scene

		object = object.clone();

		editor.addObject( object );
		editor.select( object );

	} );
	options.add( option );

	// Delete

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Delete' );
	option.onClick( function () {

		var parent = editor.selected.parent;
		editor.removeObject( editor.selected );
		editor.select( parent );

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Flatten

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Flatten' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object.parent === undefined ) return; // avoid flattening the camera or scene

		if ( confirm( 'Flatten ' + object.name + '?' ) === false ) return;

		var geometry = object.geometry.clone();
		geometry.applyMatrix( object.matrix );

		object.geometry = geometry;

		object.position.set( 0, 0, 0 );
		object.rotation.set( 0, 0, 0 );
		object.scale.set( 1, 1, 1 );

		object.geometry.buffersNeedUpdate = true;
		editor.signals.objectChanged.dispatch( object );

	} );
	options.add( option );

	return container;

};<commit_msg>Editor: Clean up Menubar.Edit.<commit_after>Menubar.Edit = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu' );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'Edit' );
	container.add( title );

	var options = new UI.Panel();
	options.setClass( 'options' );
	container.add( options );

	// Clone

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Clone' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object.parent === undefined ) return; // avoid cloning the camera or scene

		object = object.clone();

		editor.addObject( object );
		editor.select( object );

	} );
	options.add( option );

	// Delete

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Delete' );
	option.onClick( function () {

		var parent = editor.selected.parent;
		editor.removeObject( editor.selected );
		editor.select( parent );

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Flatten

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Flatten' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object.parent === undefined ) return; // avoid flattening the camera or scene

		if ( confirm( 'Flatten ' + object.name + '?' ) === false ) return;

		var geometry = object.geometry;

		geometry.applyMatrix( object.matrix );
		geometry.verticesNeedUpdate = true;
		geometry.normalsNeedUpdate = true;

		object.position.set( 0, 0, 0 );
		object.rotation.set( 0, 0, 0 );
		object.scale.set( 1, 1, 1 );

		editor.signals.objectChanged.dispatch( object );

	} );
	options.add( option );

	return container;

};
<|endoftext|>


<commit_before>require.paths.push('lib');
require.paths.push('deps/jsdom/lib');
var HTML5 = require('html5'),
	events = require('events'),
	sys = require('sys'),
	fs = require('fs'),
	assert = require('assert')

var inp = fs.createReadStream(process.argv[2])

var p = new HTML5.Parser();

if(process.argv[3]) {
	var debugs = process.argv[3].split(',');
	for(var d in debugs) HTML5.enableDebug(debugs[d]);
}

p.on('end', function() {
	console.log(HTML5.serialize(p.document, null, {lowercase: true,
quote_attr_values: false}))
})

p.parse(inp);

<commit_msg>Make parse-doc output test serialization data<commit_after>require.paths.push('lib');
require.paths.push('deps/jsdom/lib');
var HTML5 = require('html5'),
	events = require('events'),
	sys = require('sys'),
	fs = require('fs'),
	assert = require('assert')

var inp = fs.createReadStream(process.argv[2])

var p = new HTML5.Parser();

if(process.argv[3]) {
	var debugs = process.argv[3].split(',');
	for(var d in debugs) HTML5.enableDebug(debugs[d]);
}

p.on('end', function() {
	console.log(require('../tests/support/serializeTestOutput').serializeTestOutput(p.document))
})

p.parse(inp);

<|endoftext|>


<commit_before>/**
 * Target number of nano-seconds to run tests for.
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"1CEA5B7F-4E92-4087-B0DD-71B9DD9D925D",variableType:8}
 */
var benchTime = 1e9;

/**
 * Local shortcut for high-precision timing.
 * @type {function():Number}
 * @properties={typeid:35,uuid:"56B573D2-D629-4779-8D6A-07AFEC2E834A",variableType:-4}
 */
var nanoTime = java.lang.System.nanoTime;

/**
 * @properties={typeid:35,uuid:"797221B3-A92A-4A75-A0DB-642F2748664E",variableType:-4}
 */
var Bench = function () {
	var b = this;

	//Number of iterations benchmark should be run
	b.N = 0,
	b.start = null;
	b.duration = null;
	b.timerOn = false;

	b.startTimer = function() {
		if (!b.timerOn) {
			b.start = nanoTime();
			b.timerOn = true;
		}
	};

	b.stopTimer = function() {
		if (b.timerOn) {
			b.duration += (nanoTime() - b.start);
			b.timerOn = false;
		}
	};

	b.resetTimer = function() {
		if (b.timerOn) {
			b.start = nanoTime();
		}
		b.duration = 0;
	};

	/**
	 * @return {Number}
	 */
	b.nsPerOp = function() {
		if (b.N <= 0) {
			return 0;
		}
		return b.duration/b.N;
	}

	/**
	 * @return {Number}
	 */
	b.opsPerS = function() {
		if (b.duration <= 0)
		{
			return 0;
		}
		return b.N/(b.duration/1e9);
	}

}

/**
 *
 * @properties={typeid:35,uuid:"EB3AF1B5-7570-4549-A876-5CAB3A549F52",variableType:-4}
 */
var BenchmarkResult = function (ops, duration) {
	var b = this;
	b.ops = ops;
	b.duration = duration;

	/** @type {Number} */
	b.nsPerOp = (ops > 0 && (duration/ops)) || 0;
	/** @type {Number} */
	b.opsPerS = (duration > 0 && ops/(duration/1e9))
}

/**
 * @param {String} name
 * @param {BenchmarkResult} r
 *
 * @properties={typeid:35,uuid:"24A46511-1436-4F39-ABC0-7E6FD91B20F9",variableType:-4}
 */
var log = function (name, r) {
	var time = nsToTime(r.nsPerOp);
	application.output(name + ":\t" + pad(r.ops + " ops\t", 20) + pad(time.time.toFixed(3) + " " + time.unit + "/op\t", 20) + pad(r.opsPerS.toFixed(3) +" ops/sec", 20))

	function pad(s, n) {
		if (s.length >= n)
		{
			return s;
		}
		return (new Array(n-s.length+1).join(' ') + s);
	}
};

/**
 * @param {scopes.benchpress.Bench} b
 * @param {function(scopes.benchpress.Bench)} benchmark
 * @param {Number} n
 *
 * @properties={typeid:24,uuid:"65E00C72-991C-4272-A96E-5EF55E673F5A"}
 */
function runNTimes(b, benchmark, n) {
	//Attempt to get consistent results across runs by suggesting
	//to the JVM that it collect garbage from previous runs
	java.lang.System.gc();

	b.N = n;
	b.resetTimer();
	b.startTimer();
	benchmark(b);
	b.stopTimer();
}

/**
 * @param {function(scopes.benchpress.Bench)} benchmark
 *
 * @properties={typeid:24,uuid:"553F5063-96EE-4BA2-A551-C2C240CF1D2C"}
 */
function launch(benchmark) {

	var b = new Bench();

	//Run the benchmark once to start (in case it's expensive)
	var n = 1;
	runNTimes(b,benchmark,n);

	var last;
	while (b.duration < benchTime && n < 1e9) {
		last = n;

		//Predict iterations/sec
		if (b.nsPerOp() == 0) {
			n = 1e9;
		}
		else {
			n = (benchTime / b.nsPerOp())
		}

		// Run more iterations than we think we'll need for a second (1.5x).
        // Don't grow too fast in case we had timing errors previously.
        // Be sure to run at least one more than last time.
        n = Math.max(Math.min(n+n/2, 100*last), last+1);
        // Round up to something easy to read.
        n = roundUp(n);

        runNTimes(b,benchmark,n);
	}

	var result = new BenchmarkResult(n, b.duration);
	return result;

}

/**
 * Rounds a number down to the nearest power of 10.
 * @param n
 * @return {Number}
 * @properties={typeid:24,uuid:"4CAD1EB4-F416-46F4-AD2B-DD1D6B337B26"}
 */
function roundDown10(n) {
	var tens = 0
	// tens = floor(log_10(n))
	while (n >= 10) {
		n = n / 10
		tens++
	}
	// result = 10^tens
	var result = 1
	for (var i = 0; i < tens; i++) {
		result *= 10
	}
	return result
}

/**
 * Rounds x up to a number of the form [1eX, 2eX, 5eX].
 * @param n
 * @return {Number}
 *
 * @properties={typeid:24,uuid:"838FA8B2-A943-4ECB-968E-3C7F490B89C1"}
 */
function roundUp(n) {
	var base = roundDown10(n)
	if ( n <= base ) {
		return base;
	}
	else if (n <= (2 * base)) {
		return 2 * base
	}
	else if (n <= (5 * base)) {
		return 5 * base;
	}
	else {
		return 10 * base
	}
}

/**
 * Search across all scopes for benchmarking methods and run them
 * @properties={typeid:24,uuid:"5D1EFCD0-2C9D-4003-8C66-35F715834A85"}
 */
function runAllBenchmarks() {
	var scopeNames = solutionModel.getScopeNames();
	scopeNames.forEach(function (s) {
		var methods = solutionModel.getGlobalMethods(s).map(function(j) { return j.getName() } );
		var benchmarks = methods.filter(function (name) {
			return name.indexOf('benchmark_') == 0;
		});

		benchmarks.forEach(function (benchmark) {
			var result = launch(scopes[s][benchmark]);
			log([s, benchmark].join('.'), result);
		});
	});
}

/**
 * @param {Number} ns
 * @return {{time:Number, unit:String}}
 * @properties={typeid:24,uuid:"91A1D73E-5E6C-43A6-90B6-E8780ABCC0E7"}
 */
function nsToTime(ns)
{
	var time;

	//Seconds
	time = ns/1e9;
	if (time >= 1) {
		return {
			time : time,
			unit : 's'
		};
	}

	//Milliseconds
	time = ns/1e6;
	if (time > 1) {
		return {
			time : time,
			unit : 'ms'
		};
	}

	//Nanoseconds
	return {
		time : ns,
		unit : 'ns'
	};
}<commit_msg>Add stddev to benchmark results<commit_after>/**
 * Target number of nano-seconds to run tests for.
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"1CEA5B7F-4E92-4087-B0DD-71B9DD9D925D",variableType:8}
 */
var benchTime = 1e9;

/**
 * Local shortcut for high-precision timing.
 * @type {function():Number}
 * @properties={typeid:35,uuid:"56B573D2-D629-4779-8D6A-07AFEC2E834A",variableType:-4}
 */
var nanoTime = java.lang.System.nanoTime;

/**
 * @properties={typeid:35,uuid:"797221B3-A92A-4A75-A0DB-642F2748664E",variableType:-4}
 */
var Bench = function () {
	var b = this;

	//Number of iterations benchmark should be run
	b.N = 0,
	b.start = null;
	b.duration = null;
	b.timerOn = false;
	b.stddev = null;

	b.startTimer = function() {
		if (!b.timerOn) {
			b.start = nanoTime();
			b.timerOn = true;
		}
	};

	b.stopTimer = function() {
		if (b.timerOn) {
			b.duration += (nanoTime() - b.start);
			b.timerOn = false;
		}
	};

	b.resetTimer = function() {
		if (b.timerOn) {
			b.start = nanoTime();
		}
		b.duration = 0;
	};

	/**
	 * @return {Number}
	 */
	b.nsPerOp = function() {
		if (b.N <= 0) {
			return 0;
		}
		return b.duration/b.N;
	}

	/**
	 * @return {Number}
	 */
	b.opsPerS = function() {
		if (b.duration <= 0)
		{
			return 0;
		}
		return b.N/(b.duration/1e9);
	}

}

/**
 *
 * @properties={typeid:35,uuid:"EB3AF1B5-7570-4549-A876-5CAB3A549F52",variableType:-4}
 */
var BenchmarkResult = function (ops, duration) {
	var b = this;
	b.ops = ops;
	b.duration = duration;

	/** @type {Number} */
	b.nsPerOp = (ops > 0 && (duration/ops)) || 0;
	/** @type {Number} */
	b.opsPerS = (duration > 0 && ops/(duration/1e9))
}

/**
 * @param {String} name
 * @param {BenchmarkResult} r
 *
 * @properties={typeid:35,uuid:"24A46511-1436-4F39-ABC0-7E6FD91B20F9",variableType:-4}
 */
var log = function (name, r) {
	var time = nsToTime(r.nsPerOp);
	application.output(name + ":\t" + pad(r.ops + " ops\t", 20) + pad(time.time.toFixed(3) + " " + time.unit + "/op\t", 20) + pad(r.opsPerS.toFixed(3) +" ops/sec", 20))

	function pad(s, n) {
		if (s.length >= n)
		{
			return s;
		}
		return (new Array(n-s.length+1).join(' ') + s);
	}
};

/**
 * @param {scopes.benchpress.Bench} b
 * @param {function(scopes.benchpress.Bench)} benchmark
 * @param {Number} n
 *
 * @properties={typeid:24,uuid:"65E00C72-991C-4272-A96E-5EF55E673F5A"}
 */
function runNTimes(b, benchmark, n) {
	//Attempt to get consistent results across runs by suggesting
	//to the JVM that it collect garbage from previous runs
	java.lang.System.gc();

	b.N = n;
	b.resetTimer();
	b.startTimer();
	benchmark(b);
	b.stopTimer();
}

/**
 * @param {function(scopes.benchpress.Bench)} benchmark
 *
 * @properties={typeid:24,uuid:"553F5063-96EE-4BA2-A551-C2C240CF1D2C"}
 */
function launch(benchmark) {

	var b = new Bench();

	//Run the benchmark once to start (in case it's expensive)
	var n = 1;
	runNTimes(b,benchmark,n);

	//Run tests for a minimum amount of time to try and get statistically valid estimates.
	var last;
	while (b.duration < benchTime && n < 1e9) {
		last = n;

		//Predict iterations/ns
		if (b.nsPerOp() == 0) {
			n = 1e9;
		}
		else {
			n = (benchTime / b.nsPerOp())
		}

		// Run more iterations than we think we'll need for a second (1.5x).
        // Don't grow too fast in case we had timing errors previously.
        // Be sure to run at least one more than last time.
        n = Math.max(Math.min(n+n/2, 100*last), last+1);
        // Round up to something easy to read.
        n = roundUp(n);

        runNTimes(b,benchmark,n);
	}

	//Re-run tests in segments to estimate the standard deviation
	n = Math.max(Math.floor(n / 20), 1);
	n = roundUp(n);
	var expected = b.nsPerOp();
	var reps = new Bench();
	var variance = 0;
	for (var i = 0; i < 20; i++) {
		runNTimes(reps,benchmark,n);
		variance += Math.pow((expected-reps.nsPerOp()), 2);
	}
	variance = variance/20;
	b.stddev = Math.sqrt(variance);

	return b;

}

/**
 * Rounds a number down to the nearest power of 10.
 * @param n
 * @return {Number}
 * @properties={typeid:24,uuid:"4CAD1EB4-F416-46F4-AD2B-DD1D6B337B26"}
 */
function roundDown10(n) {
	var tens = 0
	// tens = floor(log_10(n))
	while (n >= 10) {
		n = n / 10
		tens++
	}
	// result = 10^tens
	var result = 1
	for (var i = 0; i < tens; i++) {
		result *= 10
	}
	return result
}

/**
 * Rounds x up to a number of the form [1eX, 2eX, 5eX].
 * @param n
 * @return {Number}
 *
 * @properties={typeid:24,uuid:"838FA8B2-A943-4ECB-968E-3C7F490B89C1"}
 */
function roundUp(n) {
	var base = roundDown10(n)
	if ( n <= base ) {
		return base;
	}
	else if (n <= (2 * base)) {
		return 2 * base
	}
	else if (n <= (5 * base)) {
		return 5 * base;
	}
	else {
		return 10 * base
	}
}

/**
 * Search across all scopes for benchmarking methods and run them
 * @properties={typeid:24,uuid:"5D1EFCD0-2C9D-4003-8C66-35F715834A85"}
 */
function runAllBenchmarks() {
	var scopeNames = solutionModel.getScopeNames();
	scopeNames.forEach(function (s) {
		var methods = solutionModel.getGlobalMethods(s).map(function(j) { return j.getName() } );
		var benchmarks = methods.filter(function (name) {
			return name.indexOf('benchmark_') == 0;
		});

		benchmarks.forEach(function (benchmark) {
			var result = launch(scopes[s][benchmark]);
			log([s, benchmark].join('.'), result);
		});
	});
}

/**
 * @param {Number} ns
 * @return {{time:Number, unit:String}}
 * @properties={typeid:24,uuid:"91A1D73E-5E6C-43A6-90B6-E8780ABCC0E7"}
 */
function nsToTime(ns)
{
	var time;

	//Seconds
	time = ns/1e9;
	if (time >= 1) {
		return {
			time : time,
			unit : 's'
		};
	}

	//Milliseconds
	time = ns/1e6;
	if (time > 1) {
		return {
			time : time,
			unit : 'ms'
		};
	}

	//Nanoseconds
	return {
		time : ns,
		unit : 'ns'
	};
}<|endoftext|>


<commit_before>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function generer() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);
groupe = 1;
    var logo = new Image();

    var numPErs =  (parseInt(localStorage.numGroupe));

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){

              var logo = new Image();
           // for (groupe = 1; groupe < 5; groupe++) {

             /*
             for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".JPEG";

                    pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }*/
           // }

                 logo.src = "/pdf_images/long/Long_adults/long_adults_dataset1_1.jpeg";

                 pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();
            var logo2 = new Image();
                 logo2.src = "/pdf_images/long/Long_adults/long_adults_dataset1_2.jpeg";

                    pdf.addImage(logo2, 'JPEG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();

             /*var logo3 = new Image();
                 logo3.src = "/pdf_images/long/Long_adults/long_adults_dataset1_3.PNG";
                 logo3.onload = function(){
                    pdf.addImage(logo3, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo4 = new Image();
                 logo4.src = "/pdf_images/long/Long_adults/long_adults_dataset1_4.PNG";
                 logo4.onload = function(){
                    pdf.addImage(logo4, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }*/
             //}
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                logo.onload = function(){
                  pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }

pdf.output("dataurlnewwindow");
}
function visualiser() {

}
<commit_msg>Update dynamic_carousel.js<commit_after>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function generer() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);
groupe = 1;
    var logo = new Image();

    var numPErs =  (parseInt(localStorage.numGroupe));

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){

              var logo = new Image();
           // for (groupe = 1; groupe < 5; groupe++) {

             /*
             for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".JPEG";

                    pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }*/
           // }

                 logo.src = "/pdf_images/court/Court_adults/court_adults_dataset1_1.gpeg";

                 pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();
            var logo2 = new Image();
                 logo2.src = "/pdf_images/court/Court_adults/court_adults_dataset1_2.jpeg";

                    pdf.addImage(logo2, 'JPEG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();

             /*var logo3 = new Image();
                 logo3.src = "/pdf_images/long/Long_adults/long_adults_dataset1_3.PNG";
                 logo3.onload = function(){
                    pdf.addImage(logo3, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo4 = new Image();
                 logo4.src = "/pdf_images/long/Long_adults/long_adults_dataset1_4.PNG";
                 logo4.onload = function(){
                    pdf.addImage(logo4, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }*/
             //}
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                logo.onload = function(){
                  pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }

pdf.output("dataurlnewwindow");
}
function visualiser() {

}
<|endoftext|>


<commit_before>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

alert("hola");

     var pdf = new jsPDF('p', 'pt', 'a4', false);
     //var pdf = new jsPDF();
  /*var logo = new Image();
         pdf.text("hello", 30,30);
       logo.src = "1.png";
       pdf.addImage(logo, 'PNG', 2, 2, 590,850);*/

          if(duration_longue){
            var logo = new Image();
            logo.src = "https://vizkit.github.io/pdf_images/Court_adults/2.jpeg";
            logo.onload = function(){
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            }
            pdf.addPage();
     //       var logo = new Image();
      //      logo.src = "/pdf_images/1.png";
       //     pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }/*else if(duration_courte) {
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
            pdf.addPage();
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }*/

           var uno= 1;

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

        }
<commit_msg>Update dynamic_carousel.js<commit_after>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

alert("hola");

     var pdf = new jsPDF('p', 'pt', 'a4', false);
     //var pdf = new jsPDF();
  /*var logo = new Image();
         pdf.text("hello", 30,30);
       logo.src = "1.png";
       pdf.addImage(logo, 'PNG', 2, 2, 590,850);*/

          if(duration_longue){
            var logo = new Image();
            logo.src = "https://vizkit.github.io/pdf_images/Court_adults/2.jpeg";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            pdf.addPage();
     //       var logo = new Image();
      //      logo.src = "/pdf_images/1.png";
       //     pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }/*else if(duration_courte) {
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
            pdf.addPage();
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }*/

           var uno= 1;

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

        }
<|endoftext|>


<commit_before>(function(){

	var Memory = {

		init: function(cards){
			this.$game = $(".game");
			this.$modal = $(".modal");
			this.$overlay = $(".modal-overlay");
			this.$restartButton = $("button.restart");
			this.cardsArray = $.merge(cards, cards);
			this.shuffleCards(this.cardsArray);
			this.setup();
		},

		shuffleCards: function(cardsArray){
			this.$cards = $(this.shuffle(this.cardsArray));
		},

		setup: function(){
			this.html = this.buildHTML();
			this.$game.html(this.html);
			this.$memoryCards = $(".card");
			this.paused = false;
     	this.guess = null;
			this.binding();
		},

		binding: function(){
			this.$memoryCards.on("click", this.cardClicked);
			this.$restartButton.on("click", $.proxy(this.reset, this));
		},
		// kinda messy but hey
		cardClicked: function(){
			var _ = Memory;
			var $card = $(this);
			if(!_.paused && !$card.find(".inside").hasClass("matched") && !$card.find(".inside").hasClass("picked")){
				$card.find(".inside").addClass("picked");
				if(!_.guess){
					_.guess = $(this).attr("data-id");
				} else if(_.guess == $(this).attr("data-id") && !$(this).hasClass("picked")){
					$(".picked").addClass("matched");
					_.guess = null;
				} else {
					_.guess = null;
					_.paused = true;
					setTimeout(function(){
						$(".picked").removeClass("picked");
						Memory.paused = false;
					}, 600);
				}
				if($(".matched").length == $(".card").length){
					_.win();
				}
			}
		},

		win: function(){
			this.paused = true;
			setTimeout(function(){
				Memory.showModal();
				Memory.$game.fadeOut();
			}, 1000);
		},

		showModal: function(){
			this.$overlay.show();
			this.$modal.fadeIn("slow");
		},

		hideModal: function(){
			this.$overlay.hide();
			this.$modal.hide();
		},

		reset: function(){
			this.hideModal();
			this.shuffleCards(this.cardsArray);
			this.setup();
			this.$game.show("slow");
		},

		// Fisher--Yates Algorithm -- https://bost.ocks.org/mike/shuffle/
		shuffle: function(array){
			var counter = array.length, temp, index;
	   	// While there are elements in the array
	   	while (counter > 0) {
        	// Pick a random index
        	index = Math.floor(Math.random() * counter);
        	// Decrease counter by 1
        	counter--;
        	// And swap the last element with it
        	temp = array[counter];
        	array[counter] = array[index];
        	array[index] = temp;
	    	}
	    	return array;
		},

		buildHTML: function(){
			var frag = '';
			this.$cards.each(function(k, v){
				frag += '

\

\

\

';
			});
			return frag;
		}
	};

	var cards = [
		{
			name: "card1",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card1.JPG",
			id: 1,
		},
		{
			name: "card2",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card2.JPG",
			id: 2
		},
		{
			name: "card3",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card3.JPG",
			id: 3
		},
		{
			name: "card4",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card4.jpg",
			id: 4
		},
		{
			name: "card5",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card5.JPG",
			id: 5
		},
		{
			name: "card6",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card6.JPG",
			id: 6
		},
		{
			name: "card7",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card7.JPG",
			id: 7
		},
		{
			name: "card8",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card8.JPG",
			id: 8
		},
		{
			name: "card9",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card9.JPG",
			id: 9
		},
		{
			name: "card10",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card10.JPG",
			id: 10
		},
		{
			name: "card11",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card11.JPG",
			id: 11
		},
		{
			name: "card12",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card12.JPG",
			id: 12
		},
	];

	Memory.init(cards);

})();<commit_msg>memory cards<commit_after>(function(){

	var Memory = {

		init: function(cards){
			this.$game = $(".game");
			this.$modal = $(".modal");
			this.$overlay = $(".modal-overlay");
			this.$restartButton = $("button.restart");
			this.cardsArray = $.merge(cards, cards);
			this.shuffleCards(this.cardsArray);
			this.setup();
		},

		shuffleCards: function(cardsArray){
			this.$cards = $(this.shuffle(this.cardsArray));
		},

		setup: function(){
			this.html = this.buildHTML();
			this.$game.html(this.html);
			this.$memoryCards = $(".card");
			this.paused = false;
     	this.guess = null;
			this.binding();
		},

		binding: function(){
			this.$memoryCards.on("click", this.cardClicked);
			this.$restartButton.on("click", $.proxy(this.reset, this));
		},
		// kinda messy but hey
		cardClicked: function(){
			var _ = Memory;
			var $card = $(this);
			if(!_.paused && !$card.find(".inside").hasClass("matched") && !$card.find(".inside").hasClass("picked")){
				$card.find(".inside").addClass("picked");
				if(!_.guess){
					_.guess = $(this).attr("data-id");
				} else if(_.guess == $(this).attr("data-id") && !$(this).hasClass("picked")){
					$(".picked").addClass("matched");
					_.guess = null;
				} else {
					_.guess = null;
					_.paused = true;
					setTimeout(function(){
						$(".picked").removeClass("picked");
						Memory.paused = false;
					}, 600);
				}
				if($(".matched").length == $(".card").length){
					_.win();
				}
			}
		},

		win: function(){
			this.paused = true;
			setTimeout(function(){
				Memory.showModal();
				Memory.$game.fadeOut();
			}, 1000);
		},

		showModal: function(){
			this.$overlay.show();
			this.$modal.fadeIn("slow");
		},

		hideModal: function(){
			this.$overlay.hide();
			this.$modal.hide();
		},

		reset: function(){
			this.hideModal();
			this.shuffleCards(this.cardsArray);
			this.setup();
			this.$game.show("slow");
		},

		// Fisher--Yates Algorithm -- https://bost.ocks.org/mike/shuffle/
		shuffle: function(array){
			var counter = array.length, temp, index;
	   	// While there are elements in the array
	   	while (counter > 0) {
        	// Pick a random index
        	index = Math.floor(Math.random() * counter);
        	// Decrease counter by 1
        	counter--;
        	// And swap the last element with it
        	temp = array[counter];
        	array[counter] = array[index];
        	array[index] = temp;
	    	}
	    	return array;
		},

		buildHTML: function(){
			var frag = '';
			this.$cards.each(function(k, v){
				frag += '

\

\

\

';
			});
			return frag;
		}
	};

	var cards = [
		{
			name: "card1",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card1.JPG",
			id: 1,
		},
		{
			name: "card2",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card2.JPG",
			id: 2
		},
		{
			name: "card3",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card3.JPG",
			id: 3
		},
		{
			name: "card4",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card4.jpg",
			id: 4
		},
		{
			name: "card5",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card5.JPG",
			id: 5
		},
		{
			name: "card6",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card6.JPG",
			id: 6
		},
		{
			name: "card7",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card7.JPG",
			id: 7
		},
		{
			name: "card8",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card8.JPG",
			id: 8
		},
		{
			name: "card9",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card9.JPG",
			id: 9
		},
		{
			name: "card10",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card10.JPG",
			id: 10
		},
		{
			name: "card11",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card11.JPG",
			id: 11
		},
		{
			name: "card12",
			img: "http://o84fll9yy.bkt.clouddn.com/fun/card12.JPG",
			id: 12
		},
	];

	Memory.init(cards);

})();<|endoftext|>