<commit_before>var sp = require('schemapack');             // Serialization module
var bp = require('binary-parser');          // Binary parser module
var Parser = bp.Parser;
var toggle = require('endian-toggle');

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Headers for encoding (Schemapack) //////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// rndis header for encoding
var rndis_1 = sp.build([
    { msg_type: 'uint32'},      // always
    { msg_len: 'uint32'},       // length of header + data + payload
    { data_offset: 'uint32'},   // offset from data until payload
    { data_len: 'uint32'},      // length of payload
    { band_offset: 'uint32'},   // not used here
    { pad: 'string'}
]);
var rndis_2 = sp.build([
    { band_len: 'uint32'},      // not used here
    { out_band_elements: 'uint32'}, //not used here
    { packet_offset: 'uint32'},     // not used here
    { packet_info_len: 'uint32'},   // not used here
    { reserved_first: 'uint32'},    // not used here
    { reserved_second: 'uint32'},   // not used here
    { pad: 'string'}
]);

// ether2 header for encoding
var ethhdr_e = sp.build([
    { h_dest:{0:'uint8',1:'uint8',2:'uint8',3:'uint8',4:'uint8',5:'uint8'} },       // Destination address
    { h_source:{0:'uint8',1:'uint8',2:'uint8',3:'uint8',4:'uint8',5:'uint8'} },     // Source address
    { h_proto : 'uint16' },        // Protocol Id
    { pad: 'string' }              // Padding to shift extra bit to last for Schemapack
]);

// ipv4 header in two parts for encoding
var iphdr1 = sp.build([
    { ver_hl: 'uint8'},            // version and header length each of 4 bits
    { tos: 'uint8'},               // Type of service
    { tot_len: 'uint16'},          // Total length of IP datagram
    { id: 'uint16'},               // Identfication
    { frag_off: 'uint16'},         // Flag and Fragment offset
    { ttl: 'uint8'},               // Time to live
    { protocol: 'uint8'},          // Protocol UDP/IP here
    { check: 'uint16'},            // Checksum for IP header
    { pad: 'string'}               // Padding to shift extra bit to last for Schemapack
    ]);
var iphdr2 = sp.build([
    { saddr: {0:'uint8',1:'uint8',2:'uint8',3:'uint8'} },   // Source IP address (Server)
    { daddr: {0:'uint8',1:'uint8',2:'uint8',3:'uint8'} },   // Destination IP address (BB)
    { pad: 'string'}
]);

// UDP Packet for encoding
var udp_e = sp.build([
    { udpSrc: 'uint16'},            // Server UDP port
    { udpDst: 'uint16'},            // BB UDP port
    { udpLen: 'uint16'},            // UDP data length + UDP header length
    { chkSum: 'uint16'},            // Checksum
    { pad: 'string'}
])

// BOOTP packet
var bootp1 = sp.build([
    { opcode: 'uint8'},             // Operation code, 1: BOOTREQUEST, 2: BOOTREPLY
    { hw: 'uint8'},                 // Hardware Type, 1: Ethernet
    { hw_length: 'uint8'},          // Hardware Address length
    { hopcount: 'uint8'},           // Set to 0 by client before transmitting
    { xid: 'uint32'},               // Transaction ID
    { secs: 'uint16'},              // Seconds since client started trying to boot
    { flags: 'uint16'},             // Optional flag, not used
    { ciaddr: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},    // Client IP Address
    { pad: 'string'}
]);
var bootp2 = sp.build([
    { yiaddr: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},        // Your IP Address ( Server assigns to client )
    { server_ip: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},     // Server IP Address
    { bootp_gw_ip: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},   // Gateway IP Address
    { hwaddr: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8'}},  // MAC Address of client (BB)
    { pad: 'string'}
]);
var bootp_servername = sp.build([
    { servername: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8', 6:'uint8', 7:'uint8',
        8:'uint8', 9:'uint8',}},                                    // Server Name
    { pad: 'string'}
]);
var bootp_bootfile = sp.build([
    { bootfile: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8'}},   // Name of File to boot
    { pad: 'string'}
]);
// Max array size supported is 9, splitting vendor field in two parts
var bootp_vendor1 = sp.build([       // Vendor extensions (Subnet here for this project)
    { vendor1: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8', 6:'uint8', 7:'uint8', 8:'uint8'}},
    { pad: 'string'}
]);
var bootp_vendor2 = sp.build([
    { vendor2: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8', 6:'uint8', 7:'uint8'}},
    { pad: 'string'}
]);

// ARP header for response
var arphdr_e = sp.build([
    { htype: 'uint16'},                     // Hardware type
    { ptype: 'uint16'},                     // Protocol type
    { hlen: 'uint8'},                       // Hardware Address length
    { plen: 'uint8'},                       // Protocol Address length
    { opcode: 'uint16'},                    // Operation code, here 2 for reply
    { hw_source: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8'}},      // Source MAC address
    { ip_source: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},                            // Source IP address
    { hw_dest: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8'}},        // Destination MAC address
    { ip_dest: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},                              // Destination IP address
    { pad: 'string'}
])

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Headers for parsing (Binary-Praser) /////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// ether header
var ethhdr = new Parser()
    .array('h_dest',{
        type: 'uint8',
        length: 6
    })
    .array('h_source',{
        type: 'uint8',
        length: 6
    })
    .int16be('h_proto');

// ARP header
var arphdr = new Parser()
    .uint16be('htype')
    .uint16be('ptype')
    .uint8('hlen')
    .uint8('plen')
    .uint16be('opcode')
    .array('hw_source',{
        type: 'uint8',
        length: 6
    })
    .array('ip_source',{
        type: 'uint8',
        length: 4
    })
    .array('hw_dest',{
        type: 'uint8',
        length: 6
    })
    .array('ip_dest',{
        type: 'uint8',
        length: 4
    });

// UDP packet
var udp = new Parser()
    .uint16be('udpSrc')
    .uint16be('udpDest')
    .uint16be('udpLen')
    .uint16be('chkSum');

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Packet make functions /////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Function for rndis data packet
function make_rndis(data_length){
    var rndis1 = [
        { msg_type: 0x00000001},
        { msg_len: data_length+44},
        { data_offset: 0x24},
        { data_len: data_length},
        { band_offset: 0}
    ];
    var rndis2 =[
        { band_len: 0},
        { out_band_elements: 0},
        { packet_offset: 0},
        { packet_info_len: 0},
        { reserved_first: 0},
        { reserved_second: 0}
    ];

    var buf1 = fix_buff(rndis_1.encode(rndis1));
    var buf2 = fix_buff(rndis_2.encode(rndis2));
    var data = Buffer.concat([buf1, buf2], 44);
    return toggle(data, 32);    // convert byte order to little endian
}

// Function for ether2 data packet
function make_ether2(dest, source, proto){
    var eth = [
        { h_dest: dest},
        { h_source: source},
        { h_proto: proto}
    ];
    var data = fix_buff(ethhdr_e.encode(eth));
    return data;
}

// Function for ipv4 header packet
function make_ipv4(src_addr, dst_addr, proto, id_, total_len){
    var ip1 = [
        { ver_hl: 69},
        { tos: 0},
        { tot_len: total_len},
        { id: id_},
        { frag_off: 0},
        { ttl: 64},
        { protocol: proto},
        { check: 0xF648}
    ];
    var ip2 = [
        { saddr: src_addr},
        { daddr: dst_addr}
    ];
    var buf1 = fix_buff(iphdr1.encode(ip1));
    var buf2 = fix_buff(iphdr2.encode(ip2));
    var data = Buffer.concat([buf1, buf2], 20);
    return data;
}

// Function for UDP packet
function make_udp(udpData_len, srcPort, dstPort){
    var udp = [
        { udpSrc: srcPort},
        { udpDst: dstPort},
        { udpLen: udpData_len+8},
        { chkSum: 0}
    ];
    return fix_buff(udp_e.encode(udp));
}

// Function for BOOTP packet
function make_bootp(server_name, file_name, xid_, hw_dest, BB_ip, serverIP){
    var bootp_1 =[
        { opcode: 2},
        { hw: 1},
        { hw_length: 6},
        { hopcount: 0},
        { xid: xid_},
        { secs: 0},
        { flags: 0},
        { ciaddr: [0,0,0,0]}
    ];
    var bootp_2 = [
        { yiaddr: BB_ip},
        { server_ip: serverIP},
        { bootp_gw_ip: serverIP},
        { hwaddr: hw_dest}
    ];
    var servername = [ { servername: server_name} ];
    var bootfile = [ { bootfile: file_name} ];
    var vendor1 = [ { vendor1: [ 99, 130, 83, 99, 1, 4, 255, 255, 255] } ];
    var vendor2 = [ { vendor2: [ 0, 3, 4, 192, 168, 1, 9, 0xFF] } ];
    var buf1 = fix_buff(bootp1.encode(bootp_1));
    var buf2 = fix_buff(bootp2.encode(bootp_2));
    var buf2_ = Buffer.alloc(10);           // Remaining 10 bytes out of 16 of hwaddr
    var buf3 = fix_buff(bootp_servername.encode(servername));
    var buf3_ = Buffer.alloc(54);           // Remaining 54 bytes out of 64 of servername
    var buf4 = fix_buff(bootp_bootfile.encode(bootfile));
    var buf4_ = Buffer.alloc(123);          // Remaining 123 bytes out of 128 of bootfile
    var buf5 = fix_buff(bootp_vendor1.encode(vendor1));
    var buf5_ = fix_buff(bootp_vendor2.encode(vendor2));
    var buf5__ = Buffer.alloc(47);           // Remaining 47 bytes out of 64 of vendor
    return Buffer.concat([buf1, buf2, buf2_, buf3, buf3_, buf4, buf4_, buf5, buf5_, buf5__], 300);

}

// Function for ARP response
function make_arp(opcode, hw_source, ip_source, hw_dest, ip_dest){
    var arp = [
        { htype: 1},
        { ptype: 0x0800},
        { hlen: 6},
        { plen: 4},
        { opcode: opcode},
        { hw_source: hw_source},
        { ip_source: ip_source},
        { hw_dest: hw_dest},
        { ip_dest: ip_dest}
    ];
    return fix_buff(arphdr_e.encode(arp));
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Packet decode functions ///////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Decode ether packet
function decode_ether(buf){
    return ethhdr.parse(buf);
}

// Parse ARP header
function parse_arp(buf){
    return arphdr.parse(buf);
}

// Parse udp packet
function parse_udp(buf){
    return udp.parse(buf);
}

///////////////////////////////////////// Function to remove extra byte from last /////////////////////////////////
function fix_buff(buf){
    var buf_fix = Buffer.alloc(buf.length-1,0,'hex');
    buf.copy(buf_fix, 0, 0, buf.length-1);
    return buf_fix;
}

exports.make_rndis = make_rndis;
exports.decode_ether = decode_ether;
exports.make_ether2 = make_ether2;
exports.make_ipv4 = make_ipv4;
exports.make_udp = make_udp;
exports.make_bootp = make_bootp;
exports.parse_arp = parse_arp;
exports.make_arp = make_arp;
exports.parse_udp = parse_udp;<commit_msg>Implemented make_tftp<commit_after>var sp = require('schemapack');             // Serialization module
var bp = require('binary-parser');          // Binary parser module
var Parser = bp.Parser;
var toggle = require('endian-toggle');

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Headers for encoding (Schemapack) //////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// rndis header for encoding
var rndis_1 = sp.build([
    { msg_type: 'uint32'},      // always
    { msg_len: 'uint32'},       // length of header + data + payload
    { data_offset: 'uint32'},   // offset from data until payload
    { data_len: 'uint32'},      // length of payload
    { band_offset: 'uint32'},   // not used here
    { pad: 'string'}
]);
var rndis_2 = sp.build([
    { band_len: 'uint32'},      // not used here
    { out_band_elements: 'uint32'}, //not used here
    { packet_offset: 'uint32'},     // not used here
    { packet_info_len: 'uint32'},   // not used here
    { reserved_first: 'uint32'},    // not used here
    { reserved_second: 'uint32'},   // not used here
    { pad: 'string'}
]);

// ether2 header for encoding
var ethhdr_e = sp.build([
    { h_dest:{0:'uint8',1:'uint8',2:'uint8',3:'uint8',4:'uint8',5:'uint8'} },       // Destination address
    { h_source:{0:'uint8',1:'uint8',2:'uint8',3:'uint8',4:'uint8',5:'uint8'} },     // Source address
    { h_proto : 'uint16' },        // Protocol Id
    { pad: 'string' }              // Padding to shift extra bit to last for Schemapack
]);

// ipv4 header in two parts for encoding
var iphdr1 = sp.build([
    { ver_hl: 'uint8'},            // version and header length each of 4 bits
    { tos: 'uint8'},               // Type of service
    { tot_len: 'uint16'},          // Total length of IP datagram
    { id: 'uint16'},               // Identfication
    { frag_off: 'uint16'},         // Flag and Fragment offset
    { ttl: 'uint8'},               // Time to live
    { protocol: 'uint8'},          // Protocol UDP/IP here
    { check: 'uint16'},            // Checksum for IP header
    { pad: 'string'}               // Padding to shift extra bit to last for Schemapack
    ]);
var iphdr2 = sp.build([
    { saddr: {0:'uint8',1:'uint8',2:'uint8',3:'uint8'} },   // Source IP address (Server)
    { daddr: {0:'uint8',1:'uint8',2:'uint8',3:'uint8'} },   // Destination IP address (BB)
    { pad: 'string'}
]);

// UDP Packet for encoding
var udp_e = sp.build([
    { udpSrc: 'uint16'},            // Server UDP port
    { udpDst: 'uint16'},            // BB UDP port
    { udpLen: 'uint16'},            // UDP data length + UDP header length
    { chkSum: 'uint16'},            // Checksum
    { pad: 'string'}
])

// BOOTP packet
var bootp1 = sp.build([
    { opcode: 'uint8'},             // Operation code, 1: BOOTREQUEST, 2: BOOTREPLY
    { hw: 'uint8'},                 // Hardware Type, 1: Ethernet
    { hw_length: 'uint8'},          // Hardware Address length
    { hopcount: 'uint8'},           // Set to 0 by client before transmitting
    { xid: 'uint32'},               // Transaction ID
    { secs: 'uint16'},              // Seconds since client started trying to boot
    { flags: 'uint16'},             // Optional flag, not used
    { ciaddr: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},    // Client IP Address
    { pad: 'string'}
]);
var bootp2 = sp.build([
    { yiaddr: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},        // Your IP Address ( Server assigns to client )
    { server_ip: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},     // Server IP Address
    { bootp_gw_ip: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},   // Gateway IP Address
    { hwaddr: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8'}},  // MAC Address of client (BB)
    { pad: 'string'}
]);
var bootp_servername = sp.build([
    { servername: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8', 6:'uint8', 7:'uint8',
        8:'uint8', 9:'uint8',}},                                    // Server Name
    { pad: 'string'}
]);
var bootp_bootfile = sp.build([
    { bootfile: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8'}},   // Name of File to boot
    { pad: 'string'}
]);
// Max array size supported is 9, splitting vendor field in two parts
var bootp_vendor1 = sp.build([       // Vendor extensions (Subnet here for this project)
    { vendor1: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8', 6:'uint8', 7:'uint8', 8:'uint8'}},
    { pad: 'string'}
]);
var bootp_vendor2 = sp.build([
    { vendor2: {0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8', 6:'uint8', 7:'uint8'}},
    { pad: 'string'}
]);

// ARP header for response
var arphdr_e = sp.build([
    { htype: 'uint16'},                     // Hardware type
    { ptype: 'uint16'},                     // Protocol type
    { hlen: 'uint8'},                       // Hardware Address length
    { plen: 'uint8'},                       // Protocol Address length
    { opcode: 'uint16'},                    // Operation code, here 2 for reply
    { hw_source: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8'}},      // Source MAC address
    { ip_source: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},                            // Source IP address
    { hw_dest: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8', 4:'uint8', 5:'uint8'}},        // Destination MAC address
    { ip_dest: { 0:'uint8', 1:'uint8', 2:'uint8', 3:'uint8'}},                              // Destination IP address
    { pad: 'string'}
])

// TFTP packet
var tftp = sp.build([
    { opcode: 'uint16'},                    // Operation code, here 3 for read/write next block of data
    { blk_number: 'uint16'},                // Block number
    { pad: 'string'}
]);

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Headers for parsing (Binary-Praser) /////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// ether header
var ethhdr = new Parser()
    .array('h_dest',{
        type: 'uint8',
        length: 6
    })
    .array('h_source',{
        type: 'uint8',
        length: 6
    })
    .int16be('h_proto');

// ARP header
var arphdr = new Parser()
    .uint16be('htype')
    .uint16be('ptype')
    .uint8('hlen')
    .uint8('plen')
    .uint16be('opcode')
    .array('hw_source',{
        type: 'uint8',
        length: 6
    })
    .array('ip_source',{
        type: 'uint8',
        length: 4
    })
    .array('hw_dest',{
        type: 'uint8',
        length: 6
    })
    .array('ip_dest',{
        type: 'uint8',
        length: 4
    });

// UDP packet
var udp = new Parser()
    .uint16be('udpSrc')
    .uint16be('udpDest')
    .uint16be('udpLen')
    .uint16be('chkSum');

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Packet make functions /////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Function for rndis data packet
function make_rndis(data_length){
    var rndis1 = [
        { msg_type: 0x00000001},
        { msg_len: data_length+44},
        { data_offset: 0x24},
        { data_len: data_length},
        { band_offset: 0}
    ];
    var rndis2 =[
        { band_len: 0},
        { out_band_elements: 0},
        { packet_offset: 0},
        { packet_info_len: 0},
        { reserved_first: 0},
        { reserved_second: 0}
    ];

    var buf1 = fix_buff(rndis_1.encode(rndis1));
    var buf2 = fix_buff(rndis_2.encode(rndis2));
    var data = Buffer.concat([buf1, buf2], 44);
    return toggle(data, 32);    // convert byte order to little endian
}

// Function for ether2 data packet
function make_ether2(dest, source, proto){
    var eth = [
        { h_dest: dest},
        { h_source: source},
        { h_proto: proto}
    ];
    var data = fix_buff(ethhdr_e.encode(eth));
    return data;
}

// Function for ipv4 header packet
function make_ipv4(src_addr, dst_addr, proto, id_, total_len){
    var ip1 = [
        { ver_hl: 69},
        { tos: 0},
        { tot_len: total_len},
        { id: id_},
        { frag_off: 0},
        { ttl: 64},
        { protocol: proto},
        { check: 0xF648}
    ];
    var ip2 = [
        { saddr: src_addr},
        { daddr: dst_addr}
    ];
    var buf1 = fix_buff(iphdr1.encode(ip1));
    var buf2 = fix_buff(iphdr2.encode(ip2));
    var data = Buffer.concat([buf1, buf2], 20);
    return data;
}

// Function for UDP packet
function make_udp(udpData_len, srcPort, dstPort){
    var udp = [
        { udpSrc: srcPort},
        { udpDst: dstPort},
        { udpLen: udpData_len+8},
        { chkSum: 0}
    ];
    return fix_buff(udp_e.encode(udp));
}

// Function for BOOTP packet
function make_bootp(server_name, file_name, xid_, hw_dest, BB_ip, serverIP){
    var bootp_1 =[
        { opcode: 2},
        { hw: 1},
        { hw_length: 6},
        { hopcount: 0},
        { xid: xid_},
        { secs: 0},
        { flags: 0},
        { ciaddr: [0,0,0,0]}
    ];
    var bootp_2 = [
        { yiaddr: BB_ip},
        { server_ip: serverIP},
        { bootp_gw_ip: serverIP},
        { hwaddr: hw_dest}
    ];
    var servername = [ { servername: server_name} ];
    var bootfile = [ { bootfile: file_name} ];
    var vendor1 = [ { vendor1: [ 99, 130, 83, 99, 1, 4, 255, 255, 255] } ];
    var vendor2 = [ { vendor2: [ 0, 3, 4, 192, 168, 1, 9, 0xFF] } ];
    var buf1 = fix_buff(bootp1.encode(bootp_1));
    var buf2 = fix_buff(bootp2.encode(bootp_2));
    var buf2_ = Buffer.alloc(10);           // Remaining 10 bytes out of 16 of hwaddr
    var buf3 = fix_buff(bootp_servername.encode(servername));
    var buf3_ = Buffer.alloc(54);           // Remaining 54 bytes out of 64 of servername
    var buf4 = fix_buff(bootp_bootfile.encode(bootfile));
    var buf4_ = Buffer.alloc(123);          // Remaining 123 bytes out of 128 of bootfile
    var buf5 = fix_buff(bootp_vendor1.encode(vendor1));
    var buf5_ = fix_buff(bootp_vendor2.encode(vendor2));
    var buf5__ = Buffer.alloc(47);           // Remaining 47 bytes out of 64 of vendor
    return Buffer.concat([buf1, buf2, buf2_, buf3, buf3_, buf4, buf4_, buf5, buf5_, buf5__], 300);

}

// Function for ARP response
function make_arp(opcode, hw_source, ip_source, hw_dest, ip_dest){
    var arp = [
        { htype: 1},
        { ptype: 0x0800},
        { hlen: 6},
        { plen: 4},
        { opcode: opcode},
        { hw_source: hw_source},
        { ip_source: ip_source},
        { hw_dest: hw_dest},
        { ip_dest: ip_dest}
    ];
    return fix_buff(arphdr_e.encode(arp));
}

// Function for TFTP packet
function make_tftp(opcode, blk_number){
    var tftp_data = [
        { opcode: opcode},
        { blk_number: blk_number}
    ];
    return fix_buff(tftp.encode(tftp_data));
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Packet decode functions ///////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Decode ether packet
function decode_ether(buf){
    return ethhdr.parse(buf);
}

// Parse ARP header
function parse_arp(buf){
    return arphdr.parse(buf);
}

// Parse udp packet
function parse_udp(buf){
    return udp.parse(buf);
}

///////////////////////////////////////// Function to remove extra byte from last /////////////////////////////////
function fix_buff(buf){
    var buf_fix = Buffer.alloc(buf.length-1,0,'hex');
    buf.copy(buf_fix, 0, 0, buf.length-1);
    return buf_fix;
}

exports.make_rndis = make_rndis;
exports.decode_ether = decode_ether;
exports.make_ether2 = make_ether2;
exports.make_ipv4 = make_ipv4;
exports.make_udp = make_udp;
exports.make_bootp = make_bootp;
exports.parse_arp = parse_arp;
exports.make_arp = make_arp;
exports.parse_udp = parse_udp;<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    rget = require('rget'),
    async = require('flatiron').common.async;

function render(template, data) {
  var re = /\{\{ ?([a-zA-Z0-9\.\-]+) ?\}\}/g;
  return template.replace(re, function (match, name) {
    return rget(data, name);
  });
}

exports.file = function (file, config, callback) {
  fs.readFile(file, function (err, data) {
    if (err) {
      return callback(err);
    }

    fs.writeFile(file, render(data.toString('utf8'), config), callback);
  });
};

exports.directory = function (dir, config, callback) {
  fs.readdir(dir, function (err, files) {
    if (err) {
      if (err.code === 'ENOENT') {
        //
        // Directory doesn't exist, there's nothing to template. Not a big deal.
        //
        return callback();
      }
      return callback(err);
    }

    async.forEach(
      files,
      function (file, next) {
        return exports.file(path.join(dir, file), config, next);
      },
      callback
    );
  });
};
<commit_msg>[api] `JSON.stringify` objects while templating<commit_after>var fs = require('fs'),
    path = require('path'),
    rget = require('rget'),
    async = require('flatiron').common.async;

function render(template, data) {
  var re = /\{\{ ?([a-zA-Z0-9\.\-]+) ?\}\}/g;
  return template.replace(re, function (match, name) {
    var value = rget(data, name);
    if (typeof value === 'object') {
      value = JSON.stringify(value);
    }
    return value;
  });
}

exports.file = function (file, config, callback) {
  fs.readFile(file, function (err, data) {
    if (err) {
      return callback(err);
    }

    fs.writeFile(file, render(data.toString('utf8'), config), callback);
  });
};

exports.directory = function (dir, config, callback) {
  fs.readdir(dir, function (err, files) {
    if (err) {
      if (err.code === 'ENOENT') {
        //
        // Directory doesn't exist, there's nothing to template. Not a big deal.
        //
        return callback();
      }
      return callback(err);
    }

    async.forEach(
      files,
      function (file, next) {
        return exports.file(path.join(dir, file), config, next);
      },
      callback
    );
  });
};
<|endoftext|>


<commit_before>Package.describe({
    summary: "Accounts Templates unstyled.",
    version: "1.2.3",
    name: "useraccounts:unstyled",
    git: "https://github.com/meteor-useraccounts/unstyled.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.2.3",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_unstyled.css"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:unstyled",
        "useraccounts:core@1.2.3",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<commit_msg>minor release - Bump to version 1.3.0<commit_after>Package.describe({
    summary: "Accounts Templates unstyled.",
    version: "1.3.0",
    name: "useraccounts:unstyled",
    git: "https://github.com/meteor-useraccounts/unstyled.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.3.0",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_unstyled.css"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:unstyled",
        "useraccounts:core@1.3.0",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<|endoftext|>


<commit_before>function getUrl(){
  var currentUrl = window.location.href;
  var locationToCut = currentUrl.indexOf("?");
  currentUrl = currentUrl.substring(locationToCut+1);
	return currentUrl;
}

function routTo(currentUrl, back){

   if (back == undefined){back = false};

   var slashPostion = currentUrl.indexOf("/");
//   var currentType = sessionStorage.getItem("_entityType");
//   var currentEntity = sessionStorage.getItem("_currentEntity");

   var currentType = currentUrl.slice(0,slashPostion);
   var currentEntity = currentUrl.slice(slashPostion+1);

   showEntities(currentType, currentEntity);

}

function setUrl(type, uid){
   //get domain
   var currentUrl = window.location.href;
   var locationToCut = currentUrl.indexOf("?");
   var domainUrl = currentUrl.slice(0,locationToCut);

   if(type == undefined || uid == undefined){
      history.pushState({}, uid, domainUrl );
   } else{

      var typeEntity = {type: type, entity: uid};

      var url = domainUrl+"?"+type+"/"+uid;
      history.pushState(typeEntity, uid, url );
   }
};

function setActiveEntity (newEntity, newUid, newEventType, newCallback, turnOffFunction){

   var previuosEntity = activeEntity.entity;
   var previuosUid = activeEntity.uid;
   var previuosEventType = activeEntity.eventType;
   var previuosCallback = activeEntity.callback;
   var previuosTurnOffFunction = activeEntity.turnOffFunction;

   if (previuosEntity != "main"){
      if (previuosEventType != ""){
         if (isNotEmpty(previuosUid)){
            DB.child(previuosEntity+"/"+previuosUid).off(previuosEventType, previuosCallback);
         } else {
            console.log("Error: no previuos entity to close off previous callback");
         }
      } else {
         previuosTurnOffFunction();
      }
   } else {
      switch (previuosUid){
         case "member":
         case "owned":
            DB.child("users/"+userUuid+"/role").off(previuosEventType, previuosCallback);
            break;
         case "public":
            DB.child("groups").off(previuosEventType, previuosCallback);
            break;
         default:
            console.log("Error: no such groups cluster in main ("+previuosUid+")");
      }
   }

   activeEntity.entity = newEntity;
   activeEntity.uid = newUid;
   activeEntity.eventType = newEventType;
   activeEntity.callback = newCallback;
   activeEntity.turnOffFunction = turnOffFunction;

   setUrl(newEntity, newUid);
   if (newEntity == "groups" || newEntity == "topics" || newEntity == "questions" || newEntity == "chats"){
      DB.child(newEntity+"/"+newUid).once("value", function (dataSnapshot){
         var entetisTranslate = {groups: "קהילה" , topics: "נושא" , questions: "שאלה", chats: "שיחה" }

         document.title = "דליב: "+entetisTranslate[newEntity] + " - " +dataSnapshot.val().title
      })
   } else {
      document.title = "דליב (ראשי) : מחליטים ביחד";
   }
}

function showEntities(entity, uid){

   switch (entity){
      case "groups":
         DB.child("groups/"+uid).once("value", function (group){
            if(group.exists()){
               showGroup(uid);
            } else { console.log("group "+uid+" do not exist"); }
         })
         break;
      case "topics":
         DB.child("topics/"+uid).once("value", function (topic){
            if (topic.exists()){
               showTopic(uid);
            } else { console.log("topic "+uid+" do not exist");}
         })
         break;
      case "questions":
         DB.child("questions/"+uid).once("value", function (question){
            if (question.exists()){
               showQuestion(uid);
            } else { console.log("question "+uid+" do not exist");}
         })
         break;
      case "chats":
         DB.child("chats/"+uid).once("value", function (question){
            if (question.exists()){
               showChat(uid);
            } else { console.log("question "+uid+" do not exist");}
         })
         break;
      case "main":
         showMain(uid);
         break;
      default:
         showPublicGroups();
   }
};

<commit_msg>Enter first page through showMain<commit_after>function getUrl(){
  var currentUrl = window.location.href;
  var locationToCut = currentUrl.indexOf("?");
  currentUrl = currentUrl.substring(locationToCut+1);
	return currentUrl;
}

function routTo(currentUrl, back){

   if (back == undefined){back = false};

   var slashPostion = currentUrl.indexOf("/");
//   var currentType = sessionStorage.getItem("_entityType");
//   var currentEntity = sessionStorage.getItem("_currentEntity");

   var currentType = currentUrl.slice(0,slashPostion);
   var currentEntity = currentUrl.slice(slashPostion+1);

   showEntities(currentType, currentEntity);

}

function setUrl(type, uid){
   //get domain
   var currentUrl = window.location.href;
   var locationToCut = currentUrl.indexOf("?");
   var domainUrl = currentUrl.slice(0,locationToCut);

   if(type == undefined || uid == undefined){
      history.pushState({}, uid, domainUrl );
   } else{

      var typeEntity = {type: type, entity: uid};

      var url = domainUrl+"?"+type+"/"+uid;
      history.pushState(typeEntity, uid, url );
   }
};

function setActiveEntity (newEntity, newUid, newEventType, newCallback, turnOffFunction){

   var previuosEntity = activeEntity.entity;
   var previuosUid = activeEntity.uid;
   var previuosEventType = activeEntity.eventType;
   var previuosCallback = activeEntity.callback;
   var previuosTurnOffFunction = activeEntity.turnOffFunction;

   if (previuosEntity != "main"){
      if (previuosEventType != ""){
         if (isNotEmpty(previuosUid)){
            DB.child(previuosEntity+"/"+previuosUid).off(previuosEventType, previuosCallback);
         } else {
            console.log("Error: no previuos entity to close off previous callback");
         }
      } else {
         previuosTurnOffFunction();
      }
   } else {
      switch (previuosUid){
         case "member":
         case "owned":
            DB.child("users/"+userUuid+"/role").off(previuosEventType, previuosCallback);
            break;
         case "public":
            DB.child("groups").off(previuosEventType, previuosCallback);
            break;
         default:
            console.log("Error: no such groups cluster in main ("+previuosUid+")");
      }
   }

   activeEntity.entity = newEntity;
   activeEntity.uid = newUid;
   activeEntity.eventType = newEventType;
   activeEntity.callback = newCallback;
   activeEntity.turnOffFunction = turnOffFunction;

   setUrl(newEntity, newUid);
   if (newEntity == "groups" || newEntity == "topics" || newEntity == "questions" || newEntity == "chats"){
      DB.child(newEntity+"/"+newUid).once("value", function (dataSnapshot){
         var entetisTranslate = {groups: "קהילה" , topics: "נושא" , questions: "שאלה", chats: "שיחה" }

         document.title = "דליב: "+entetisTranslate[newEntity] + " - " +dataSnapshot.val().title
      })
   } else {
      document.title = "דליב (ראשי) : מחליטים ביחד";
   }
}

function showEntities(entity, uid){

   switch (entity){
      case "groups":
         DB.child("groups/"+uid).once("value", function (group){
            if(group.exists()){
               showGroup(uid);
            } else { console.log("group "+uid+" do not exist"); }
         })
         break;
      case "topics":
         DB.child("topics/"+uid).once("value", function (topic){
            if (topic.exists()){
               showTopic(uid);
            } else { console.log("topic "+uid+" do not exist");}
         })
         break;
      case "questions":
         DB.child("questions/"+uid).once("value", function (question){
            if (question.exists()){
               showQuestion(uid);
            } else { console.log("question "+uid+" do not exist");}
         })
         break;
      case "chats":
         DB.child("chats/"+uid).once("value", function (question){
            if (question.exists()){
               showChat(uid);
            } else { console.log("question "+uid+" do not exist");}
         })
         break;
      case "main":
         showMain(uid);
         break;
      default:
         showMain("public");
   }
};

<|endoftext|>


<commit_before>var { generateBlocks } = require("./blocks")
var { Step } = require("./steps")

function processBlock({ journey, subject, situation, isActive }, b) {
  if (b instanceof Step) {
    b.isActive = isActive
    journey.push(b)
  } else if (typeof b == "string") {
    console.warn(`string step should no longer be used: ${b}`)
    journey.push({ isActive, path: b })
  } else {
    if (!b.steps) {
      throw Error("" + b + " (" + (b instanceof Array ? "array" : "?") + ")")
    }
    let blockSubject = b.subject
      ? b.subject(subject, situation)
      : subject || situation
    const localActive =
      isActive &&
      (!b.isActive || (blockSubject && b.isActive(blockSubject, situation)))
    b.steps.forEach((s) =>
      processBlock(
        { journey, subject: blockSubject, situation, isActive: localActive },
        s
      )
    )
  }
}

function generateJourney(situation) {
  const blocks = generateBlocks(situation)

  function processBlocks({ situation }) {
    let journey = []
    blocks.forEach((b) => {
      processBlock(
        { journey, subject: situation, situation, isActive: true },
        b
      )
    })
    return journey
  }
  try {
    return processBlocks({ situation })
  } catch (e) {
    console.log("error", e)
  }
}

function full(situation) {
  const journey = generateJourney(situation)
  journey.pop()
  let lastChapter
  return journey.map((s) => {
    if (s.chapter) lastChapter = s.chapter
    else s.chapter = lastChapter
    return s
  })
}

function current(currentPath, situation) {
  const journey = full(situation)
  return journey.find((item) => item.path == currentPath)
}

function next(current, situation) {
  const journey = full(situation)
  const activeJourney = journey.filter((s) => s.isActive)

  let matches = activeJourney
    .map((element, index) => {
      return { element, index }
    })
    .filter((item) => item.element.path == (current.path || current))
  if (matches.length) {
    return activeJourney[matches[matches.length - 1].index + 1]
  } else {
    const test = current.path || current.fullPath || current
    throw new Error("Logic missing for " + test)
  }
}

module.exports = {
  full,
  next,
  current,
}
<commit_msg>Gère le passage à des écrans non actifs (#1676)<commit_after>var { generateBlocks } = require("./blocks")
var { Step } = require("./steps")

function processBlock({ journey, subject, situation, isActive }, b) {
  if (b instanceof Step) {
    b.isActive = isActive
    journey.push(b)
  } else if (typeof b == "string") {
    console.warn(`string step should no longer be used: ${b}`)
    journey.push({ isActive, path: b })
  } else {
    if (!b.steps) {
      throw Error("" + b + " (" + (b instanceof Array ? "array" : "?") + ")")
    }
    let blockSubject = b.subject
      ? b.subject(subject, situation)
      : subject || situation
    const localActive =
      isActive &&
      (!b.isActive || (blockSubject && b.isActive(blockSubject, situation)))
    b.steps.forEach((s) =>
      processBlock(
        { journey, subject: blockSubject, situation, isActive: localActive },
        s
      )
    )
  }
}

function generateJourney(situation) {
  const blocks = generateBlocks(situation)

  function processBlocks({ situation }) {
    let journey = []
    blocks.forEach((b) => {
      processBlock(
        { journey, subject: situation, situation, isActive: true },
        b
      )
    })
    return journey
  }
  try {
    return processBlocks({ situation })
  } catch (e) {
    console.log("error", e)
  }
}

function full(situation) {
  const journey = generateJourney(situation)
  journey.pop()
  let lastChapter
  return journey.map((s) => {
    if (s.chapter) lastChapter = s.chapter
    else s.chapter = lastChapter
    return s
  })
}

function current(currentPath, situation) {
  const journey = full(situation)
  return journey.find((item) => item.path == currentPath)
}

function next(current, situation) {
  const journey = full(situation)

  let matches = journey
    .map((element, index) => {
      return { element, index }
    })
    .filter((item) => item.element.path == (current.path || current))

  if (!matches.length) {
    const test = current.path || current.fullPath || current
    throw new Error("Logic missing for " + test)
  }

  return journey
    .slice(matches[matches.length - 1].index + 1)
    .filter((step) => step.isActive)[0]
}

module.exports = {
  full,
  next,
  current,
}
<|endoftext|>


<commit_before>'use strict';

var gateHost = '{%gate.baseUrl%}';
var artifactsEnabled = '{%features.artifacts%}' === 'true';
var atlasWebComponentsUrl = '{%canary.atlasWebComponentsUrl%}';
var authEnabled = '{%features.auth%}' === 'true';
var authEndpoint = gateHost + '/auth/user';
var bakeryDetailUrl = gateHost + '/bakery/logs/{{context.region}}/{{context.status.resourceId}}';
var canaryFeatureDisabled = '{%canary.featureEnabled%}' !== 'true';
var canaryStagesEnabled = '{%canary.stages%}' === 'true';
var changelogGistId = '{%changelog.gist.id%}';
var changelogGistName = '{%changelog.gist.name%}';
var chaosEnabled = '{%features.chaos%}' === 'true';
var defaultCanaryJudge = '{%canary.defaultJudge%}';
var defaultMetricsStore = '{%canary.defaultMetricsStore%}';
var defaultMetricsAccountName = '{%canary.defaultMetricsAccount%}';
var defaultStorageAccountName = '{%canary.defaultStorageAccount%}';
var displayTimestampsInUserLocalTime = '{%features.displayTimestampsInUserLocalTime%}' === 'true';
var entityTagsEnabled = false;
var fiatEnabled = '{%features.fiat%}' === 'true';
var gremlinEnabled = '{%features.gremlinEnabled%}' === 'true';
var iapRefresherEnabled = '{%features.iapRefresherEnabled}' === 'true';
var infrastructureStagesEnabled = '{%features.infrastructureStages%}' === 'true';
var managedPipelineTemplatesV2UIEnabled = '{%features.managedPipelineTemplatesV2UI%}' === 'true';
var jobsEnabled = '{%features.jobs%}' === 'true';
var maxPipelineAgeDays = '{%maxPipelineAgeDays%}';
var mineCanaryEnabled = '{%features.mineCanary%}' === 'true';
var notificationsEnabled = '{%notifications.enabled%}' === 'true';
var onDemandClusterThreshold = '{%onDemandClusterThreshold%}';
var pipelineTemplatesEnabled = '{%features.pipelineTemplates%}' === 'true';
var reduxLoggerEnabled = '{%canary.reduxLogger%}' === 'true';
var showAllConfigsEnabled = '{%canary.showAllCanaryConfigs%}' === 'true';
var slack = {
  botName: '{%notifications.slack.botName%}',
  enabled: '{%notifications.slack.enabled%}' === 'true',
};
var sms = {
  enabled: '{%notifications.twilio.enabled%}' === 'true',
};
var templatesEnabled = '{%canary.templatesEnabled%}' === 'true';
var travisEnabled = '{%features.travis%}' === 'true';
var timezone = '{%timezone%}';
var version = '{%version%}';
var werckerEnabled = '{%features.wercker%}' === 'true';

// Cloud Providers
var appengine = {
  defaults: {
    account: '{%appengine.default.account%}',
    editLoadBalancerStageEnabled: '{%appengine.enabled%}' === 'true',
  },
};
var aws = {
  defaults: {
    account: '{%aws.default.account%}',
    iamRole: 'BaseIAMRole',
    region: '{%aws.default.region%}',
  },
  defaultSecurityGroups: [],
  loadBalancers: {
    // if true, VPC load balancers will be created as internal load balancers if the selected subnet has a purpose
    // tag that starts with "internal"
    inferInternalFlagFromSubnet: false,
  },
  useAmiBlockDeviceMappings: false,
};
var azure = {
  defaults: {
    account: '{%azure.default.account%}',
    region: '{%azure.default.region%}',
  },
};
var cloudfoundry = {
  defaults: {
    account: '{%cloudfoundry.default.account%}',
  },
};
var dcos = {
  defaults: {
    account: '{%dcos.default.account%}',
  },
};
var ecs = {
  defaults: {
    account: '{%ecs.default.account%}',
  },
};
var gce = {
  defaults: {
    account: '{%google.default.account%}',
    region: '{%google.default.region%}',
    zone: '{%google.default.zone%}',
  },
  associatePublicIpAddress: true,
};
var kubernetes = {
  defaults: {
    account: '{%kubernetes.default.account%}',
    instanceLinkTemplate: '{{host}}/api/v1/proxy/namespaces/{{namespace}}/pods/{{name}}',
    internalDNSNameTemplate: '{{name}}.{{namespace}}.svc.cluster.local',
    namespace: '{%kubernetes.default.namespace%}',
    proxy: '{%kubernetes.default.proxy%}',
  },
};
var openstack = {
  defaults: {
    account: '{%openstack.default.account%}',
    region: '{%openstack.default.region%}',
  },
};
var oracle = {
  defaults: {
    account: '{%oracle.default.account%}',
    region: '{%oracle.default.region%}',
  },
};

window.spinnakerSettings = {
  authEnabled: authEnabled,
  authEndpoint: authEndpoint,
  authTtl: 600000,
  bakeryDetailUrl: bakeryDetailUrl,
  canary: {
    atlasWebComponentsUrl: atlasWebComponentsUrl,
    defaultJudge: defaultCanaryJudge,
    featureDisabled: canaryFeatureDisabled,
    reduxLogger: reduxLoggerEnabled,
    metricsAccountName: defaultMetricsAccountName,
    metricStore: defaultMetricsStore,
    showAllConfigs: showAllConfigsEnabled,
    stagesEnabled: canaryStagesEnabled,
    storageAccountName: defaultStorageAccountName,
    templatesEnabled: templatesEnabled,
  },
  changelog: {
    fileName: changelogGistName,
    gistId: changelogGistId,
  },
  checkForUpdates: false,
  defaultCategory: 'serverGroup',
  defaultInstancePort: 80,
  defaultProviders: [
    'appengine',
    'aws',
    'azure',
    'cloudfoundry',
    'dcos',
    'ecs',
    'gce',
    'kubernetes',
    'openstack',
    'oracle',
    'titus',
  ],
  defaultTimeZone: timezone, // see http://momentjs.com/timezone/docs/#/data-utilities/
  feature: {
    artifacts: artifactsEnabled,
    canary: mineCanaryEnabled,
    chaosMonkey: chaosEnabled,
    displayTimestampsInUserLocalTime: displayTimestampsInUserLocalTime,
    entityTags: entityTagsEnabled,
    fiatEnabled: fiatEnabled,
    gremlinEnabled: gremlinEnabled,
    iapRefresherEnabled: iapRefresherEnabled,
    infrastructureStages: infrastructureStagesEnabled,
    jobs: jobsEnabled,
    managedPipelineTemplatesV2UI: managedPipelineTemplatesV2UIEnabled,
    notifications: notificationsEnabled,
    pagerDuty: false,
    pipelines: true,
    pipelineTemplates: pipelineTemplatesEnabled,
    roscoMode: true,
    snapshots: false,
    travis: travisEnabled,
    versionedProviders: true,
    wercker: werckerEnabled,
  },
  gateUrl: gateHost,
  gitSources: ['bitbucket', 'gitlab', 'github', 'stash'],
  maxPipelineAgeDays: maxPipelineAgeDays,
  notifications: {
    bearychat: {
      enabled: true,
    },
    email: {
      enabled: true,
    },
    githubStatus: {
      enabled: true,
    },
    googlechat: {
      enabled: true,
    },
    hipchat: {
      botName: 'Skynet T-800',
      enabled: true,
    },
    pubsub: {
      enabled: true,
    },
    slack: slack,
    sms: sms,
  },
  onDemandClusterThreshold: onDemandClusterThreshold,
  pagerDuty: {
    required: false,
  },
  pollSchedule: 30000,
  providers: {
    appengine: appengine,
    aws: aws,
    azure: azure,
    cloudfoundry: cloudfoundry,
    dcos: dcos,
    ecs: ecs,
    gce: gce,
    kubernetes: kubernetes,
    openstack: openstack,
    oracle: oracle,
    titus: {
      defaults: {
        account: 'titustestvpc',
        iamProfile: '{{application}}InstanceProfile',
        region: 'us-east-1',
      },
    },
  },
  pubsubProviders: ['google'], // TODO(joonlim): Add amazon once it is confirmed that amazon pub/sub works.
  triggerTypes: [
    'artifactory',
    'concourse',
    'cron',
    'docker',
    'git',
    'jenkins',
    'pipeline',
    'pubsub',
    'travis',
    'webhook',
    'wercker',
  ],
  version: version,
};
<commit_msg>fix(IAP) Fix refresher not enabling (#6740)<commit_after>'use strict';

var gateHost = '{%gate.baseUrl%}';
var artifactsEnabled = '{%features.artifacts%}' === 'true';
var atlasWebComponentsUrl = '{%canary.atlasWebComponentsUrl%}';
var authEnabled = '{%features.auth%}' === 'true';
var authEndpoint = gateHost + '/auth/user';
var bakeryDetailUrl = gateHost + '/bakery/logs/{{context.region}}/{{context.status.resourceId}}';
var canaryFeatureDisabled = '{%canary.featureEnabled%}' !== 'true';
var canaryStagesEnabled = '{%canary.stages%}' === 'true';
var changelogGistId = '{%changelog.gist.id%}';
var changelogGistName = '{%changelog.gist.name%}';
var chaosEnabled = '{%features.chaos%}' === 'true';
var defaultCanaryJudge = '{%canary.defaultJudge%}';
var defaultMetricsStore = '{%canary.defaultMetricsStore%}';
var defaultMetricsAccountName = '{%canary.defaultMetricsAccount%}';
var defaultStorageAccountName = '{%canary.defaultStorageAccount%}';
var displayTimestampsInUserLocalTime = '{%features.displayTimestampsInUserLocalTime%}' === 'true';
var entityTagsEnabled = false;
var fiatEnabled = '{%features.fiat%}' === 'true';
var gremlinEnabled = '{%features.gremlinEnabled%}' === 'true';
var iapRefresherEnabled = '{%features.iapRefresherEnabled%}' === 'true';
var infrastructureStagesEnabled = '{%features.infrastructureStages%}' === 'true';
var managedPipelineTemplatesV2UIEnabled = '{%features.managedPipelineTemplatesV2UI%}' === 'true';
var jobsEnabled = '{%features.jobs%}' === 'true';
var maxPipelineAgeDays = '{%maxPipelineAgeDays%}';
var mineCanaryEnabled = '{%features.mineCanary%}' === 'true';
var notificationsEnabled = '{%notifications.enabled%}' === 'true';
var onDemandClusterThreshold = '{%onDemandClusterThreshold%}';
var pipelineTemplatesEnabled = '{%features.pipelineTemplates%}' === 'true';
var reduxLoggerEnabled = '{%canary.reduxLogger%}' === 'true';
var showAllConfigsEnabled = '{%canary.showAllCanaryConfigs%}' === 'true';
var slack = {
  botName: '{%notifications.slack.botName%}',
  enabled: '{%notifications.slack.enabled%}' === 'true',
};
var sms = {
  enabled: '{%notifications.twilio.enabled%}' === 'true',
};
var templatesEnabled = '{%canary.templatesEnabled%}' === 'true';
var travisEnabled = '{%features.travis%}' === 'true';
var timezone = '{%timezone%}';
var version = '{%version%}';
var werckerEnabled = '{%features.wercker%}' === 'true';

// Cloud Providers
var appengine = {
  defaults: {
    account: '{%appengine.default.account%}',
    editLoadBalancerStageEnabled: '{%appengine.enabled%}' === 'true',
  },
};
var aws = {
  defaults: {
    account: '{%aws.default.account%}',
    iamRole: 'BaseIAMRole',
    region: '{%aws.default.region%}',
  },
  defaultSecurityGroups: [],
  loadBalancers: {
    // if true, VPC load balancers will be created as internal load balancers if the selected subnet has a purpose
    // tag that starts with "internal"
    inferInternalFlagFromSubnet: false,
  },
  useAmiBlockDeviceMappings: false,
};
var azure = {
  defaults: {
    account: '{%azure.default.account%}',
    region: '{%azure.default.region%}',
  },
};
var cloudfoundry = {
  defaults: {
    account: '{%cloudfoundry.default.account%}',
  },
};
var dcos = {
  defaults: {
    account: '{%dcos.default.account%}',
  },
};
var ecs = {
  defaults: {
    account: '{%ecs.default.account%}',
  },
};
var gce = {
  defaults: {
    account: '{%google.default.account%}',
    region: '{%google.default.region%}',
    zone: '{%google.default.zone%}',
  },
  associatePublicIpAddress: true,
};
var kubernetes = {
  defaults: {
    account: '{%kubernetes.default.account%}',
    instanceLinkTemplate: '{{host}}/api/v1/proxy/namespaces/{{namespace}}/pods/{{name}}',
    internalDNSNameTemplate: '{{name}}.{{namespace}}.svc.cluster.local',
    namespace: '{%kubernetes.default.namespace%}',
    proxy: '{%kubernetes.default.proxy%}',
  },
};
var openstack = {
  defaults: {
    account: '{%openstack.default.account%}',
    region: '{%openstack.default.region%}',
  },
};
var oracle = {
  defaults: {
    account: '{%oracle.default.account%}',
    region: '{%oracle.default.region%}',
  },
};

window.spinnakerSettings = {
  authEnabled: authEnabled,
  authEndpoint: authEndpoint,
  authTtl: 600000,
  bakeryDetailUrl: bakeryDetailUrl,
  canary: {
    atlasWebComponentsUrl: atlasWebComponentsUrl,
    defaultJudge: defaultCanaryJudge,
    featureDisabled: canaryFeatureDisabled,
    reduxLogger: reduxLoggerEnabled,
    metricsAccountName: defaultMetricsAccountName,
    metricStore: defaultMetricsStore,
    showAllConfigs: showAllConfigsEnabled,
    stagesEnabled: canaryStagesEnabled,
    storageAccountName: defaultStorageAccountName,
    templatesEnabled: templatesEnabled,
  },
  changelog: {
    fileName: changelogGistName,
    gistId: changelogGistId,
  },
  checkForUpdates: false,
  defaultCategory: 'serverGroup',
  defaultInstancePort: 80,
  defaultProviders: [
    'appengine',
    'aws',
    'azure',
    'cloudfoundry',
    'dcos',
    'ecs',
    'gce',
    'kubernetes',
    'openstack',
    'oracle',
    'titus',
  ],
  defaultTimeZone: timezone, // see http://momentjs.com/timezone/docs/#/data-utilities/
  feature: {
    artifacts: artifactsEnabled,
    canary: mineCanaryEnabled,
    chaosMonkey: chaosEnabled,
    displayTimestampsInUserLocalTime: displayTimestampsInUserLocalTime,
    entityTags: entityTagsEnabled,
    fiatEnabled: fiatEnabled,
    gremlinEnabled: gremlinEnabled,
    iapRefresherEnabled: iapRefresherEnabled,
    infrastructureStages: infrastructureStagesEnabled,
    jobs: jobsEnabled,
    managedPipelineTemplatesV2UI: managedPipelineTemplatesV2UIEnabled,
    notifications: notificationsEnabled,
    pagerDuty: false,
    pipelines: true,
    pipelineTemplates: pipelineTemplatesEnabled,
    roscoMode: true,
    snapshots: false,
    travis: travisEnabled,
    versionedProviders: true,
    wercker: werckerEnabled,
  },
  gateUrl: gateHost,
  gitSources: ['bitbucket', 'gitlab', 'github', 'stash'],
  maxPipelineAgeDays: maxPipelineAgeDays,
  notifications: {
    bearychat: {
      enabled: true,
    },
    email: {
      enabled: true,
    },
    githubStatus: {
      enabled: true,
    },
    googlechat: {
      enabled: true,
    },
    hipchat: {
      botName: 'Skynet T-800',
      enabled: true,
    },
    pubsub: {
      enabled: true,
    },
    slack: slack,
    sms: sms,
  },
  onDemandClusterThreshold: onDemandClusterThreshold,
  pagerDuty: {
    required: false,
  },
  pollSchedule: 30000,
  providers: {
    appengine: appengine,
    aws: aws,
    azure: azure,
    cloudfoundry: cloudfoundry,
    dcos: dcos,
    ecs: ecs,
    gce: gce,
    kubernetes: kubernetes,
    openstack: openstack,
    oracle: oracle,
    titus: {
      defaults: {
        account: 'titustestvpc',
        iamProfile: '{{application}}InstanceProfile',
        region: 'us-east-1',
      },
    },
  },
  pubsubProviders: ['google'], // TODO(joonlim): Add amazon once it is confirmed that amazon pub/sub works.
  triggerTypes: [
    'artifactory',
    'concourse',
    'cron',
    'docker',
    'git',
    'jenkins',
    'pipeline',
    'pubsub',
    'travis',
    'webhook',
    'wercker',
  ],
  version: version,
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import SubPage from '../reusable/SubPage.js';
import SubPageContent from '../reusable/SubPageContent.js';
import GridItem from '../reusable/GridItem';
import LevelDetails from '../reusable/LevelDetails';
import Scrollbar from '../reusable/Scrollbar';
import { TweenLite, Sine } from 'gsap';
import 'ScrollToPlugin'; // Using aliases in webpack.config.js allowes using GASP-plugins

export default class Levels extends SubPage{
  grid=null;
  tween=null;
  state = {
    selectedLevel: this.props.selectedLevel,
  }

  componentDidMount(nextProps) {
    super.componentDidMount();
    this.grid=ReactDOM.findDOMNode(this.refs.grid);
    this.props.setKeybinds({
      37: this.props.exit,
      8: this.props.exit,
      38: this.moveUp,
      40: this.moveDown,
      39: this.startGame,
    });
    this.centralizeCurrent();
  }

  startGame=()=>{
    if(this.props.progress[this.state.selectedLevel].unlocked){
      this.setRotation(true);
      this.props.setSelectedLevel(
        this.state.selectedLevel,
        ()=>{this.props.navigate('game')}
      );
    }

  }

  setSelectedLevel(selectedLevel, e){
    this.setState({ selectedLevel });
  }

  gridItemMouseEnterHandler(i,e){
    if(i!==this.state.selectedLevel){
      this.setSelectedLevel(i);
      this.slideGridItemIntoView(i);
    }
  }

  moveUp=()=>{
    const { progress } = this.props;
    const { selectedLevel } = this.state;
    (selectedLevel)==0
      ? this.setSelectedLevel(progress.length-1)
      : this.setSelectedLevel(selectedLevel-1)
    ;
    this.centralizeCurrent();
  }

  moveDown=()=>{
    const { progress } = this.props;
    const { selectedLevel } = this.state;
    (selectedLevel)==progress.length-1
      ? this.setSelectedLevel(0)
      : this.setSelectedLevel(selectedLevel+1)
    ;
    this.centralizeCurrent();
  }

  animateScroll(elem, scrollTo) {
    this.tween && this.tween.kill(); // TODO Resolve.
    this.tween = TweenLite.to(elem, .3, {scrollTo: elem.scrollTop+scrollTo, ease: Sine.easeInOut});
  }

  centralizeCurrent=()=>{
    const currentGridItem=this.grid.getElementsByClassName('grid-item')[this.state.selectedLevel];
    const offsetTopShouldBe=this.grid.offsetHeight/2-currentGridItem.offsetHeight/2;
    const offsetTopIs=currentGridItem.getBoundingClientRect().top-this.grid.getBoundingClientRect().top;
    this.animateScroll(currentGridItem.parentElement.parentElement, offsetTopIs-offsetTopShouldBe);
  }

  slideGridItemIntoView=which=>{
    const currentGridItem=this.grid.getElementsByClassName('grid-item')[which];
    const offsetTopIs=currentGridItem.getBoundingClientRect().top-this.grid.getBoundingClientRect().top;
    const maxOffset=this.grid.offsetHeight-currentGridItem.offsetHeight;
    let offsetIncement=0;
    if(offsetTopIs<0) offsetIncement=offsetTopIs;
    else if(offsetTopIs>maxOffset) offsetIncement=offsetTopIs-maxOffset;
    this.animateScroll(currentGridItem.parentElement.parentElement, offsetIncement*1.2);
  }

  render (){
    const { progress, setKeybinds, userProgress } = this.props;
    const { selectedLevel } = this.state;
    return (
      <SubPageContent {...this.props} style={{height: '100%'}} id="levels">

          <Scrollbar>
            {progress.map((level, i) =>
              <GridItem
                key={i}
                level={level}
                selected={selectedLevel === i}
                onMouseEnter={this.gridItemMouseEnterHandler.bind(this, i)}
              />
            )}
          </Scrollbar>

          <LevelDetails
            selectedLevel={progress[selectedLevel]}
            progress={progress}
            startGame={this.startGame}
          />

      </SubPageContent>
    );
  }
}
<commit_msg>Fixed issue #4<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import SubPage from '../reusable/SubPage.js';
import SubPageContent from '../reusable/SubPageContent.js';
import GridItem from '../reusable/GridItem';
import LevelDetails from '../reusable/LevelDetails';
import Scrollbar from '../reusable/Scrollbar';
import { TweenLite, Sine } from 'gsap';
import 'ScrollToPlugin'; // Using aliases in webpack.config.js allowes using GASP-plugins

export default class Levels extends SubPage{
  grid=null;
  tween=null;
  state = {
    selectedLevel: this.props.selectedLevel,
  }

  componentDidMount(nextProps) {
    super.componentDidMount();
    this.grid=ReactDOM.findDOMNode(this.refs.grid);
    this.props.setKeybinds({
      37: this.props.exit,
      8: this.props.exit,
      38: this.moveUp,
      40: this.moveDown,
      39: this.startGame,
    });
    this.centralizeCurrent();
  }

  startGame=()=>{
    if(this.props.progress[this.state.selectedLevel].unlocked){
      this.setRotation(true);
      this.props.setSelectedLevel(
        this.state.selectedLevel,
        ()=>{this.props.navigate('game')}
      );
    }

  }

  setSelectedLevel(selectedLevel, e){
    this.setState({ selectedLevel });
  }

  gridItemMouseEnterHandler(i,e){
    if(i!==this.state.selectedLevel){
      this.setSelectedLevel(i);
      this.slideGridItemIntoView(i);
    }
  }

  moveUp=()=>{
    const { progress } = this.props;
    const { selectedLevel } = this.state;
    (selectedLevel)==0
      ? this.setSelectedLevel(progress.length-1)
      : this.setSelectedLevel(selectedLevel-1)
    ;
    this.centralizeCurrent();
  }

  moveDown=()=>{
    const { progress } = this.props;
    const { selectedLevel } = this.state;
    (selectedLevel)==progress.length-1
      ? this.setSelectedLevel(0)
      : this.setSelectedLevel(selectedLevel+1)
    ;
    this.centralizeCurrent();
  }

  animateScroll(elem, scrollTo) {
    this.tween && TweenLite.killTweensOf(this.tween);
    this.tween = TweenLite.to(elem, .3, {scrollTo: elem.scrollTop+scrollTo, ease: Sine.easeInOut});
  }

  centralizeCurrent=()=>{
    const currentGridItem=this.grid.getElementsByClassName('grid-item')[this.state.selectedLevel];
    const offsetTopShouldBe=this.grid.offsetHeight/2-currentGridItem.offsetHeight/2;
    const offsetTopIs=currentGridItem.getBoundingClientRect().top-this.grid.getBoundingClientRect().top;
    this.animateScroll(currentGridItem.parentElement.parentElement, offsetTopIs-offsetTopShouldBe);
  }

  slideGridItemIntoView=which=>{
    const currentGridItem=this.grid.getElementsByClassName('grid-item')[which];
    const offsetTopIs=currentGridItem.getBoundingClientRect().top-this.grid.getBoundingClientRect().top;
    const maxOffset=this.grid.offsetHeight-currentGridItem.offsetHeight;
    let offsetIncement=0;
    if(offsetTopIs<0) offsetIncement=offsetTopIs;
    else if(offsetTopIs>maxOffset) offsetIncement=offsetTopIs-maxOffset;
    this.animateScroll(currentGridItem.parentElement.parentElement, offsetIncement*1.2);
  }

  render (){
    const { progress, setKeybinds, userProgress } = this.props;
    const { selectedLevel } = this.state;
    return (
      <SubPageContent {...this.props} style={{height: '100%'}} id="levels">

          <Scrollbar>
            {progress.map((level, i) =>
              <GridItem
                key={i}
                level={level}
                selected={selectedLevel === i}
                onMouseEnter={this.gridItemMouseEnterHandler.bind(this, i)}
              />
            )}
          </Scrollbar>

          <LevelDetails
            selectedLevel={progress[selectedLevel]}
            progress={progress}
            startGame={this.startGame}
          />

      </SubPageContent>
    );
  }
}
<|endoftext|>


<commit_before>//export const vueFormProvider = Symbol();
export const vueFormConfig = 'VueFormProviderConfig';
export const vueFormState = 'VueFormProviderState';
<commit_msg>Use Symbol if available<commit_after>import { randomId } from './util';

const s = typeof Symbol === 'function';
export const vueFormConfig = s ? Symbol() : `VueFormProviderConfig_${randomId}`;
export const vueFormState =  s ? Symbol() : `VueFormProviderState${randomId}`;
<|endoftext|>


<commit_before>Package.describe({
  summary: "State of the art, out of the box Meteor pagination"
});

Package.on_use(function(api){
    api.use([
        "deps",
        "templating",
        "underscore",
        "coffeescript",
        "handlebars",
        "spark",
        "session"
    ], "client");

    api.use([
        "deps",
        "underscore",
        "coffeescript"
    ], "server");

    api.add_files([
        "paginate.coffee"
    ], ["client", "server"]);

    api.add_files([
        "templates.html",
        "client/main.coffee",
        "loader.gif"
    ], "client");
    /*
    api.export([
        "_Paginate",
        "_PaginateInstances"
    ], ["client", "server"]);
    */
});<commit_msg>.pagination and .pager CSS from Bootstrap 3<commit_after>Package.describe({
  summary: "State of the art, out of the box Meteor pagination"
});

Package.on_use(function(api){
    api.use([
        "deps",
        "templating",
        "underscore",
        "coffeescript",
        "handlebars",
        "spark",
        "session"
    ], "client");

    api.use([
        "deps",
        "underscore",
        "coffeescript"
    ], "server");

    api.add_files([
        "paginate.coffee"
    ], ["client", "server"]);

    api.add_files([
        "templates.html",
        "client/main.coffee",
        "client/pages.css",
        "loader.gif"
    ], "client");
    /*
    api.export([
        "_Paginate",
        "_PaginateInstances"
    ], ["client", "server"]);
    */
});<|endoftext|>


<commit_before>const _ = require('lodash')
const uuidv4 = require('uuid/v4')
const addMilliseconds = require('date-fns/add_milliseconds')
const subMilliseconds = require('date-fns/sub_milliseconds')

exports.seed = async knex => {
  const now = new Date()

  let dateCounter = 0
  const getCurrentDate = () => {
    const uniqueDate = addMilliseconds(now, dateCounter)
    return uniqueDate
  }
  const getUniqueDate = () => {
    dateCounter += 1
    return getCurrentDate()
  }

  const daGrevisAccountId = 'faceb00c-0000-0000-0000-000000000000'
  const msksDevConnectionId = 'deadc0de-0000-0000-0000-000000000000'
  const siverGadConnectionId = 'b16b00b5-0000-0000-0000-000000000000'
  const siverGadServerChannelId = 'cafedaff-0000-0000-0000-000000000000'
  const publicMeeseekeriaChannelId = 'deedfeed-0000-0000-0000-000000000000'
  const siverGadMeeseekeriaChannelId = uuidv4()
  const siverGadMeeseekeria2ChannelId = uuidv4()
  const siverGadDaGrevisChannelId = uuidv4()

  await knex('accounts').insert([
    {
      id: daGrevisAccountId,
      createdAt: getUniqueDate(),
      username: 'daGrevis',
      hashedPassword:
        '$2b$10$T0R/COrdem7pjS.6zktqbeOJJ5344/PbonNad2unT3y6iSAOh4HZ6', // hunter2
    },
  ])

  await knex('connections').insert([
    {
      id: msksDevConnectionId,
      createdAt: getUniqueDate(),
      accountId: daGrevisAccountId,
      serverId: 'freenode',
      isBot: true,
      nick: 'msks-dev',
      host: 'chat.freenode.net',
      port: 6697,
      autoConnect: false,
    },
    {
      id: siverGadConnectionId,
      createdAt: getUniqueDate(),
      accountId: daGrevisAccountId,
      serverId: 'freenode',
      nick: 'siverGad',
      host: 'chat.freenode.net',
      port: 6697,
      autoConnect: false,
    },
  ])

  await knex('channels').insert([
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      connectionId: msksDevConnectionId,
      name: '*',
      type: 'server',
    },
    {
      id: siverGadServerChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: '*',
      type: 'server',
    },
    {
      id: publicMeeseekeriaChannelId,
      createdAt: getUniqueDate(),
      connectionId: msksDevConnectionId,
      name: '#meeseekeria',
      type: 'shared',
      isPublic: true,
      autoJoin: true,
      topic: 'msks is short for meeseeks',
    },
    {
      id: siverGadMeeseekeriaChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: '#meeseekeria',
      type: 'shared',
      autoJoin: true,
      topic: 'msks is short for meeseeks',
    },
    {
      id: siverGadMeeseekeria2ChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: '#meeseekeria2',
      type: 'shared',
      autoJoin: true,
    },
    {
      id: siverGadDaGrevisChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: 'daGrevis',
      type: 'user',
    },
  ])

  await knex('messages').insert(
    _.map(_.range(1, 1001), messageNumber => ({
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'text',
      text: `#${messageNumber}`,
    })),
  )

  await knex('messages').insert(
    _.map(['a', 'b', 'c'], text => ({
      id: uuidv4(),
      createdAt: subMilliseconds(getCurrentDate(), 100),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text,
    })),
  )

  await knex('messages').insert([
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'First!',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'Welcome to public #meeseekeria!',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'action',
      text: 'waves',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'notice',
      text: 'some very important notice',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'part',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'nick',
      text: '',
      meta: JSON.stringify({
        newNick: 'msks-dev2',
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev2',
      type: 'quit',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'topic',
      text: 'msks is short for meeseeks',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'mode',
      text: 'siverGad set +v on msks-dev',
      meta: JSON.stringify({
        mode: '+v',
        param: 'msks-dev',
        isVoiced: true,
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'mode',
      text: 'siverGad set -b on *!~ij@NixOS/user/siers',
      meta: JSON.stringify({
        mode: '-b',
        param: '*!~ij@NixOS/user/siers',
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'kick',
      text: 'just a test',
      meta: JSON.stringify({
        kicked: 'msks-dev',
        isVoiced: true,
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: '\u0002bold\u0002 \u001ditalic\u001d \u001funderline\u001f',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text:
        '\u0002\u00034r\u00037a\u00038i\u00039n\u00033b\u000312o\u00036w\u0002',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'msks-dev, ping',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'text',
      text: 'pong',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadMeeseekeria2ChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'This channel is not public.',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadServerChannelId,
      nick: 'moon.freenode.net',
      type: 'status',
      text: 'Connecting as siverGad',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadServerChannelId,
      nick: 'siverGad',
      type: 'banlist',
      text: '',
      meta: {
        channelName: '#developerslv',
        bans: [
          {
            author: 'siers!~ij@NixOS/user/siers',
            target: '*!~ij@NixOS/user/siers',
            timestamp: 1553607589,
          },
        ],
      },
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadServerChannelId,
      nick: 'moon.freenode.net',
      type: 'status',
      text: 'Disconnected as daGrevis',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadDaGrevisChannelId,
      nick: 'daGrevis',
      type: 'text',
      text: 'Hello, siverGad',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadDaGrevisChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'Hi, daGrevis - I am /whois-ing you',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadDaGrevisChannelId,
      nick: 'daGrevis',
      type: 'whois',
      text: '',
      meta: {
        account: 'daGrevis',
        ident: '~daGrevis',
        hostname: 'unaffiliated/dagrevis',
        realName: 'Raitis Stengrevics',
        server: 'weber.freenode.net',
        serverInfo: 'US',
        secure: true,
      },
    },
  ])

  await knex('users').insert([
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadMeeseekeria2ChannelId,
      nick: 'siverGad',
    },
  ])
}
<commit_msg>Add testik to postgres/seeds/development.js<commit_after>const _ = require('lodash')
const uuidv4 = require('uuid/v4')
const addMilliseconds = require('date-fns/add_milliseconds')
const subMilliseconds = require('date-fns/sub_milliseconds')

exports.seed = async knex => {
  const now = new Date()

  let dateCounter = 0
  const getCurrentDate = () => {
    const uniqueDate = addMilliseconds(now, dateCounter)
    return uniqueDate
  }
  const getUniqueDate = () => {
    dateCounter += 1
    return getCurrentDate()
  }

  const daGrevisAccountId = 'faceb00c-0000-0000-0000-000000000000'
  const testikAccountId = uuidv4()
  const msksDevConnectionId = 'deadc0de-0000-0000-0000-000000000000'
  const siverGadConnectionId = 'b16b00b5-0000-0000-0000-000000000000'
  const testikConnectionId = uuidv4()
  const siverGadServerChannelId = 'cafedaff-0000-0000-0000-000000000000'
  const publicMeeseekeriaChannelId = 'deedfeed-0000-0000-0000-000000000000'
  const siverGadMeeseekeriaChannelId = uuidv4()
  const siverGadMeeseekeria2ChannelId = uuidv4()
  const siverGadDaGrevisChannelId = uuidv4()

  await knex('accounts').insert([
    {
      id: daGrevisAccountId,
      createdAt: getUniqueDate(),
      username: 'daGrevis',
      hashedPassword:
        '$2b$10$T0R/COrdem7pjS.6zktqbeOJJ5344/PbonNad2unT3y6iSAOh4HZ6', // hunter2
    },
    {
      id: testikAccountId,
      createdAt: getUniqueDate(),
      username: 'testik',
      hashedPassword:
        '$2b$10$T0R/COrdem7pjS.6zktqbeOJJ5344/PbonNad2unT3y6iSAOh4HZ6', // hunter2
    },
  ])

  await knex('connections').insert([
    {
      id: msksDevConnectionId,
      createdAt: getUniqueDate(),
      accountId: daGrevisAccountId,
      serverId: 'freenode',
      isBot: true,
      nick: 'msks-dev',
      host: 'chat.freenode.net',
      port: 6697,
      autoConnect: false,
    },
    {
      id: siverGadConnectionId,
      createdAt: getUniqueDate(),
      accountId: daGrevisAccountId,
      serverId: 'freenode',
      nick: 'siverGad',
      host: 'chat.freenode.net',
      port: 6697,
      autoConnect: false,
    },
    {
      id: testikConnectionId,
      createdAt: getUniqueDate(),
      accountId: testikAccountId,
      serverId: 'freenode',
      nick: 'testik',
      host: 'chat.freenode.net',
      port: 6697,
      autoConnect: false,
    },
  ])

  await knex('channels').insert([
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      connectionId: msksDevConnectionId,
      name: '*',
      type: 'server',
    },
    {
      id: siverGadServerChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: '*',
      type: 'server',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      connectionId: testikConnectionId,
      name: '*',
      type: 'server',
    },
    {
      id: publicMeeseekeriaChannelId,
      createdAt: getUniqueDate(),
      connectionId: msksDevConnectionId,
      name: '#meeseekeria',
      type: 'shared',
      isPublic: true,
      autoJoin: true,
      topic: 'msks is short for meeseeks',
    },
    {
      id: siverGadMeeseekeriaChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: '#meeseekeria',
      type: 'shared',
      autoJoin: true,
      topic: 'msks is short for meeseeks',
    },
    {
      id: siverGadMeeseekeria2ChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: '#meeseekeria2',
      type: 'shared',
      autoJoin: true,
    },
    {
      id: siverGadDaGrevisChannelId,
      createdAt: getUniqueDate(),
      connectionId: siverGadConnectionId,
      name: 'daGrevis',
      type: 'user',
    },
  ])

  await knex('messages').insert(
    _.map(_.range(1, 1001), messageNumber => ({
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'text',
      text: `#${messageNumber}`,
    })),
  )

  await knex('messages').insert(
    _.map(['a', 'b', 'c'], text => ({
      id: uuidv4(),
      createdAt: subMilliseconds(getCurrentDate(), 100),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text,
    })),
  )

  await knex('messages').insert([
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'First!',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'Welcome to public #meeseekeria!',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'action',
      text: 'waves',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'notice',
      text: 'some very important notice',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'part',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'nick',
      text: '',
      meta: JSON.stringify({
        newNick: 'msks-dev2',
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev2',
      type: 'quit',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'topic',
      text: 'msks is short for meeseeks',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'mode',
      text: 'siverGad set +v on msks-dev',
      meta: JSON.stringify({
        mode: '+v',
        param: 'msks-dev',
        isVoiced: true,
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'mode',
      text: 'siverGad set -b on *!~ij@NixOS/user/siers',
      meta: JSON.stringify({
        mode: '-b',
        param: '*!~ij@NixOS/user/siers',
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'kick',
      text: 'just a test',
      meta: JSON.stringify({
        kicked: 'msks-dev',
        isVoiced: true,
      }),
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'join',
      text: '',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: '\u0002bold\u0002 \u001ditalic\u001d \u001funderline\u001f',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text:
        '\u0002\u00034r\u00037a\u00038i\u00039n\u00033b\u000312o\u00036w\u0002',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'msks-dev, ping',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
      type: 'text',
      text: 'pong',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadMeeseekeria2ChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'This channel is not public.',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadServerChannelId,
      nick: 'moon.freenode.net',
      type: 'status',
      text: 'Connecting as siverGad',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadServerChannelId,
      nick: 'siverGad',
      type: 'banlist',
      text: '',
      meta: {
        channelName: '#developerslv',
        bans: [
          {
            author: 'siers!~ij@NixOS/user/siers',
            target: '*!~ij@NixOS/user/siers',
            timestamp: 1553607589,
          },
        ],
      },
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadServerChannelId,
      nick: 'moon.freenode.net',
      type: 'status',
      text: 'Disconnected as daGrevis',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadDaGrevisChannelId,
      nick: 'daGrevis',
      type: 'text',
      text: 'Hello, siverGad',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadDaGrevisChannelId,
      nick: 'siverGad',
      type: 'text',
      text: 'Hi, daGrevis - I am /whois-ing you',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadDaGrevisChannelId,
      nick: 'daGrevis',
      type: 'whois',
      text: '',
      meta: {
        account: 'daGrevis',
        ident: '~daGrevis',
        hostname: 'unaffiliated/dagrevis',
        realName: 'Raitis Stengrevics',
        server: 'weber.freenode.net',
        serverInfo: 'US',
        secure: true,
      },
    },
  ])

  await knex('users').insert([
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'msks-dev',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: publicMeeseekeriaChannelId,
      nick: 'siverGad',
    },
    {
      id: uuidv4(),
      createdAt: getUniqueDate(),
      channelId: siverGadMeeseekeria2ChannelId,
      nick: 'siverGad',
    },
  ])
}
<|endoftext|>


<commit_before>const BinaryPjax       = require('../../base/binary_pjax');
const Client           = require('../../base/client');
const Header           = require('../../base/header');
const BinarySocket     = require('../../base/socket');
const jpClient         = require('../../common/country_base').jpClient;
const jpResidence      = require('../../common/country_base').jpResidence;
const isCryptocurrency = require('../../common/currency').isCryptocurrency;
const urlFor           = require('../../../_common/url').urlFor;

const Cashier = (() => {
    let href = '';

    const showContent = () => {
        Client.activateByClientType();
        Header.upgradeMessageVisibility(); // To handle the upgrade buttons visibility
    };

    const displayTopUpButton = () => {
        BinarySocket.wait('balance').then((response) => {
            const currency  = response.balance.currency;
            const balance   = +response.balance.balance;
            const can_topup = (currency !== 'JPY' && balance <= 1000) || (currency === 'JPY' && balance <= 100000);
            const top_up_id = '#VRT_topup_link';
            const $a        = $(top_up_id);
            if (!$a) {
                return;
            }
            const classes   = ['toggle', 'button-disabled'];
            const new_el    = { class: $a.attr('class').replace(classes[+can_topup], classes[1 - +can_topup]), html: $a.html(), id: $a.attr('id') };
            if (can_topup) {
                href        = href || urlFor('/cashier/top_up_virtualws');
                new_el.href = href;
            }
            $a.replaceWith($('<a/>', new_el));
            $(top_up_id).parent().setVisibility(1);
        });
    };

    const onLoad = () => {
        if (jpClient() && !jpResidence()) {
            BinaryPjax.loadPreviousUrl();
        }
        if (Client.isLoggedIn()) {
            BinarySocket.wait('authorize').then(() => {
                const is_virtual = Client.get('is_virtual');
                const is_crypto  = isCryptocurrency(Client.get('currency'));
                if (is_virtual) {
                    displayTopUpButton();
                }
                const residence = Client.get('residence');
                if (residence) {
                    BinarySocket.send({ paymentagent_list: residence }).then((response) => {
                        if (response.paymentagent_list && response.paymentagent_list.length) {
                            $('#payment-agent-section').setVisibility(1);
                        }
                    });
                }
                $(is_crypto ? '.crypto_currency' : '.normal_currency').setVisibility(1);
                if (/^BCH/.test(Client.get('currency'))) {
                    document.getElementById('message_bitcoin_cash').setVisibility(1);
                }
            });
        }
        showContent();
    };

    return {
        onLoad,
        PaymentMethods: { onLoad: () => { showContent(); } },
    };
})();

module.exports = Cashier;
<commit_msg>fix paymentagent check<commit_after>const BinaryPjax       = require('../../base/binary_pjax');
const Client           = require('../../base/client');
const Header           = require('../../base/header');
const BinarySocket     = require('../../base/socket');
const jpClient         = require('../../common/country_base').jpClient;
const jpResidence      = require('../../common/country_base').jpResidence;
const isCryptocurrency = require('../../common/currency').isCryptocurrency;
const urlFor           = require('../../../_common/url').urlFor;
const getPropertyValue = require('../../../_common/utility').getPropertyValue;

const Cashier = (() => {
    let href = '';

    const showContent = () => {
        Client.activateByClientType();
        Header.upgradeMessageVisibility(); // To handle the upgrade buttons visibility
    };

    const displayTopUpButton = () => {
        BinarySocket.wait('balance').then((response) => {
            const currency  = response.balance.currency;
            const balance   = +response.balance.balance;
            const can_topup = (currency !== 'JPY' && balance <= 1000) || (currency === 'JPY' && balance <= 100000);
            const top_up_id = '#VRT_topup_link';
            const $a        = $(top_up_id);
            if (!$a) {
                return;
            }
            const classes   = ['toggle', 'button-disabled'];
            const new_el    = { class: $a.attr('class').replace(classes[+can_topup], classes[1 - +can_topup]), html: $a.html(), id: $a.attr('id') };
            if (can_topup) {
                href        = href || urlFor('/cashier/top_up_virtualws');
                new_el.href = href;
            }
            $a.replaceWith($('<a/>', new_el));
            $(top_up_id).parent().setVisibility(1);
        });
    };

    const onLoad = () => {
        if (jpClient() && !jpResidence()) {
            BinaryPjax.loadPreviousUrl();
        }
        if (Client.isLoggedIn()) {
            BinarySocket.wait('authorize').then(() => {
                const is_virtual = Client.get('is_virtual');
                const is_crypto  = isCryptocurrency(Client.get('currency'));
                if (is_virtual) {
                    displayTopUpButton();
                }
                const residence = Client.get('residence');
                if (residence) {
                    BinarySocket.send({ paymentagent_list: residence }).then((response) => {
                        const list = getPropertyValue(response, ['paymentagent_list', 'list']);
                        if (list && list.length) {
                            $('#payment-agent-section').setVisibility(1);
                        }
                    });
                }
                $(is_crypto ? '.crypto_currency' : '.normal_currency').setVisibility(1);
                if (/^BCH/.test(Client.get('currency'))) {
                    document.getElementById('message_bitcoin_cash').setVisibility(1);
                }
            });
        }
        showContent();
    };

    return {
        onLoad,
        PaymentMethods: { onLoad: () => { showContent(); } },
    };
})();

module.exports = Cashier;
<|endoftext|>


<commit_before>
/*
load forcast of current location on load. Then upon submit/enter return forecast for searched city.
Use Autocomplete API for search results. This will return a Json. list the city names from the Json,
and attach the link associated with each city so it will load the forecast from that city. Populate new
forecast into cards.
*/

"use strict";

angular.module('myapp')
  .controller("WeatherController", function($scope, $http){
    //$scope.forecastDay = [];
    //$scope.forecastNight = [];
    $scope.forecast = [];
    if (navigator.geolocation) navigator.geolocation.getCurrentPosition(onPositionUpdate);

    function onPositionUpdate(position) {
      var lati = position.coords.latitude;
      var longi = position.coords.longitude;
      var url = 'https://api.wunderground.com/api/4a82154c39d11213/forecast/q/' + lati + ',' + longi + '.json';

      $http.get(url)
        .then(function(info) {
          //console.log(info);
          for(var i = 0; i < 8; i++){
            var item = {
              title: info.data.forecast.txt_forecast.forecastday[i].title,
              icon: info.data.forecast.txt_forecast.forecastday[i].icon_url,
              conditionsI: info.data.forecast.txt_forecast.forecastday[i].fcttext,
              conditionsM: info.data.forecast.txt_forecast.forecastday[i].fcttext_metric,
            };
            item.icon = item.icon.repleace("http", "https");
            $scope.forecast.push(item);

            //if(i%2 === 0){
            //  $scope.forecastDay.push(item);
            //}else{
            //  $scope.forecastNight.push(item);
            //}

            }
            //console.log($scope.forecastDay);
            //console.log($scope.forecastNight);
            console.log($scope.forecast);

        });
      //$scope.search = function(e){
        //e.preventDefault();

      //};

   }

  });
<commit_msg>Update controller1.js<commit_after>
/*
load forcast of current location on load. Then upon submit/enter return forecast for searched city.
Use Autocomplete API for search results. This will return a Json. list the city names from the Json,
and attach the link associated with each city so it will load the forecast from that city. Populate new
forecast into cards.
*/

"use strict";

angular.module('myapp')
  .controller("WeatherController", function($scope, $http){
    //$scope.forecastDay = [];
    //$scope.forecastNight = [];
    $scope.forecast = [];
    if (navigator.geolocation) navigator.geolocation.getCurrentPosition(onPositionUpdate);

    function onPositionUpdate(position) {
      var lati = position.coords.latitude;
      var longi = position.coords.longitude;
      var url = 'https://api.wunderground.com/api/4a82154c39d11213/forecast/q/' + lati + ',' + longi + '.json';

      $http.get(url)
        .then(function(info) {
          //console.log(info);
          for(var i = 0; i < 8; i++){
            var item = {
              title: info.data.forecast.txt_forecast.forecastday[i].title,
              icon: info.data.forecast.txt_forecast.forecastday[i].icon_url,
              conditionsI: info.data.forecast.txt_forecast.forecastday[i].fcttext,
              conditionsM: info.data.forecast.txt_forecast.forecastday[i].fcttext_metric,
            };
            var temp = item.icon;
            icon = icon.repleace("http", "https");
            item.icon = temp;
            $scope.forecast.push(item);

            //if(i%2 === 0){
            //  $scope.forecastDay.push(item);
            //}else{
            //  $scope.forecastNight.push(item);
            //}

            }
            //console.log($scope.forecastDay);
            //console.log($scope.forecastNight);
            console.log($scope.forecast);

        });
      //$scope.search = function(e){
        //e.preventDefault();

      //};

   }

  });
<|endoftext|>