<commit_before>"use strict";

var
/** @const */  PCI_VENDOR_ID =		0x00	/* 16 bits */
/** @const */ ,PCI_DEVICE_ID =		0x02	/* 16 bits */
/** @const */ ,PCI_COMMAND =		0x04	/* 16 bits */
/** @const */ ,PCI_BASE_ADDRESS_0 =	0x10	/* 32 bits */
/** @const */ ,PCI_BASE_ADDRESS_1 =	0x14	/* 32 bits [htype 0,1 only] */
/** @const */ ,PCI_BASE_ADDRESS_2 =	0x18	/* 32 bits [htype 0 only] */
/** @const */ ,PCI_BASE_ADDRESS_3 =	0x1c	/* 32 bits */
/** @const */ ,PCI_BASE_ADDRESS_4 =	0x20	/* 32 bits */
/** @const */ ,PCI_BASE_ADDRESS_5 =	0x24	/* 32 bits */
/** @const */ ,PCI_INTERRUPT_LINE =	0x3c	/* 8 bits */
/** @const */ ,PCI_CLASS_REVISION =	0x08;	/* High 24 bits are class, low 8 revision */

var
/** @const */ PCI_CONFIG_ADDRESS = 0xCF8,
/** @const */ PCI_CONFIG_DATA = 0xCFC;

/** @constructor */
function PCI(dev)
{
    var
        io = dev.io,
        pci_addr = new Uint8Array(4),
        pci_response = new Uint8Array(4),
        pci_status = new Uint8Array(4),

        pci_addr32 = new Int32Array(pci_addr.buffer),
        pci_response32 = new Int32Array(pci_response.buffer),
        pci_status32 = new Int32Array(pci_status.buffer),
        pci = this;

    var device_spaces = Array(0x10000),
        devices = Array(0x10000);

    /*
    io.register_write(0xCF9, function(value)
    {
        dbg_log("PCI reboot: " + h(value, 2), LOG_PCI);

        // PCI reboot
        if(value & 6)
        {
            cpu_restart();
        }
    });*/

    io.register_write(PCI_CONFIG_DATA, function(out_byte)
    {
        dbg_log("PCI data0: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);
        pci_write_byte(0, out_byte);
    });
    io.register_write(PCI_CONFIG_DATA | 1, function(out_byte)
    {
        dbg_log("PCI data1: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);
        pci_write_byte(1, out_byte);
    });
    io.register_write(PCI_CONFIG_DATA | 2, function(out_byte)
    {
        dbg_log("PCI data2: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);
        pci_write_byte(2, out_byte);
    });
    io.register_write(PCI_CONFIG_DATA | 3, function(out_byte)
    {
        dbg_log("PCI data3: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);

        pci_write_byte(3, out_byte);
    });

    io.register_read(PCI_CONFIG_DATA, function()
    {
        return pci_response[0];
    });
    io.register_read(PCI_CONFIG_DATA | 1, function()
    {
        return pci_response[1];
    });
    io.register_read(PCI_CONFIG_DATA | 2, function()
    {
        return pci_response[2];
    });
    io.register_read(PCI_CONFIG_DATA | 3, function()
    {
        return pci_response[3];
    });

    io.register_read(PCI_CONFIG_ADDRESS, function()
    {
        return pci_status[0];
    });
    io.register_read(PCI_CONFIG_ADDRESS | 1, function()
    {
        return pci_status[1];
    });
    io.register_read(PCI_CONFIG_ADDRESS | 2, function()
    {
        return pci_status[2];
    });
    io.register_read(PCI_CONFIG_ADDRESS | 3, function()
    {
        return pci_status[3];
    });

    io.register_write(PCI_CONFIG_ADDRESS, function(out_byte)
    {
        pci_addr[0] = out_byte;
    });
    io.register_write(PCI_CONFIG_ADDRESS | 1, function(out_byte)
    {
        pci_addr[1] = out_byte;
    });
    io.register_write(PCI_CONFIG_ADDRESS | 2, function(out_byte)
    {
        pci_addr[2] = out_byte;
    });
    io.register_write(PCI_CONFIG_ADDRESS | 3, function(out_byte)
    {
        pci_addr[3] = out_byte;

        pci_query();
    });

    function pci_query()
    {
        var dbg_line = "PCI: ";

        // Bit | .31                     .0
        // Fmt | EBBBBBBBBDDDDDFFFRRRRRR00

        var bdf = pci_addr[2] << 8 | pci_addr[1],
            addr = pci_addr[0] & 0xFC,
            devfn = bdf & 0xFF,
            bus = bdf >> 8,
            dev = bdf >> 3 & 0x1F,
            fn = bdf & 7,
            enabled = pci_addr[3] >> 7;

        dbg_line += " enabled=" + (enabled);
        dbg_line += " bdf=" + h(bdf, 4);
        dbg_line += " addr=" + h(addr, 2);

        //dbg_log(dbg_line + " " + h(pci_addr32[0] >>> 0, 8), LOG_PCI);

        var device = device_spaces[bdf];

        if(device !== undefined)
        {
            dbg_log(dbg_line + " " + h(pci_addr32[0] >>> 0, 8), LOG_PCI);

            pci_status32[0] = 0x80000000 | 0;

            if(addr < device.byteLength)
            {
                pci_response32[0] = device[addr >> 2];
            }
            else
            {
                pci_response32[0] = 0;
            }
        }
        else
        {
            pci_response32[0] = 0;
            pci_status32[0] = 0;
        }
    }

    function pci_write_byte(byte_pos, byte)
    {
        var bdf = pci_addr[2] << 8 | pci_addr[1],
            addr = pci_addr[0] & 0xFC;

        var space = device_spaces[bdf],
            device = devices[bdf];

        if(space)
        {
            (new Uint8Array(space.buffer))[addr | byte_pos] = byte;

            if(byte_pos === 3 && addr >= 0x10 && addr < 0x28)
            {
                var bar_nr = addr - 0x10 >> 2,
                    bar = device.pci_bars[bar_nr],
                    value = space[addr >> 2];

                dbg_log("BAR" + bar_nr + " changed to " + h(space[addr >> 2] >>> 0) + " dev=" + h(bdf, 2), LOG_PCI);

                if(bar)
                {
                    dbg_assert(!(bar.size & bar.size - 1));
                    space[addr >> 2] = value & ~(bar.size - 1) | 3;
                }
                else
                {
                    space[addr >> 2] = 0;
                }
            }
        }
    }

    this.register_device = function(device)
    {
        dbg_assert(device.pci_id !== undefined);
        dbg_assert(device.pci_space !== undefined);
        dbg_assert(device.pci_bars !== undefined);

        var device_id = device.pci_id;

        dbg_log("PCI register bdf=" + h(device_id), LOG_PCI);

        dbg_assert(!devices[device_id]);
        dbg_assert(device.pci_space.length === 64);

        // convert bytewise notation from lspci to double words
        device_spaces[device_id] = new Int32Array(new Uint8Array(device.pci_space).buffer);
        devices[device_id] = device;
    };

    // Some experimental PCI devices taken from my PC:

    // 00:00.0 Host bridge: Intel Corporation 4 Series Chipset DRAM Controller (rev 02)
    //var host_bridge = {
    //    pci_id: 0,
    //    pci_space: [
    //        0x86, 0x80, 0x20, 0x2e, 0x06, 0x00, 0x90, 0x20, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
    //        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    //        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x10, 0xd3, 0x82,
    //        0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    //    ],
    //    pci_bars: [],
    //};

    var host_bridge = {
        pci_id: 0,
        pci_space: [
            // 00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
            0x86, 0x80, 0x37, 0x12, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ],
        pci_bars: [],
    };
    this.register_device(host_bridge);

    var isa_bridge = {
        pci_id: 1 << 3,
        pci_space: [
            // 00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
            0x86, 0x80, 0x00, 0x70, 0x07, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x80, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ],
        pci_bars: [],
    };
    this.register_device(isa_bridge);

    // 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 90)
    //this.register_device([
    //    0x86, 0x80, 0x4e, 0x24, 0x07, 0x01, 0x10, 0x00, 0x90, 0x01, 0x04, 0x06, 0x00, 0x00, 0x01, 0x00,
    //    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x05, 0x20, 0xe0, 0xe0, 0x80, 0x22,
    //    0xb0, 0xfe, 0xb0, 0xfe, 0xf1, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    //    0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x02, 0x00,
    //], 0x1e << 3);

}
<commit_msg>Report invalid device correctly<commit_after>"use strict";

var
/** @const */  PCI_VENDOR_ID =		0x00	/* 16 bits */
/** @const */ ,PCI_DEVICE_ID =		0x02	/* 16 bits */
/** @const */ ,PCI_COMMAND =		0x04	/* 16 bits */
/** @const */ ,PCI_BASE_ADDRESS_0 =	0x10	/* 32 bits */
/** @const */ ,PCI_BASE_ADDRESS_1 =	0x14	/* 32 bits [htype 0,1 only] */
/** @const */ ,PCI_BASE_ADDRESS_2 =	0x18	/* 32 bits [htype 0 only] */
/** @const */ ,PCI_BASE_ADDRESS_3 =	0x1c	/* 32 bits */
/** @const */ ,PCI_BASE_ADDRESS_4 =	0x20	/* 32 bits */
/** @const */ ,PCI_BASE_ADDRESS_5 =	0x24	/* 32 bits */
/** @const */ ,PCI_INTERRUPT_LINE =	0x3c	/* 8 bits */
/** @const */ ,PCI_CLASS_REVISION =	0x08;	/* High 24 bits are class, low 8 revision */

var
/** @const */ PCI_CONFIG_ADDRESS = 0xCF8,
/** @const */ PCI_CONFIG_DATA = 0xCFC;

/** @constructor */
function PCI(dev)
{
    var
        io = dev.io,
        pci_addr = new Uint8Array(4),
        pci_response = new Uint8Array(4),
        pci_status = new Uint8Array(4),

        pci_addr32 = new Int32Array(pci_addr.buffer),
        pci_response32 = new Int32Array(pci_response.buffer),
        pci_status32 = new Int32Array(pci_status.buffer),
        pci = this;

    var device_spaces = Array(0x10000),
        devices = Array(0x10000);

    /*
    io.register_write(0xCF9, function(value)
    {
        dbg_log("PCI reboot: " + h(value, 2), LOG_PCI);

        // PCI reboot
        if(value & 6)
        {
            cpu_restart();
        }
    });*/

    io.register_write(PCI_CONFIG_DATA, function(out_byte)
    {
        dbg_log("PCI data0: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);
        pci_write_byte(0, out_byte);
    });
    io.register_write(PCI_CONFIG_DATA | 1, function(out_byte)
    {
        dbg_log("PCI data1: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);
        pci_write_byte(1, out_byte);
    });
    io.register_write(PCI_CONFIG_DATA | 2, function(out_byte)
    {
        dbg_log("PCI data2: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);
        pci_write_byte(2, out_byte);
    });
    io.register_write(PCI_CONFIG_DATA | 3, function(out_byte)
    {
        dbg_log("PCI data3: " + h(out_byte, 2) + " addr=" + h(pci_addr32[0] >>> 0), LOG_PCI);

        pci_write_byte(3, out_byte);
    });

    io.register_read(PCI_CONFIG_DATA, function()
    {
        return pci_response[0];
    });
    io.register_read(PCI_CONFIG_DATA | 1, function()
    {
        return pci_response[1];
    });
    io.register_read(PCI_CONFIG_DATA | 2, function()
    {
        return pci_response[2];
    });
    io.register_read(PCI_CONFIG_DATA | 3, function()
    {
        return pci_response[3];
    });

    io.register_read(PCI_CONFIG_ADDRESS, function()
    {
        return pci_status[0];
    });
    io.register_read(PCI_CONFIG_ADDRESS | 1, function()
    {
        return pci_status[1];
    });
    io.register_read(PCI_CONFIG_ADDRESS | 2, function()
    {
        return pci_status[2];
    });
    io.register_read(PCI_CONFIG_ADDRESS | 3, function()
    {
        return pci_status[3];
    });

    io.register_write(PCI_CONFIG_ADDRESS, function(out_byte)
    {
        pci_addr[0] = out_byte;
    });
    io.register_write(PCI_CONFIG_ADDRESS | 1, function(out_byte)
    {
        pci_addr[1] = out_byte;
    });
    io.register_write(PCI_CONFIG_ADDRESS | 2, function(out_byte)
    {
        pci_addr[2] = out_byte;
    });
    io.register_write(PCI_CONFIG_ADDRESS | 3, function(out_byte)
    {
        pci_addr[3] = out_byte;

        pci_query();
    });

    function pci_query()
    {
        var dbg_line = "PCI: ";

        // Bit | .31                     .0
        // Fmt | EBBBBBBBBDDDDDFFFRRRRRR00

        var bdf = pci_addr[2] << 8 | pci_addr[1],
            addr = pci_addr[0] & 0xFC,
            devfn = bdf & 0xFF,
            bus = bdf >> 8,
            dev = bdf >> 3 & 0x1F,
            fn = bdf & 7,
            enabled = pci_addr[3] >> 7;

        dbg_line += " enabled=" + (enabled);
        dbg_line += " bdf=" + h(bdf, 4);
        dbg_line += " addr=" + h(addr, 2);

        //dbg_log(dbg_line + " " + h(pci_addr32[0] >>> 0, 8), LOG_PCI);

        var device = device_spaces[bdf];

        if(device !== undefined)
        {
            pci_status32[0] = 0x80000000 | 0;

            if(addr < device.byteLength)
            {
                pci_response32[0] = device[addr >> 2];
            }
            else
            {
                pci_response32[0] = 0;
            }

            dbg_log(dbg_line + " " + h(pci_addr32[0] >>> 0, 8) + "  " + h(pci_response32[0] >>> 0, 8), LOG_PCI);
        }
        else
        {
            pci_response32[0] = -1;
            pci_status32[0] = 0;
        }
    }

    function pci_write_byte(byte_pos, byte)
    {
        var bdf = pci_addr[2] << 8 | pci_addr[1],
            addr = pci_addr[0] & 0xFC;

        var space = device_spaces[bdf],
            device = devices[bdf];

        if(space)
        {
            (new Uint8Array(space.buffer))[addr | byte_pos] = byte;

            if(byte_pos === 3 && addr >= 0x10 && addr < 0x28)
            {
                var bar_nr = addr - 0x10 >> 2,
                    bar = device.pci_bars[bar_nr],
                    value = space[addr >> 2];

                dbg_log("BAR" + bar_nr + " changed to " + h(space[addr >> 2] >>> 0) + " dev=" + h(bdf, 2), LOG_PCI);

                if(bar)
                {
                    dbg_assert(!(bar.size & bar.size - 1));
                    space[addr >> 2] = value & ~(bar.size - 1) | 3;
                }
                else
                {
                    space[addr >> 2] = 0;
                }
            }
        }
    }

    this.register_device = function(device)
    {
        dbg_assert(device.pci_id !== undefined);
        dbg_assert(device.pci_space !== undefined);
        dbg_assert(device.pci_bars !== undefined);

        var device_id = device.pci_id;

        dbg_log("PCI register bdf=" + h(device_id), LOG_PCI);

        dbg_assert(!devices[device_id]);
        dbg_assert(device.pci_space.length === 64);

        // convert bytewise notation from lspci to double words
        device_spaces[device_id] = new Int32Array(new Uint8Array(device.pci_space).buffer);
        devices[device_id] = device;
    };

    // Some experimental PCI devices taken from my PC:

    // 00:00.0 Host bridge: Intel Corporation 4 Series Chipset DRAM Controller (rev 02)
    //var host_bridge = {
    //    pci_id: 0,
    //    pci_space: [
    //        0x86, 0x80, 0x20, 0x2e, 0x06, 0x00, 0x90, 0x20, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
    //        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    //        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x10, 0xd3, 0x82,
    //        0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    //    ],
    //    pci_bars: [],
    //};

    var host_bridge = {
        pci_id: 0,
        pci_space: [
            // 00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
            0x86, 0x80, 0x37, 0x12, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ],
        pci_bars: [],
    };
    this.register_device(host_bridge);

    var isa_bridge = {
        pci_id: 1 << 3,
        pci_space: [
            // 00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
            0x86, 0x80, 0x00, 0x70, 0x07, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x80, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ],
        pci_bars: [],
    };
    this.register_device(isa_bridge);

    // 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 90)
    //this.register_device([
    //    0x86, 0x80, 0x4e, 0x24, 0x07, 0x01, 0x10, 0x00, 0x90, 0x01, 0x04, 0x06, 0x00, 0x00, 0x01, 0x00,
    //    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x05, 0x20, 0xe0, 0xe0, 0x80, 0x22,
    //    0xb0, 0xfe, 0xb0, 0xfe, 0xf1, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    //    0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x02, 0x00,
    //], 0x1e << 3);

}
<|endoftext|>


<commit_before>if (Meteor.isClient) {
  angular.module('socially', ['angular-meteor']);

  angular.module('socially').controller('PartiesListCtrl', function ($scope) {
    $scope.parties = [
      {
        'name': 'Dubstep-Free Zone',
        'description': 'Can we please just for an evening not listen to dubstep.'
      },
      {
        'name': 'All dubstep all the time',
        'description': 'Get it on!'
      },
      {
        'name': 'Savage lounging',
        'description': 'Leisure suit required. And only fiercest manners.'
      }
    ];
  });
}<commit_msg>Step 3.1: Add the parties collection<commit_after>Parties = new Mongo.Collection("parties");

if (Meteor.isClient) {
  angular.module('socially', ['angular-meteor']);

  angular.module('socially').controller('PartiesListCtrl', function ($scope) {
    $scope.parties = [
      {
        'name': 'Dubstep-Free Zone',
        'description': 'Can we please just for an evening not listen to dubstep.'
      },
      {
        'name': 'All dubstep all the time',
        'description': 'Get it on!'
      },
      {
        'name': 'Savage lounging',
        'description': 'Leisure suit required. And only fiercest manners.'
      }
    ];
  });
}<|endoftext|>


<commit_before>'use strict';

const ServerDescription = require('./server_description').ServerDescription;
const ServerType = require('./server_description').ServerType;
const calculateDurationInMs = require('../utils').calculateDurationInMs;

/**
 * Published when server description changes, but does NOT include changes to the RTT.
 *
 * @property {Object} topologyId A unique identifier for the topology
 * @property {ServerAddress} address The address (host/port pair) of the server
 * @property {ServerDescription} previousDescription The previous server description
 * @property {ServerDescription} newDescription The new server description
 */
class ServerDescriptionChangedEvent {
  constructor(topologyId, address, previousDescription, newDescription) {
    Object.assign(this, { topologyId, address, previousDescription, newDescription });
  }
}

/**
 * Published when server is initialized.
 *
 * @property {Object} topologyId A unique identifier for the topology
 * @property {ServerAddress} address The address (host/port pair) of the server
 */
class ServerOpeningEvent {
  constructor(topologyId, address) {
    Object.assign(this, { topologyId, address });
  }
}

/**
 * Published when server is closed.
 *
 * @property {ServerAddress} address The address (host/port pair) of the server
 * @property {Object} topologyId A unique identifier for the topology
 */
class ServerClosedEvent {
  constructor(topologyId, address) {
    Object.assign(this, { topologyId, address });
  }
}

/**
 * Published when topology description changes.
 *
 * @property {Object} topologyId
 * @property {TopologyDescription} previousDescription The old topology description
 * @property {TopologyDescription} newDescription The new topology description
 */
class TopologyDescriptionChangedEvent {
  constructor(topologyId, previousDescription, newDescription) {
    Object.assign(this, { topologyId, previousDescription, newDescription });
  }
}

/**
 * Published when topology is initialized.
 *
 * @param {Object} topologyId A unique identifier for the topology
 */
class TopologyOpeningEvent {
  constructor(topologyId) {
    Object.assign(this, { topologyId });
  }
}

/**
 * Published when topology is closed.
 *
 * @param {Object} topologyId A unique identifier for the topology
 */
class TopologyClosedEvent {
  constructor(topologyId) {
    Object.assign(this, { topologyId });
  }
}

/**
 * Fired when the server monitor’s ismaster command is started - immediately before
 * the ismaster command is serialized into raw BSON and written to the socket.
 *
 * @property {Object} connectionId The connection id for the command
 */
class ServerHeartbeatStartedEvent {
  constructor(connectionId) {
    Object.assign(this, { connectionId });
  }
}

/**
 * Fired when the server monitor’s ismaster succeeds.
 *
 * @param {Number} duration The execution time of the event in ms
 * @param {Object} reply The command reply
 * @param {Object} connectionId The connection id for the command
 */
class ServerHeartbeatSucceededEvent {
  constructor(duration, reply, connectionId) {
    Object.assign(this, { duration, reply, connectionId });
  }
}

/**
 * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception.
 *
 * @param {Number} duration The execution time of the event in ms
 * @param {MongoError|Object} failure The command failure
 * @param {Object} connectionId The connection id for the command
 */
class ServerHeartbeatFailedEvent {
  constructor(duration, failure, connectionId) {
    Object.assign(this, { duration, failure, connectionId });
  }
}

/**
 * Performs a server check as described by the SDAM spec.
 *
 * NOTE: This method automatically reschedules itself, so that there is always an active
 * monitoring process
 *
 * @param {Server} server The server to monitor
 */
function monitorServer(server, options) {
  options = options || {};
  const heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000;

  if (options.initial === true) {
    server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS);
    return;
  }

  // executes a single check of a server
  const checkServer = callback => {
    let start = process.hrtime();

    // emit a signal indicating we have started the heartbeat
    server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name));

    // NOTE: legacy monitoring event
    process.nextTick(() => server.emit('monitoring', server));

    server.command(
      'admin.$cmd',
      { ismaster: true },
      {
        monitoring: true,
        socketTimeout: server.s.options.connectionTimeout || 2000
      },
      (err, result) => {
        let duration = calculateDurationInMs(start);

        if (err) {
          server.emit(
            'serverHeartbeatFailed',
            new ServerHeartbeatFailedEvent(duration, err, server.name)
          );

          return callback(err, null);
        }

        const isMaster = result.result;
        server.emit(
          'serverHeartbeatSucceded',
          new ServerHeartbeatSucceededEvent(duration, isMaster, server.name)
        );

        return callback(null, isMaster);
      }
    );
  };

  const successHandler = isMaster => {
    server.s.monitoring = false;

    // emit an event indicating that our description has changed
    server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster));

    // schedule the next monitoring process
    server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS);
  };

  // run the actual monitoring loop
  server.s.monitoring = true;
  checkServer((err, isMaster) => {
    if (!err) {
      successHandler(isMaster);
      return;
    }

    // According to the SDAM specification's "Network error during server check" section, if
    // an ismaster call fails we reset the server's pool. If a server was once connected,
    // change its type to `Unknown` only after retrying once.
    server.s.pool.reset(() => {
      // otherwise re-attempt monitoring once
      checkServer((error, isMaster) => {
        if (error) {
          server.s.monitoring = false;

          // we revert to an `Unknown` by emitting a default description with no isMaster
          server.emit(
            'descriptionReceived',
            new ServerDescription(server.description.address, null, { error })
          );

          // we do not reschedule monitoring in this case
          return;
        }

        successHandler(isMaster);
      });
    });
  });
}

module.exports = {
  ServerDescriptionChangedEvent,
  ServerOpeningEvent,
  ServerClosedEvent,
  TopologyDescriptionChangedEvent,
  TopologyOpeningEvent,
  TopologyClosedEvent,
  ServerHeartbeatStartedEvent,
  ServerHeartbeatSucceededEvent,
  ServerHeartbeatFailedEvent,
  monitorServer
};
<commit_msg>chore: clean up linting issues introduced by SDAM backport<commit_after>'use strict';

const ServerDescription = require('./server_description').ServerDescription;
const calculateDurationInMs = require('../utils').calculateDurationInMs;

/**
 * Published when server description changes, but does NOT include changes to the RTT.
 *
 * @property {Object} topologyId A unique identifier for the topology
 * @property {ServerAddress} address The address (host/port pair) of the server
 * @property {ServerDescription} previousDescription The previous server description
 * @property {ServerDescription} newDescription The new server description
 */
class ServerDescriptionChangedEvent {
  constructor(topologyId, address, previousDescription, newDescription) {
    Object.assign(this, { topologyId, address, previousDescription, newDescription });
  }
}

/**
 * Published when server is initialized.
 *
 * @property {Object} topologyId A unique identifier for the topology
 * @property {ServerAddress} address The address (host/port pair) of the server
 */
class ServerOpeningEvent {
  constructor(topologyId, address) {
    Object.assign(this, { topologyId, address });
  }
}

/**
 * Published when server is closed.
 *
 * @property {ServerAddress} address The address (host/port pair) of the server
 * @property {Object} topologyId A unique identifier for the topology
 */
class ServerClosedEvent {
  constructor(topologyId, address) {
    Object.assign(this, { topologyId, address });
  }
}

/**
 * Published when topology description changes.
 *
 * @property {Object} topologyId
 * @property {TopologyDescription} previousDescription The old topology description
 * @property {TopologyDescription} newDescription The new topology description
 */
class TopologyDescriptionChangedEvent {
  constructor(topologyId, previousDescription, newDescription) {
    Object.assign(this, { topologyId, previousDescription, newDescription });
  }
}

/**
 * Published when topology is initialized.
 *
 * @param {Object} topologyId A unique identifier for the topology
 */
class TopologyOpeningEvent {
  constructor(topologyId) {
    Object.assign(this, { topologyId });
  }
}

/**
 * Published when topology is closed.
 *
 * @param {Object} topologyId A unique identifier for the topology
 */
class TopologyClosedEvent {
  constructor(topologyId) {
    Object.assign(this, { topologyId });
  }
}

/**
 * Fired when the server monitor’s ismaster command is started - immediately before
 * the ismaster command is serialized into raw BSON and written to the socket.
 *
 * @property {Object} connectionId The connection id for the command
 */
class ServerHeartbeatStartedEvent {
  constructor(connectionId) {
    Object.assign(this, { connectionId });
  }
}

/**
 * Fired when the server monitor’s ismaster succeeds.
 *
 * @param {Number} duration The execution time of the event in ms
 * @param {Object} reply The command reply
 * @param {Object} connectionId The connection id for the command
 */
class ServerHeartbeatSucceededEvent {
  constructor(duration, reply, connectionId) {
    Object.assign(this, { duration, reply, connectionId });
  }
}

/**
 * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception.
 *
 * @param {Number} duration The execution time of the event in ms
 * @param {MongoError|Object} failure The command failure
 * @param {Object} connectionId The connection id for the command
 */
class ServerHeartbeatFailedEvent {
  constructor(duration, failure, connectionId) {
    Object.assign(this, { duration, failure, connectionId });
  }
}

/**
 * Performs a server check as described by the SDAM spec.
 *
 * NOTE: This method automatically reschedules itself, so that there is always an active
 * monitoring process
 *
 * @param {Server} server The server to monitor
 */
function monitorServer(server, options) {
  options = options || {};
  const heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000;

  if (options.initial === true) {
    server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS);
    return;
  }

  // executes a single check of a server
  const checkServer = callback => {
    let start = process.hrtime();

    // emit a signal indicating we have started the heartbeat
    server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name));

    // NOTE: legacy monitoring event
    process.nextTick(() => server.emit('monitoring', server));

    server.command(
      'admin.$cmd',
      { ismaster: true },
      {
        monitoring: true,
        socketTimeout: server.s.options.connectionTimeout || 2000
      },
      (err, result) => {
        let duration = calculateDurationInMs(start);

        if (err) {
          server.emit(
            'serverHeartbeatFailed',
            new ServerHeartbeatFailedEvent(duration, err, server.name)
          );

          return callback(err, null);
        }

        const isMaster = result.result;
        server.emit(
          'serverHeartbeatSucceded',
          new ServerHeartbeatSucceededEvent(duration, isMaster, server.name)
        );

        return callback(null, isMaster);
      }
    );
  };

  const successHandler = isMaster => {
    server.s.monitoring = false;

    // emit an event indicating that our description has changed
    server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster));

    // schedule the next monitoring process
    server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS);
  };

  // run the actual monitoring loop
  server.s.monitoring = true;
  checkServer((err, isMaster) => {
    if (!err) {
      successHandler(isMaster);
      return;
    }

    // According to the SDAM specification's "Network error during server check" section, if
    // an ismaster call fails we reset the server's pool. If a server was once connected,
    // change its type to `Unknown` only after retrying once.
    server.s.pool.reset(() => {
      // otherwise re-attempt monitoring once
      checkServer((error, isMaster) => {
        if (error) {
          server.s.monitoring = false;

          // we revert to an `Unknown` by emitting a default description with no isMaster
          server.emit(
            'descriptionReceived',
            new ServerDescription(server.description.address, null, { error })
          );

          // we do not reschedule monitoring in this case
          return;
        }

        successHandler(isMaster);
      });
    });
  });
}

module.exports = {
  ServerDescriptionChangedEvent,
  ServerOpeningEvent,
  ServerClosedEvent,
  TopologyDescriptionChangedEvent,
  TopologyOpeningEvent,
  TopologyClosedEvent,
  ServerHeartbeatStartedEvent,
  ServerHeartbeatSucceededEvent,
  ServerHeartbeatFailedEvent,
  monitorServer
};
<|endoftext|>


<commit_before>(function($) {

    /**
     * .slideshow
     *
     * Begins the slideshow by choosing the type of slide and duration
     *
     * type        Type of slideshow to run; Defaults to 'fade'
     * duration    Time in miliseconds that each element is visible; Defaults to
     *                 5000
     */
    $.fn.slideshow = function(type, duration) {
        type = typeof type !== 'undefined' ? type : 'fade';
        duration = typeof duration !== 'undefined' ? duration : 5000;

        var $container = this;
        var count = 0;

        switch(type) {
            case 'fade':
                this.children().hide().fadeOut();
                this.children(":first").addClass('active').show();

                var intervalID = setInterval(function() {
                    $container.slideshowFade(intervalID);
                }, duration);
                break;
            case 'FadeInto':
                this["init"+type]();

                var intervalID = setInterval(function() {
/*                    count = $container.slideshowFadeInto(intervalID, count); */
                    count = $container["slideshow"+type](intervalID, count);
                }, duration);
                break;
        };
    };

    $.fn.slideshowFadeInto = function (intervalID, count, fadeSpeed) {
        /* if(count == 6) clearInterval(intervalID); */
        /* if(count !== 0 && count%7 == 0 ) this.reset(); */

        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();
        var $container = this;

        $swap["active"].fadeOut(fadeSpeed, function() {
                $swap["active"].hide(function() {
                   $swap["next"].addClass('active');
                   var nextZ = $container.nextZ();
                   $swap["active"].css({'z-index':nextZ}).show();
                });
            })

        return count+1;

    };

    $.fn.swap = function () {
        var $active = this.children(".active").toggleClass('active');
        if($active.length == 0)
            $active = this.children(":last");
        var $next = $active.next().length ? $active.next()
            : this.children(":first");

        return {"active":$active,"next":$next};
    }

    /**
     * Sets the initial state for the FadeInto slideshow
     *
     * start    z-index for top-most element in slideshow; Defaults to 100
     */
    $.fn.initFadeInto = function(start) {
        start = typeof start !== 'undefined' ? start : 100

        // Adds .active to first element in 'this'
        this.children(":first").addClass('active');

        /* Iterates through all children of 'this'
         *     sets initiale z-index (start - order in 'this')
         *     sets position: absolute
         *     shows child
         */
        for(var i=1; i<=this.children().length; i=i+1) {
            this.find(":nth-child("+i+")")
            .css({
                'z-index':start-i,
                'position':'absolute'
            })
            .show();
        }
    }

    $.fn.nextZ = function(){
        var nextZ = 999;
        var length = this.children().length;
        for(var count=1; count<=length; count = count +1) {
            if(nextZ>this.find(":nth-child("+count+")").css("z-index"))
                nextZ = this.find(":nth-child("+count+")").css("z-index");
        }
        return nextZ-1;
    }

    $.fn.slideshowFade = function (fadeSpeed) {
        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();

        $swap["active"].fadeOut(fadeSpeed, function () {
                $swap["active"].hide(function () {
                    $swap["next"].addClass('active')
                        .fadeIn(fadeSpeed);
                });
            });

    };

}) (jQuery);
<commit_msg>Makes function calls dynamic<commit_after>(function($) {

    /**
     * .slideshow
     *
     * Begins the slideshow by choosing the type of slide and duration
     *
     * type        Type of slideshow to run; Defaults to 'fade'
     * duration    Time in miliseconds that each element is visible; Defaults to
     *                 5000
     */
    $.fn.slideshow = function(type, duration) {
        type = typeof type !== 'undefined' ? type : 'fade';
        duration = typeof duration !== 'undefined' ? duration : 5000;

        var $container = this;
        var count = 0;
        var validTypes = ['fade','fadeInto'];

        if(validTypes.indexOf(type) !== -1) {
            this["init"+type]();

            var intervalID = setInterval(function() {
                count = $container["slideshow"+type](intervalID, count);
            }, duration);
        } else {
            alert(type+" is not a supported slideshow type.");
        }

        /*
        switch(type) {
            case 'fade':
                this.children().hide().fadeOut();
                this.children(":first").addClass('active').show();

                var intervalID = setInterval(function() {
                    $container.slideshowFade(intervalID);
                }, duration);
                break;
            case 'FadeInto':
                this["init"+type]();

                var intervalID = setInterval(function() {
                    count = $container["slideshow"+type](intervalID, count);
                }, duration);
                break;
        };
        */
    };

    $.fn.slideshowFadeInto = function (intervalID, count, fadeSpeed) {
        /* if(count == 6) clearInterval(intervalID); */
        /* if(count !== 0 && count%7 == 0 ) this.reset(); */

        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();
        var $container = this;

        $swap["active"].fadeOut(fadeSpeed, function() {
                $swap["active"].hide(function() {
                   $swap["next"].addClass('active');
                   var nextZ = $container.nextZ();
                   $swap["active"].css({'z-index':nextZ}).show();
                });
            })

        return count+1;

    };

    $.fn.swap = function () {
        var $active = this.children(".active").toggleClass('active');
        if($active.length == 0)
            $active = this.children(":last");
        var $next = $active.next().length ? $active.next()
            : this.children(":first");

        return {"active":$active,"next":$next};
    }

    /**
     * Sets the initial state for the FadeInto slideshow
     *
     * start    z-index for top-most element in slideshow; Defaults to 100
     */
    $.fn.initFadeInto = function(start) {
        start = typeof start !== 'undefined' ? start : 100

        // Adds .active to first element in 'this'
        this.children(":first").addClass('active');

        /* Iterates through all children of 'this'
         *     sets initiale z-index (start - order in 'this')
         *     sets position: absolute
         *     shows child
         */
        for(var i=1; i<=this.children().length; i=i+1) {
            this.find(":nth-child("+i+")")
            .css({
                'z-index':start-i,
                'position':'absolute'
            })
            .show();
        }
    }

    $.fn.nextZ = function(){
        var nextZ = 999;
        var length = this.children().length;
        for(var count=1; count<=length; count = count +1) {
            if(nextZ>this.find(":nth-child("+count+")").css("z-index"))
                nextZ = this.find(":nth-child("+count+")").css("z-index");
        }
        return nextZ-1;
    }

    $.fn.slideshowFade = function (fadeSpeed) {
        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();

        $swap["active"].fadeOut(fadeSpeed, function () {
                $swap["active"].hide(function () {
                    $swap["next"].addClass('active')
                        .fadeIn(fadeSpeed);
                });
            });

    };

}) (jQuery);
<|endoftext|>


<commit_before>var fs = require('fs'),
    express = require('express'),
    app = express(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    podium = function() {
      var config = null,
          socket = null,
          slides = {},

          loadConfig = function (err, data) {
            if (err) {
              throw err;
            }

            config = JSON.parse(data);
            server.listen(config.port);
            app.set('views', __dirname + '/views');
            app.set('view engine', 'jade');
            app.use(express.static(__dirname + '/public'));
            console.log('Podium Express server listening on port '+config.port);
            fs.readdir(__dirname + '/slides', scanSlidesDir);
          },

          scanSlidesDir = function(err, directories) {
            if (err) {
              throw err;
            }

            directories.forEach(function(slides_directory) {
              if(slides_directory === '.DS_Store') {
                // continue;
              } else if (fs.existsSync(__dirname + "/slides/"+slides_directory+"/podium.json")) {
                var slideDeck = JSON.parse(
                      fs.readFileSync(__dirname + "/slides/"+slides_directory+"/podium.json")
                    );

                slides[slideDeck.route] = {
                  name: slideDeck.name,
                  location: location = "/slides/"+slides_directory+"/",
                  route: slideDeck.route,
                  // initial slide horizontal index
                  indexh : 0,
                  // initial slide veriticlal index
                  indexv : 0
                };
              } else {
                console.log("\nWarning: There is no podium config file in /slides/"+slides_directory+"/");
              }
            });

            main();
          },

          socketRequestSlideDeck = function(data) {
            if(slides[data.route]) {
              console.log('sending init presentation data ' + JSON.stringify(slides[data.route]) );
              socket.emit('initdata', slides[data.route]);
            }
          },

          sockectOnCommand = function(command) {
            var route = command.route,
                // command can be 'up', 'down', 'left', 'right'
                command = command.text,
                currentDeck = null;

            console.log("receive command " + JSON.stringify(command) );

            // TODO: future might need a way to tell how many slides there are

            if(slides[route]) {
              currentDeck = slides[route];
              // update ppt information

              switch(command) {
                case 'up':
                  currentDeck.indexv--;
                  break;
                case 'down':
                  currentDeck.indexv++;
                  break;
                case 'left':
                  currentDeck.indexh--;
                  break;
                case 'right':
                  currentDeck.indexh++;
                  break;
              }

              if(currentDeck.indexh < 0 ) {
                currentDeck.indexh = 0;
              }

              if(currentDeck.indexv < 0 ) {
                currentDeck.indexv = 0;
              }

              slides[route] = currentDeck;

              // send the new data for update
              socket.broadcast.emit('updatedata', currentDeck);
            }
          },

          socketConnect = function (sock) {
            socket = sock;

            // once connected need to broadcast the cur slide data
            socket.on('request_presentation', socketRequestSlideDeck);

            // send commands to make slide go previous/ next/etc
            // this should be triggered from the remote controller
            socket.on('command', sockectOnCommand);
          },

          main = function () {
            app.get('/', function (req, res) {
              res.render('index', {slides: slides});
            });

            app.get('/controller', function (req, res) {
              res.render('controller', {slides: slides});
            });

            //Map out all of the routes for the slide decks
            for (var route in slides) {
              app.use(express.static(__dirname + slides[route].location + 'public'));

              app.get(route, function (req, res) {
                res.sendfile(__dirname + slides[route].location+'index.html');
              });
            }

            io.on('connection', socketConnect);
          },

          init = function () {
            fs.readFile(__dirname + '/config.json', loadConfig);
          }();

      return {
        config: config
      };
    }();<commit_msg>reordered functions in app js to follow execution flow<commit_after>var fs = require('fs'),
    express = require('express'),
    app = express(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    podium = function() {
      var config = null,
          socket = null,
          slides = {},

          init = function () {
            fs.readFile(__dirname + '/config.json', loadConfig);
          }(),

          loadConfig = function (err, data) {
            if (err) {
              throw err;
            }

            config = JSON.parse(data);
            server.listen(config.port);
            app.set('views', __dirname + '/views');
            app.set('view engine', 'jade');
            app.use(express.static(__dirname + '/public'));
            console.log('Podium Express server listening on port '+config.port);
            fs.readdir(__dirname + '/slides', scanSlidesDir);
          },

          scanSlidesDir = function(err, directories) {
            if (err) {
              throw err;
            }

            directories.forEach(function(slides_directory) {
              if(slides_directory === '.DS_Store') {
                // continue;
              } else if (fs.existsSync(__dirname + "/slides/"+slides_directory+"/podium.json")) {
                var slideDeck = JSON.parse(
                      fs.readFileSync(__dirname + "/slides/"+slides_directory+"/podium.json")
                    );

                slides[slideDeck.route] = {
                  name: slideDeck.name,
                  location: location = "/slides/"+slides_directory+"/",
                  route: slideDeck.route,
                  // initial slide horizontal index
                  indexh : 0,
                  // initial slide veriticlal index
                  indexv : 0
                };
              } else {
                console.log("\nWarning: There is no podium config file in /slides/"+slides_directory+"/");
              }
            });

            main();
          },

          main = function () {
            app.get('/', function (req, res) {
              res.render('index', {slides: slides});
            });

            app.get('/controller', function (req, res) {
              res.render('controller', {slides: slides});
            });

            //Map out all of the routes for the slide decks
            for (var route in slides) {
              app.use(express.static(__dirname + slides[route].location + 'public'));

              app.get(route, function (req, res) {
                res.sendfile(__dirname + slides[route].location+'index.html');
              });
            }

            io.on('connection', socketConnect);
          },

          socketConnect = function (sock) {
            socket = sock;

            socket.on('requestDeck', socketRequestSlideDeck);

            socket.on('command', sockectOnCommand);
          },

          socketRequestSlideDeck = function(data) {
            if(slides[data.route]) {
              console.log('Sending initial deck data: ' + JSON.stringify(slides[data.route]) );
              socket.emit('initalData', slides[data.route]);
            }
          },

          sockectOnCommand = function(command) {
            var route = command.route,
                command = command.text,
                currentDeck = null;

            console.log("Received command: " + JSON.stringify(command) );

            if(slides[route]) {
              currentDeck = slides[route];

              switch(command) {
                case 'up':
                  currentDeck.indexv--;
                  break;
                case 'down':
                  currentDeck.indexv++;
                  break;
                case 'left':
                  currentDeck.indexh--;
                  break;
                case 'right':
                  currentDeck.indexh++;
                  break;
              }

              if(currentDeck.indexh < 0 ) {
                currentDeck.indexh = 0;
              }

              if(currentDeck.indexv < 0 ) {
                currentDeck.indexv = 0;
              }

              slides[route] = currentDeck;

              socket.broadcast.emit('updateData', currentDeck);
            }
          };

      return {
        config: config
      };
    }();<|endoftext|>


<commit_before>var Board = require("../lib/board.js"),
    five = require("../lib/johnny-five.js"),
    es6 = require("es6-collections"),
    WeakMap = es6.WeakMap;

// Led instance private data
var priv = new WeakMap();
var colors = [ "red", "green", "blue" ];

function RGBLed( opts ) {
  if ( !(this instanceof RGBLed) ) {
    return new RGBLed( opts );
  }

  opts = Board.options( opts );

  this.board = Board.mount( opts );
  this.firmata = this.board.firmata;

  colors.forEach(function(color) {
    this[ color ] = new five.Led( opts[ color ] );
  }, this);

  priv.set(this, {
    red: 0,
    green: 0,
    blue: 0
  });
}

RGBLed.prototype.setColor = function( color ) {
  var red, green, blue;

  function hexToInt( val ) {
    return parseInt( val, 16 );
  }

  if ( typeof color === 'string' ) {
    red = hexToInt( color.slice(0, 2) );
    green = hexToInt( color.slice(2, 4) );
    blue = hexToInt( color.slice(4, 6) );
  } else {
    red = color[ 0 ];
    green = color[ 1 ];
    blue = color[ 2 ];
  }

  priv.set( this, {
    red: red,
    green: green,
    blue: blue
  });

  this.red.brightness( red );
  this.green.brightness( green );
  this.blue.brightness( blue );
};

RGBLed.prototype.on = function() {
  var brightness = priv.get( this )
  colors.forEach(function( color ) {
    this[ color ].on();
    this[ color ].brightness( brightness[ color ] );
  }, this);
};

RGBLed.prototype.off = function() {
  colors.forEach(function( color ) {
    this[ color ].off();
  }, this);
};

module.exports = RGBLed;<commit_msg>removes lib/rgbled.js<commit_after><|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var express = require('express'),
	mysql = require('mysql'),
	mssql = require('mssql'),
	async = require('async'),
	passport = require('passport'),
	flash = require('connect-flash');

var port = process.env.PORT || 8080;
	db = require('./config/database'),
	local = require('./config/local');

/**
 * Module configuration.
 */

var app = express();
// Setup connection to the databases.
var webapi = mysql.createConnection(db.mysql),
	mssql_conn = mssql.connect(db.mssql);

// Set up the express application.
app.configure(function () {
	app.use(express.static(__dirname + '/public'));
	app.set('views', __dirname + '/public');
	// Log every request to the console.
	app.use(express.logger('dev'));
	// Read cookies needed for authentication.
	app.use(express.cookieParser());
	// Get information from HTML forms.
	app.use(express.json());
	app.use(express.urlencoded());
	// Set up jade for templating.
	app.locals(local);
	app.set('view engine', 'jade');
	// Session secret.
	app.use(express.session({ secret: 'uopwebapi' }));
	app.use(passport.initialize());
	// Use persistent login sessions.
	app.use(passport.session());
	// Use connect-flash for flash messages stored in session.
	app.use(flash());
});

/**
 * Route cofiguration.
 */

// Load routes and pass in the application and passport instances.
require('./app/routes')(app, passport);

// Listen for connections.
app.listen(port, function () {
	console.log('Listening to port ' + port);
});<commit_msg>Added Google OAuth in the dependencies, updated the templating engine, and updated configuration data to use the new config file.<commit_after>/**
 * Module dependencies.
 */

var express = require('express'),
	mysql = require('mysql'),
	mssql = require('mssql'),
	async = require('async'),
	passport = require('passport'),
	flash = require('connect-flash'),
	GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;;

var port = process.env.PORT || 8080;
	config = require('./config/config'),
	local = require('./config/local');

/**
 * Module configuration.
 */

var app = express();
// Setup connection to the databases.
var webapi = mysql.createConnection(config.db.mysql),
	mssql_conn = mssql.connect(config.db.mssql);

// Set up the express application.
app.configure(function () {
	app.use(express.static(__dirname + '/public'));
	app.set('views', __dirname + '/public');
	// Log every request to the console.
	app.use(express.logger('dev'));
	// Read cookies needed for authentication.
	app.use(express.cookieParser());
	// Get information from HTML forms.
	app.use(express.json());
	app.use(express.urlencoded());
	// Set up ejs for templating.
	app.locals(local);
	app.set('view engine', 'ejs');
	// Session secret.
	app.use(express.session({ secret: config.express.secret }));
	app.use(passport.initialize());
	// Use persistent login sessions.
	app.use(passport.session());
	// Use connect-flash for flash messages stored in session.
	app.use(flash());
});

/**
 * Route cofiguration.
 */

// Load routes and pass in the application and passport instances.
require('./app/routes')(app, passport);

// Listen for connections.
app.listen(port, function () {
	console.log('Listening to port ' + port);
});<|endoftext|>


<commit_before>var subscriptions = new SubsManager();

Router.configure({
	layoutTemplate: 'layout',
	loadingTemplate: 'loading',
	notFoundTemplate: 'notFound'
});

Router.route('/gameStats/:_id', {
	name: 'gameStats',
	waitOn: function() {
		return subscriptions.subscribe('games');
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/gameDefinition/:_id', {
	name: 'gameDefinition',
	waitOn: function() {
		return [subscriptions.subscribe('clubs'), subscriptions.subscribe('games'), subscriptions.subscribe('federationConfig')];
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/participantsDefinition/:_id', {
	name: 'participantsDefinition',
	waitOn: function() {
		return [subscriptions.subscribe('clubs'), subscriptions.subscribe('games')];
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/myGames', {
	name: 'myGames',
	waitOn: function() {
		return subscriptions.subscribe('games');
	}
});

Router.route('/liveGames', {
	name: "liveGames",
	waitOn: function() {
		return subscriptions.subscribe('games');
	}
});

Router.route('/about', {
	name: 'about'
});

Router.route('/proVersionTest', {
	name: 'proVersionTest'
});

Router.route('/myAccount', {
	name: 'myAccount',
	data: function() {
		return Meteor.users.findOne({
			_id: Meteor.userId()
		});
	}
});

Router.route('/admin', {
	name: 'admin',
	waitOn: function() {
		return [subscriptions.subscribe('games'), subscriptions.subscribe('clubs'), subscriptions.subscribe("federationConfig")];
	}
});

Router.route('/createNewClub', {
	name: 'createNewClub',
	waitOn: function() {
		return subscriptions.subscribe("federationConfig");
	}
});

Router.route('/myClub', {
	name: 'myClub',
	waitOn: function() {
		return [subscriptions.subscribe('games'), subscriptions.subscribe('clubs')];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/newTeamDefinition', {
	name: 'newTeamDefinition',
	waitOn: function() {
		return [subscriptions.subscribe("federationConfig"), subscriptions.subscribe('clubs')];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/teamEdition', {
	name: 'teamEdition',
	waitOn: function() {
		return [subscriptions.subscribe('clubs'), subscriptions.subscribe('federationConfig')];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/', {
	name: 'home',
	fastRender: true
});
<commit_msg>Add subscription for games on home page<commit_after>var subscriptions = new SubsManager();

Router.configure({
	layoutTemplate: 'layout',
	loadingTemplate: 'loading',
	notFoundTemplate: 'notFound'
});

Router.route('/gameStats/:_id', {
	name: 'gameStats',
	waitOn: function() {
		return subscriptions.subscribe('games');
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/gameDefinition/:_id', {
	name: 'gameDefinition',
	waitOn: function() {
		return [subscriptions.subscribe('clubs'), subscriptions.subscribe('games'), subscriptions.subscribe('federationConfig')];
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/participantsDefinition/:_id', {
	name: 'participantsDefinition',
	waitOn: function() {
		return [subscriptions.subscribe('clubs'), subscriptions.subscribe('games')];
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});

Router.route('/myGames', {
	name: 'myGames',
	waitOn: function() {
		return subscriptions.subscribe('games');
	}
});

Router.route('/liveGames', {
	name: "liveGames",
	waitOn: function() {
		return subscriptions.subscribe('games');
	}
});

Router.route('/about', {
	name: 'about'
});

Router.route('/proVersionTest', {
	name: 'proVersionTest'
});

Router.route('/myAccount', {
	name: 'myAccount',
	data: function() {
		return Meteor.users.findOne({
			_id: Meteor.userId()
		});
	}
});

Router.route('/admin', {
	name: 'admin',
	waitOn: function() {
		return [subscriptions.subscribe('games'), subscriptions.subscribe('clubs'), subscriptions.subscribe("federationConfig")];
	}
});

Router.route('/createNewClub', {
	name: 'createNewClub',
	waitOn: function() {
		return subscriptions.subscribe("federationConfig");
	}
});

Router.route('/myClub', {
	name: 'myClub',
	waitOn: function() {
		return [subscriptions.subscribe('games'), subscriptions.subscribe('clubs')];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/newTeamDefinition', {
	name: 'newTeamDefinition',
	waitOn: function() {
		return [subscriptions.subscribe("federationConfig"), subscriptions.subscribe('clubs')];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/myClub/teamEdition', {
	name: 'teamEdition',
	waitOn: function() {
		return [subscriptions.subscribe('clubs'), subscriptions.subscribe('federationConfig')];
	},
	data: function() {
		return Clubs.findOne({
			createdBy: Meteor.userId()
		});
	}
});

Router.route('/', {
	name: 'home',
	waitOn: function() {
		return subscriptions.subscribe('games');
	},
	fastRender: true
});
<|endoftext|>


<commit_before>
const https = require("https");
const auth = require("./myNetatmoAuth.js");

//zürich
const cityId = 2657896;
//api key für guido.schnider@gmail.com from openweathermap.org
const apiKey = auth().apiKeyOpenweathermap;

module.exports = {
    sunshineForecast: function (response) {
        const result = {};
        result.sunshine = 0;
        result.type = "sun";
        doRequest(response, result);
    },
    thunderstormForecast: function (response) {
        const result = {};
        result.thunderstorm = 0;
        result.type = "thunderstorm";
        doRequest(response, result);
    }

};

function doRequest(response, result) {

    https.get("https://api.openweathermap.org/data/2.5/forecast?id=" + cityId + "&appid=" + apiKey, (resp) => {
        var data = "";
        // A chunk of data has been recieved.
        resp.on("data", (chunk) => {
            data += chunk;
        });
        resp.on("end", () => {
            const weather = JSON.parse(data);

            switch (result.type) {
                case "sun":
                    result.sunshine = 0;
                    if (weather.cnt > 2) {
                        //the sun shines only on daytime --> "d"
                        const hours3 = weather.list[0].sys.pod === "d";
                        const hours6 = weather.list[1].sys.pod === "d";
                        if (hours3 === "d" || hours6 === "d") {
                            for (var i = 0; i < 2; i++) {
                                const weatherId = weather.list[i].weather.id;
                                //weather cond. ids: https://openweathermap.org/weather-conditions
                                if (weatherId >= 800 && weatherId < 803) {
                                    result.sunshine = 1;
                                }
                            }
                        }
                    }
                    response.end(JSON.stringify(result));
                    break;

                case "thunderstorm":
                    result.thunderstorm = 0;
                    if (weather.cnt > 1) {
                        const weatherId = weather.list[0].weather.id;
                        //weather cond. ids: https://openweathermap.org/weather-conditions
                        if (weatherId >= 200 && weatherId < 232) {
                            result.thunderstorm = 1;
                        }
                    }
                    response.end(JSON.stringify(result));
                    break;
                default:
                    result.type = "error";
                    response.end(JSON.stringify(result));
                    break;
            }

        });
    }).on("error", (err) => {
        console.log("Error: " + err.message);
        response.end(JSON.stringify(result));
    });
}

<commit_msg>more var changes<commit_after>
const https = require("https");
const auth = require("./myNetatmoAuth.js");

//zürich
const cityId = 2657896;
//api key für guido.schnider@gmail.com from openweathermap.org
const apiKey = auth().apiKeyOpenweathermap;

module.exports = {
    sunshineForecast: function (response) {
        const result = {};
        result.sunshine = 0;
        result.type = "sun";
        doRequest(response, result);
    },
    thunderstormForecast: function (response) {
        const result = {};
        result.thunderstorm = 0;
        result.type = "thunderstorm";
        doRequest(response, result);
    }

};

function doRequest(response, result) {

    https.get("https://api.openweathermap.org/data/2.5/forecast?id=" + cityId + "&appid=" + apiKey, (resp) => {
        var data = "";
        // A chunk of data has been recieved.
        resp.on("data", (chunk) => {
            data += chunk;
        });
        resp.on("end", () => {
            const weather = JSON.parse(data);
            var weatherId = 0;
            switch (result.type) {
                case "sun":
                    result.sunshine = 0;
                    if (weather.cnt > 2) {
                        //the sun shines only on daytime --> "d"
                        const hours3 = weather.list[0].sys.pod === "d";
                        const hours6 = weather.list[1].sys.pod === "d";
                        if (hours3 === "d" || hours6 === "d") {
                            for (var i = 0; i < 2; i++) {
                                weatherId = weather.list[i].weather.id;
                                //weather cond. ids: https://openweathermap.org/weather-conditions
                                if (weatherId >= 800 && weatherId < 803) {
                                    result.sunshine = 1;
                                }
                            }
                        }
                    }
                    response.end(JSON.stringify(result));
                    break;

                case "thunderstorm":
                    result.thunderstorm = 0;
                    if (weather.cnt > 1) {
                        weatherId = weather.list[0].weather.id;
                        //weather cond. ids: https://openweathermap.org/weather-conditions
                        if (weatherId >= 200 && weatherId < 232) {
                            result.thunderstorm = 1;
                        }
                    }
                    response.end(JSON.stringify(result));
                    break;
                default:
                    result.type = "error";
                    response.end(JSON.stringify(result));
                    break;
            }

        });
    }).on("error", (err) => {
        console.log("Error: " + err.message);
        response.end(JSON.stringify(result));
    });
}

<|endoftext|>


<commit_before>var express = require('express');
var sentiment = require('sentiment');

var app = express();

app.use(express.static('public'));

app.get('/', function (req, res) {
  res.send('index.html');
});

var port = process.env.port || 3000;

var server = app.listen(port, function () {

  var host = server.address().address;

  console.log('Example app listening at http://%s:%s', host, port);

});<commit_msg>remove sentiment require from app.js<commit_after>var express = require('express');
// var sentiment = require('sentiment');

var app = express();

app.use(express.static('public'));

app.get('/', function (req, res) {
  res.send('index.html');
});

var port = process.env.port || 3000;

var server = app.listen(port, function () {

  var host = server.address().address;

  console.log('Example app listening at http://%s:%s', host, port);

});<|endoftext|>


<commit_before>Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'notFound',
  waitOn: function() {
    return [Meteor.subscribe('projects'),
            Meteor.subscribe('notifications')];
  }
});

Router.route('/projects/:_id/edit', {
  name: 'projectEdit',
  data: function() { return Projects.findOne(this.params._id); }
});

Router.route('/projects/:projectId/findings/:_id/edit', {
  name: 'findingEdit',
  waitOn: function() {
    return [Meteor.subscribe('findings', this.params.projectId),
            Meteor.subscribe('sources', this.params.projectId)];
  },
  data: function() { return Findings.findOne(this.params._id); }
});

Router.route('/projects/:projectId/sources/:_id/edit', {
  name: 'sourceEdit',
  waitOn: function() {
    return [Meteor.subscribe('sources', this.params.projectId),
            Meteor.subscribe('findings', this.params.projectId)];
  },
  data: function() { return Sources.findOne(this.params._id); }
});

Router.route('/projects/:_id', {
  name: 'projectPage',
  waitOn: function() {
    return [Meteor.subscribe('findings', this.params._id),
            Meteor.subscribe('sources', this.params._id)];
  },
  data: function() { return Projects.findOne(this.params._id); }
});

Router.route('/new', {name: 'projectNew'});

Router.route('/', {name: 'projectsList'});

var requireLogin = function() {
  if (! Meteor.user()) {
    if (Meteor.loggingIn()) {
      this.render(this.loadingTemplate);
    } else {
      this.render('accessDenied');
    }
  } else {
    this.next();
  }
}

Router.onBeforeAction('dataNotFound', {only: 'projectPage'});
Router.onBeforeAction(requireLogin);
<commit_msg>More consistent route.<commit_after>Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'notFound',
  waitOn: function() {
    return [Meteor.subscribe('projects'),
            Meteor.subscribe('notifications')];
  }
});

Router.route('/projects/:_id/edit', {
  name: 'projectEdit',
  data: function() { return Projects.findOne(this.params._id); }
});

Router.route('/projects/:projectId/findings/:_id/edit', {
  name: 'findingEdit',
  waitOn: function() {
    return [Meteor.subscribe('findings', this.params.projectId),
            Meteor.subscribe('sources', this.params.projectId)];
  },
  data: function() { return Findings.findOne(this.params._id); }
});

Router.route('/projects/:projectId/sources/:_id/edit', {
  name: 'sourceEdit',
  waitOn: function() {
    return [Meteor.subscribe('sources', this.params.projectId),
            Meteor.subscribe('findings', this.params.projectId)];
  },
  data: function() { return Sources.findOne(this.params._id); }
});

Router.route('/projects/new', {name: 'projectNew'});

Router.route('/projects/:_id', {
  name: 'projectPage',
  waitOn: function() {
    return [Meteor.subscribe('findings', this.params._id),
            Meteor.subscribe('sources', this.params._id)];
  },
  data: function() { return Projects.findOne(this.params._id); }
});

Router.route('/', {name: 'projectsList'});

var requireLogin = function() {
  if (! Meteor.user()) {
    if (Meteor.loggingIn()) {
      this.render(this.loadingTemplate);
    } else {
      this.render('accessDenied');
    }
  } else {
    this.next();
  }
}

Router.onBeforeAction('dataNotFound', {only: 'projectPage'});
Router.onBeforeAction(requireLogin);
<|endoftext|>


<commit_before>/**
 * @file Ship App
 * @author treelite(c.xinle@gmail.com)
 */

'use strict';

import fs from 'fs';
import path from 'path';
import extend from 'xtend';
import express from 'express';
import bodyParser from 'body-parser';

import pipe from './lib/pipe';
import Meta from './lib/meta';
import locker from './lib/locker';
import logger from './lib/logger';
import exists from './lib/util/exists';

let options = {
    port: 80,
    log: '/var/log/ship',
    meta: '/etc/ship/ship.json'
};

let file = process.argv[2];
if (file && exists(file)) {
    let config = JSON.parse(fs.readFileSync(file, 'utf8'));
    let dir = path.dirname(file);
    if (config.log) {
        config.log = path.resolve(dir, config.log);
    }
    if (config.meta) {
        config.meta = path.resolve(dir, config.meta);
    }
    options = extend(options, config);
}

let log = logger(options.log);

let meta = new Meta(options.meta);
meta.on('error', error => log.error('meta: %s', error));

let lock = locker();

let app = express();

// 访问日志
app.use((req, res, next) => {
    res.on('finish', () => {
        if (res.statusCode >= 500) {
            log.error('access: %d %s', res.statusCode, req.url);
        }
        else {
            log.info('access: %d %s', res.statusCode, req.url);
        }
    });
    next();
});

app.use(bodyParser.text({type: '*/*'}));

// FIXME
// 规范错误处理
app.post('/:repository/:event', (req, res) => {
    let {repository, event} = req.params;
    let action = meta.get(repository, event);

    if (!action) {
        return res.status(404).end();
    }

    if (!lock(`${repository}-${event}`)) {
        return res.status(403).end();
    }

    let data;
    try {
        data = JSON.parse(decodeURIComponent(req.body));
    }
    catch (e) {
        return res.status(400).end();
    }

    log.info('pipe receive', extend({data: JSON.stringify(data)}, req.params));
    pipe(action, data)
        .then(
            info => log.info('pipe success: %s', JSON.stringify(info), req.params),
            error => log.error('pipe fail: %s', error, req.params)
        );

    res.status(200).end();
});

app.use((error, req, res, next) => {
    log.error('unkown error: %s %s', error.message, req.url, {stack: error.stack});
    res.status(500).end();
});

app.use((req, res) => {
    res.status(404).end();
});

app.listen(options.port);

log.info('server start at %d', options.port);
<commit_msg>Modify meta file path<commit_after>/**
 * @file Ship App
 * @author treelite(c.xinle@gmail.com)
 */

'use strict';

import fs from 'fs';
import path from 'path';
import extend from 'xtend';
import express from 'express';
import bodyParser from 'body-parser';

import pipe from './lib/pipe';
import Meta from './lib/meta';
import locker from './lib/locker';
import logger from './lib/logger';
import exists from './lib/util/exists';

let options = {
    port: 80,
    log: '/var/log/ship',
    meta: '/etc/ship/meta.json'
};

let file = process.argv[2];
if (file && exists(file)) {
    let config = JSON.parse(fs.readFileSync(file, 'utf8'));
    let dir = path.dirname(file);
    if (config.log) {
        config.log = path.resolve(dir, config.log);
    }
    if (config.meta) {
        config.meta = path.resolve(dir, config.meta);
    }
    options = extend(options, config);
}

let log = logger(options.log);

let meta = new Meta(options.meta);
meta.on('error', error => log.error('meta: %s', error));

let lock = locker();

let app = express();

// 访问日志
app.use((req, res, next) => {
    res.on('finish', () => {
        if (res.statusCode >= 500) {
            log.error('access: %d %s', res.statusCode, req.url);
        }
        else {
            log.info('access: %d %s', res.statusCode, req.url);
        }
    });
    next();
});

app.use(bodyParser.text({type: '*/*'}));

// FIXME
// 规范错误处理
app.post('/:repository/:event', (req, res) => {
    let {repository, event} = req.params;
    let action = meta.get(repository, event);

    if (!action) {
        return res.status(404).end();
    }

    if (!lock(`${repository}-${event}`)) {
        return res.status(403).end();
    }

    let data;
    try {
        data = JSON.parse(decodeURIComponent(req.body));
    }
    catch (e) {
        return res.status(400).end();
    }

    log.info('pipe receive', extend({data: JSON.stringify(data)}, req.params));
    pipe(action, data)
        .then(
            info => log.info('pipe success: %s', JSON.stringify(info), req.params),
            error => log.error('pipe fail: %s', error, req.params)
        );

    res.status(200).end();
});

app.use((error, req, res, next) => {
    log.error('unkown error: %s %s', error.message, req.url, {stack: error.stack});
    res.status(500).end();
});

app.use((req, res) => {
    res.status(404).end();
});

app.listen(options.port);

log.info('server start at %d', options.port);
<|endoftext|>


<commit_before>var micAccess = document.getElementById("micAccess");
var backgroundChange = document.getElementById("backgroundChange");
var backUrl = document.getElementById("backUrl");
var preDefThemes = document.getElementById("preDefThemes");
var theme;
var theValue;

if(micAccess) {
    micAccess.addEventListener("click", () => {
        navigator.webkitGetUserMedia({
            audio: true
        }, function (stream) {
            stream.stop();
        }, function () {
            console.log("no access");
        });
    });
}
if(preDefThemes) {
preDefThemes.addEventListener("click",(e) => {
    if(e.target!==e.currentTarget){
        theme= e.target.id;
        console.log(theme);
    }

    e.stopPropagation;
    });
}

if(backgroundChange) {
    backgroundChange.addEventListener("submit", (e) => {
        e.preventDefault();
        theValue = backUrl.value;
        if (!theValue) {
            alert("Error: No value specified");
        } else {
            localStorage.setItem("theValue", theValue);
            alert("Successfully stored");
        }
    });
}
<commit_msg>Fixed Theme change<commit_after>var micAccess = document.getElementById("micAccess");
var backgroundChange = document.getElementById("backgroundChange");
var backUrl = document.getElementById("backUrl");
var preDefThemes = document.getElementById("preDefThemes");
var submit = document.getElementById("submit");
var theme;
var theValue;

if(micAccess) {
    micAccess.addEventListener("click", () => {
        navigator.webkitGetUserMedia({
            audio: true
        }, function (stream) {
            stream.stop();
        }, function () {
            console.log("no access");
        });
    });
}
if(preDefThemes) {
preDefThemes.addEventListener("click",(e) => {
    if(e.target!==e.currentTarget){
        theme= e.target.id;
        console.log(theme);
    }

    e.stopPropagation;
    });
}

if(submit) {
    submit.addEventListener("click",()=>{
         localStorage.setItem("theme",theme);
         console.log("success");
         alert("success");
    });
}

if(backgroundChange) {
    backgroundChange.addEventListener("submit", (e) => {
        e.preventDefault();
        theValue = backUrl.value;
        if (!theValue) {
            alert("Error: No value specified");
        } else {
            localStorage.setItem("theValue", theValue);
            alert("Successfully stored");
        }
    });
}
<|endoftext|>