<commit_before>var PUB_KEY = $("#pub_key").val();
var SUB_KEY = $("#sub_key").val();
var SECRET_KEY = $("#secret_key").val();
var UUID = $("#uuid").val();

function stateInit() {
    stateEnable = $("#stateEnable").prop('checked');
    state = stateEnable && $("#state").val().length > 0 ? JSON.parse($("#state").val()) : false;
}
stateInit();
$("#state, #stateEnable").bind("change", function () {
    stateInit();
});

function channelGroupInit() {
    channelGroupEnable = $("#channelGroupEnable").prop('checked');
    channelGroup = channelGroupEnable && $("#channelGroup").val().length > 0 ? $("#channelGroup").val() : false;
}

channelGroupInit();
$("#channelGroup, #channelGroupEnable").bind("change", function () {
    channelGroupInit();
});

function channelInit() {
    channelEnable = $("#channelEnable").prop('checked');
    channel = channelEnable && $("#channel").val().length > 0 ? $("#channel").val() : false;
}

channelInit();
$("#channel, #channelEnable").bind("change", function () {
    channelInit();
});

function authInit() {
    authEnable = $("#authEnable").prop('checked');
    auth = authEnable && $("#auth").val().length > 0 ? $("#auth").val() : false;
}

authInit();
$("#auth, #authEnable").bind("change", function () {
    authInit();
});

function messageInit() {
    message = $("#message").val().length > 0 ? $("#message").val() : null;
}

messageInit();
$("#message").bind("change", function () {
    messageInit();
});

function originInit() {
    origin = $("#origin").val().length > 0 ? $("#origin").val() : null;
}
originInit();
$("#origin").bind("change", function () {
    originInit();
});

pubnub = PUBNUB.init({
    "subscribe_key": SUB_KEY,
    "publish_key": PUB_KEY,
    "secret_key": SECRET_KEY,
    "uuid": UUID,
    "origin": origin
});

function pnTime() {
    pubnub.time(
        function (time) {
            displayCallback(time);
        }
    );
}

function pnPublish() {
    if (channel) {
        pubnub.publish({
            channel: channel,
            message: $("#message").val(),
            callback: displayCallback,
            error: displayCallback
        });
    }
}

function displayCallback(m, e, c) {
    // Use first and last args

    if (c && m) {
        console.log(JSON.stringify(c + ": " + m));
        $("#output").html(c + ":" + JSON.stringify(m) + "\n" + $("#output").html());

        // Only one argument
    } else if (m) {
        console.log(JSON.stringify(m));
        $("#output").html(JSON.stringify(m) + "\n" + $("#output").html());

    }
}

function pnSubscribe() {
    console.log('pnSubscribe');
    pubnub.subscribe({
        channel: channel,
        channel_group : channelGroup,
        callback: displayCallback,
        error: displayCallback,
        heartbeat : 15
    });
}

function pnHistory() {
    if (channel) {
        pubnub.history({
            channel: channel,
            callback: displayCallback,
            error: displayCallback,
            count: 5
        });
    } else if (channelGroup) {
        pubnub.history({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback,
            count: 5
        });
    }
}

function pnUnsubscribe() {
    if (channel) {
        pubnub.unsubscribe({
            channel: channel,
            callback: displayCallback,
            error: displayCallback
        });
    } else if (channelGroup) {
        pubnub.unsubscribe({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback
        });
    }
}

function pnGetChannelGroups() {
    pubnub.channel_group({
        callback: displayCallback,
        error: displayCallback,
    });
}

function pnDeleteChannelGroups() {
    pubnub.channel_group_remove({
        callback: displayCallback,
        error: displayCallback,
        channel_group : channelGroup

    });
}

function pnGetChannelsForChannelGroup() {
    pubnub.channel_group({
        callback: displayCallback,
        error: displayCallback,
        channel_group: channelGroup,
    });
}

function pnAddChannelToChannelGroup() {
    pubnub.channel_group({
        callback: displayCallback,
        error: displayCallback,
        channels: channel,
        channel_group: channelGroup,
    });
}

function pnRemoveChannelFromChannelGroup() {
    pubnub.channel_group_remove({
        callback: displayCallback,
        error: displayCallback,
        channels: channel,
        channel_group: channelGroup,
    });
}

function pnCloak(cloak) {
    pubnub.channel_group_cloak({
        channel_group : channelGroup,
        channel: channel,
        cloak: cloak,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnSetState() {
    pubnub.state({
        channel_group : channelGroup,
        channel: channel,
        state: state,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnGetState() {
    pubnub.state({
        channel_group : channelGroup,
        channel: channel,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnGrant() {
    pubnub.grant({
        channel_group : channelGroup,
        channel: channel,
        read   : $("#check_read").prop('checked'),
        write  : $("#check_write").prop('checked'),
        manage : $("#check_manage").prop('checked'),
        callback: displayCallback,
        error: displayCallback
    });
}

function pnRevoke() {
    pubnub.revoke({
        channel_group : channelGroup,
        channel: channel,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnAudit() {
    pubnub.audit({
        channel_group : channelGroup,
        channel: channel,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnHereNow(){
    if (channel) {
        pubnub.here_now({
            channel: channel,
            callback: displayCallback,
            error: displayCallback
        });
    } else if (!channelGroup) {
        pubnub.here_now({
            callback: displayCallback,
            error: displayCallback
        });
    } else if (channelGroup) {
        pubnub.here_now({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback
        });
    }
}

function pnWhereNow(){
    if (channel) {
        pubnub.where_now({
            channel: channel,
            callback: displayCallback,
            error: displayCallback
        });

    } else if (channelGroup) {
        pubnub.where_now({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback
        });
    }
}

pubnub.auth(auth);

$("#whereNow").click(function () {
    pnWhereNow();
});

$("#hereNow").click(function () {
    pnHereNow();
});

$("#getState").click(function () {
    pnGetState();
});

$("#setState").click(function () {
    pnSetState();
});

$("#history").click(function () {
    pnHistory();
});

$("#removeChannelFromChannelGroup").click(function () {
    pnRemoveChannelFromChannelGroup();
});

$("#addChannelToChannelGroup").click(function () {
    pnAddChannelToChannelGroup();
});

$("#getChannelsForChannelGroup").click(function () {
    pnGetChannelsForChannelGroup();
});

$("#removeChannelGroup").click(function () {
    pnDeleteChannelGroups();
});

$("#getAllChannelGroups").click(function () {
    pnGetChannelGroups();
});

$("#publish").click(function () {
    pnPublish();
});

$("#time").click(function () {
    pnTime();
});

$("#subscribe").click(function () {
    pnSubscribe();
});

$("#unsubscribe").click(function () {
    pnUnsubscribe();
});

$("#grant").click(function () {
    pnGrant();
});

$("#revoke").click(function () {
    pnRevoke();
});

$("#audit").click(function () {
    pnAudit();
});

$("#setCloak").click(function () {
    pnCloak(true);
});
$("#unsetCloak").click(function () {
    pnCloak(fals);
});<commit_msg>[fixes #78298302] fixed<commit_after>var PUB_KEY = $("#pub_key").val();
var SUB_KEY = $("#sub_key").val();
var SECRET_KEY = $("#secret_key").val();
var UUID = $("#uuid").val();

function stateInit() {
    stateEnable = $("#stateEnable").prop('checked');
    state = stateEnable && $("#state").val().length > 0 ? JSON.parse($("#state").val()) : false;
}
stateInit();
$("#state, #stateEnable").bind("change", function () {
    stateInit();
});

function channelGroupInit() {
    channelGroupEnable = $("#channelGroupEnable").prop('checked');
    channelGroup = channelGroupEnable && $("#channelGroup").val().length > 0 ? $("#channelGroup").val() : false;
}

channelGroupInit();
$("#channelGroup, #channelGroupEnable").bind("change", function () {
    channelGroupInit();
});

function channelInit() {
    channelEnable = $("#channelEnable").prop('checked');
    channel = channelEnable && $("#channel").val().length > 0 ? $("#channel").val() : false;
}

channelInit();
$("#channel, #channelEnable").bind("change", function () {
    channelInit();
});

function authInit() {
    authEnable = $("#authEnable").prop('checked');
    auth = authEnable && $("#auth").val().length > 0 ? $("#auth").val() : false;
}

authInit();
$("#auth, #authEnable").bind("change", function () {
    authInit();
});

function messageInit() {
    message = $("#message").val().length > 0 ? $("#message").val() : null;
}

messageInit();
$("#message").bind("change", function () {
    messageInit();
});

function originInit() {
    origin = $("#origin").val().length > 0 ? $("#origin").val() : null;
}
originInit();
$("#origin").bind("change", function () {
    originInit();
});

pubnub = PUBNUB.init({
    "subscribe_key": SUB_KEY,
    "publish_key": PUB_KEY,
    "secret_key": SECRET_KEY,
    "uuid": UUID,
    "origin": origin
});

function pnTime() {
    pubnub.time(
        function (time) {
            displayCallback(time);
        }
    );
}

function pnPublish() {
    if (channel) {
        pubnub.publish({
            channel: channel,
            message: $("#message").val(),
            callback: displayCallback,
            error: displayCallback
        });
    }
}

function displayCallback(m, e, c) {
    // Use first and last args

    if (c && m) {
        console.log(JSON.stringify(c + ": " + m));
        $("#output").html(c + ":" + JSON.stringify(m) + "\n" + $("#output").html());

        // Only one argument
    } else if (m) {
        console.log(JSON.stringify(m));
        $("#output").html(JSON.stringify(m) + "\n" + $("#output").html());

    }
}

function pnSubscribe() {
    console.log('pnSubscribe');
    pubnub.subscribe({
        channel: channel,
        channel_group : channelGroup,
        callback: displayCallback,
        error: displayCallback,
        heartbeat : 15
    });
}

function pnHistory() {
    if (channel) {
        pubnub.history({
            channel: channel,
            callback: displayCallback,
            error: displayCallback,
            count: 5
        });
    } else if (channelGroup) {
        pubnub.history({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback,
            count: 5
        });
    }
}

function pnUnsubscribe() {
    if (channel) {
        pubnub.unsubscribe({
            channel: channel,
            callback: displayCallback,
            error: displayCallback
        });
    } else if (channelGroup) {
        pubnub.unsubscribe({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback
        });
    }
}

function pnGetChannelGroups() {
    pubnub.channel_group({
        channel_group : channelGroup,
        callback: displayCallback,
        error: displayCallback,
    });
}

function pnDeleteChannelGroups() {
    pubnub.channel_group_remove({
        callback: displayCallback,
        error: displayCallback,
        channel_group : channelGroup

    });
}

function pnGetChannelsForChannelGroup() {
    pubnub.channel_group({
        callback: displayCallback,
        error: displayCallback,
        channel_group: channelGroup,
    });
}

function pnAddChannelToChannelGroup() {
    pubnub.channel_group({
        callback: displayCallback,
        error: displayCallback,
        channels: channel,
        channel_group: channelGroup,
    });
}

function pnRemoveChannelFromChannelGroup() {
    pubnub.channel_group_remove({
        callback: displayCallback,
        error: displayCallback,
        channels: channel,
        channel_group: channelGroup,
    });
}

function pnCloak(cloak) {
    pubnub.channel_group_cloak({
        channel_group : channelGroup,
        channel: channel,
        cloak: cloak,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnSetState() {
    pubnub.state({
        channel_group : channelGroup,
        channel: channel,
        state: state,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnGetState() {
    pubnub.state({
        channel_group : channelGroup,
        channel: channel,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnGrant() {
    pubnub.grant({
        channel_group : channelGroup,
        channel: channel,
        read   : $("#check_read").prop('checked'),
        write  : $("#check_write").prop('checked'),
        manage : $("#check_manage").prop('checked'),
        callback: displayCallback,
        error: displayCallback
    });
}

function pnRevoke() {
    pubnub.revoke({
        channel_group : channelGroup,
        channel: channel,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnAudit() {
    pubnub.audit({
        channel_group : channelGroup,
        channel: channel,
        callback: displayCallback,
        error: displayCallback
    });
}

function pnHereNow(){
    if (channel) {
        pubnub.here_now({
            channel: channel,
            callback: displayCallback,
            error: displayCallback
        });
    } else if (!channelGroup) {
        pubnub.here_now({
            callback: displayCallback,
            error: displayCallback
        });
    } else if (channelGroup) {
        pubnub.here_now({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback
        });
    }
}

function pnWhereNow(){
    if (channel) {
        pubnub.where_now({
            channel: channel,
            callback: displayCallback,
            error: displayCallback
        });

    } else if (channelGroup) {
        pubnub.where_now({
            channel_group: channelGroup,
            callback: displayCallback,
            error: displayCallback
        });
    }
}

pubnub.auth(auth);

$("#whereNow").click(function () {
    pnWhereNow();
});

$("#hereNow").click(function () {
    pnHereNow();
});

$("#getState").click(function () {
    pnGetState();
});

$("#setState").click(function () {
    pnSetState();
});

$("#history").click(function () {
    pnHistory();
});

$("#removeChannelFromChannelGroup").click(function () {
    pnRemoveChannelFromChannelGroup();
});

$("#addChannelToChannelGroup").click(function () {
    pnAddChannelToChannelGroup();
});

$("#getChannelsForChannelGroup").click(function () {
    pnGetChannelsForChannelGroup();
});

$("#removeChannelGroup").click(function () {
    pnDeleteChannelGroups();
});

$("#getAllChannelGroups").click(function () {
    pnGetChannelGroups();
});

$("#publish").click(function () {
    pnPublish();
});

$("#time").click(function () {
    pnTime();
});

$("#subscribe").click(function () {
    pnSubscribe();
});

$("#unsubscribe").click(function () {
    pnUnsubscribe();
});

$("#grant").click(function () {
    pnGrant();
});

$("#revoke").click(function () {
    pnRevoke();
});

$("#audit").click(function () {
    pnAudit();
});

$("#setCloak").click(function () {
    pnCloak(true);
});
$("#unsetCloak").click(function () {
    pnCloak(fals);
});<|endoftext|>


<commit_before>console.log('This would be the main JS file.');
<commit_msg>Delete main.js<commit_after><|endoftext|>


<commit_before>console.log("Main JS file loaded");
//Globals
OUTPUT = null;
INPUT = null;

// setup the globals
function init(){
  OUTPUT = $('#outputTextArea');
  INPUT = $('#inputTextArea');
}

function test(){
  lexer(INPUT.val());
}

function lexer(input){
  console.log(input);
  console.log(input.split("\n"));
  raiseFatalError(input);
}

function raiseFatalError(message){
  message = "Fatal Error: " + message + "\n";
  OUTPUT.append(message);
  throw new Error(message);
}<commit_msg>Checking for invalid characters working<commit_after>console.log("Main JS file loaded");
//Globals
OUTPUT = null;
INPUT = null;

//Regex Constants
TYPE = 'int|string|boolean';
CHAR = 'a-zA-Z';
SPACE = '\\s';
DIGIT = '\\d';
BOOLOP = '(?:^|[^!=])([!=]=)(?!=)'; // Matches only == and !=, === and !== fails
BOOLVAL = 'false|true';
INTOP = '\\+';
BLOCKS = "\\" + ["{", "}", "(", ")", "\"", "\""].join("\\"); // Curly Brace,

INVALID = "[^" + CHAR + SPACE + DIGIT + INTOP + BLOCKS + "!" + "=" + "$" + "]";

// setup the globals
function init(){
  OUTPUT = $('#outputTextArea');
  INPUT = $('#inputTextArea');
}

function test(){
  OUTPUT.empty();  // Clear the output text area.
  lexer(INPUT.val());
}

function lexer(input){
  checkInvalids();
  //console.log(input.split("\n"));
  //raiseFatalError(input);
}

function checkInvalids(){
  var lines = INPUT.val().split("\n");
  var line = 0;
  var invalid_re = new RegExp(INVALID, "g");
  var invalid_check;

  while(line < lines.length){
    invalid_check = invalid_re.exec(lines[line]);
    console.log(lines[line]);
    if(invalid_check != null) raiseFatalError("Invalid character found at line: " + (line + 1) );
    line++;
  }
  writeOutput("No invalid characters found.");
}

function writeOutput(message){
  OUTPUT.append(message);
}

function raiseFatalError(message){
  message = "Fatal Error: " + message + "\n";
  writeOutput(message);
  throw new Error(message);
}<|endoftext|>


<commit_before>// (function() {

  function add(a1, a2) {
    return a1 + a2;
    console.log(add);
  }

  function subtract(s1, s2) {
    return s1 - s2;
    console.log(subtract);
  }

  function multiply(m1, m2) {
    return m1 * m2;
    console.log(multiply);
  }

  function divide(d1, d2) {
    return d1/d2;
    console.log(divide);
  }

  function power(p1, p2) {
    return Math.pow(p1, p2);
    console.log(power);
  }

  //STEP 6
  function test_add_1() {
    return add(5, 4);
    // 9
  }

  //STEP 7
  function test_add_2() {
    var ta3 = 3;
    return add(5,4) + ta3;
    // 12
  }

  //STEP 8
  function test_subtract_1() {
    var sub1 = 5;
    var sub2 = 4;
    return subtract(5, 4);
    // 1
  }

  //STEP 9
  function test_subtract_2() {
    var ts1 = 5;
    var ts2 = 4;
    var ts3 = 3;
    var ts4 = subtract(5,4);
    return ts3 - ts4;
    // 2
  }

  //STEP 10-1
  var add1 = add(1, 2);
  console.log(add1);

  //STEP 10-2
  var add21 = add(2,3);
  var add22 = add(1, add21);
  console.log(add22);

  //STEP 10-3
  var add31 = add(1, 2);
  var add32 = add(3, 4);
  var add33 = add(add31, add32);
  add(add(1, 2), add(3, 4));
  console.log(add33);

  //STEP 10-4
  var sub = subtract(10, 9);
  console.log(sub);

  //STEP 10-5
  var sub5 = subtract(10, subtract(19, 10));
  console.log(sub5);

  //STEP 10-6
  var sub6 = subtract(subtract(20, 10), subtract(19, 10));
  console.log(sub6);

  //STEP 10-7
  var mul = multiply(2, 3);
  console.log(mul);

  //STEP 10-8
  var mul8 = multiply(2, );
  console.log(mul8);

  //STEP 10-9
  var mul9 = multiply(multiply(1, 2), multiply(3, 4));
  console.log(mul9);

  //STEP 10-10

  //THE FOLLOWING IS USED TO DEBUG FUNCTION BY BREAKING INTO
  //EACH INDIVIDUAL OPERATION. THE NEW 'PIECE OF PAPER'
  //var op1 = add(1,2);
  //console.log("op1 "op1);
  // var op2 = subtract(8, 4);
  // console.log("op2 "op2);
  // var op3 = add(test_add_1(), test_subtract_1());
  // console.log("op3 "op3);
  // var op4 = subtract(test_add_2(), test_subtract_2());
  // console.log("op4 "op4);
  // var ap1 = multiply(op1, op2);
  // console.log("ap1 "ap1);
  // var ap2 = multiply(op3, op4):
  // console.log("ap2 "ap2);
  // var mul10 = multiply(ap1, ap2);
  // console.log("multiply("+ap1+", "+ap2+" = " +mul10);
  // console.log(mul10);

  var mul10 = multiply(
                        multiply(
                                  add(1, 2),
                                  subtract(8,4)
                                  ),
                        multiply(
                                  add(
                                      test_add_1(),
                                      test_subtract_1()
                                      ),
                                  subtract(
                                      test_add_2(),
                                      test_subtract_2()
                                      )
                                  )
                        );
  console.log(mul10);

// }());<commit_msg>step 10-8 fixed<commit_after>// (function() {

  function add(a1, a2) {
    return a1 + a2;
    console.log(add);
  }

  function subtract(s1, s2) {
    return s1 - s2;
    console.log(subtract);
  }

  function multiply(m1, m2) {
    return m1 * m2;
    console.log(multiply);
  }

  function divide(d1, d2) {
    return d1/d2;
    console.log(divide);
  }

  function power(p1, p2) {
    return Math.pow(p1, p2);
    console.log(power);
  }

  //STEP 6
  function test_add_1() {
    return add(5, 4);
    // 9
  }

  //STEP 7
  function test_add_2() {
    var ta3 = 3;
    return add(5,4) + ta3;
    // 12
  }

  //STEP 8
  function test_subtract_1() {
    var sub1 = 5;
    var sub2 = 4;
    return subtract(5, 4);
    // 1
  }

  //STEP 9
  function test_subtract_2() {
    var ts1 = 5;
    var ts2 = 4;
    var ts3 = 3;
    var ts4 = subtract(5,4);
    return ts3 - ts4;
    // 2
  }

  //STEP 10-1
  var add1 = add(1, 2);
  console.log(add1);

  //STEP 10-2
  var add21 = add(2,3);
  var add22 = add(1, add21);
  console.log(add22);

  //STEP 10-3
  var add31 = add(1, 2);
  var add32 = add(3, 4);
  var add33 = add(add31, add32);
  add(add(1, 2), add(3, 4));
  console.log(add33);

  //STEP 10-4
  var sub = subtract(10, 9);
  console.log(sub);

  //STEP 10-5
  var sub5 = subtract(10, subtract(19, 10));
  console.log(sub5);

  //STEP 10-6
  var sub6 = subtract(subtract(20, 10), subtract(19, 10));
  console.log(sub6);

  //STEP 10-7
  var mul = multiply(2, 3);
  console.log(mul);

  //STEP 10-8
  var mul8 = multiply(2, multiply(1, 3));
  console.log(mul8);

  //STEP 10-9
  var mul9 = multiply(multiply(1, 2), multiply(3, 4));
  console.log(mul9);

  //STEP 10-10

  //THE FOLLOWING IS USED TO DEBUG FUNCTION BY BREAKING INTO
  //EACH INDIVIDUAL OPERATION. THE NEW 'PIECE OF PAPER'
  //var op1 = add(1,2);
  //console.log("op1 "op1);
  // var op2 = subtract(8, 4);
  // console.log("op2 "op2);
  // var op3 = add(test_add_1(), test_subtract_1());
  // console.log("op3 "op3);
  // var op4 = subtract(test_add_2(), test_subtract_2());
  // console.log("op4 "op4);
  // var ap1 = multiply(op1, op2);
  // console.log("ap1 "ap1);
  // var ap2 = multiply(op3, op4):
  // console.log("ap2 "ap2);
  // var mul10 = multiply(ap1, ap2);
  // console.log("multiply("+ap1+", "+ap2+" = " +mul10);
  // console.log(mul10);

  var mul10 = multiply(
                        multiply(
                                  add(1, 2),
                                  subtract(8,4)
                                  ),
                        multiply(
                                  add(
                                      test_add_1(),
                                      test_subtract_1()
                                      ),
                                  subtract(
                                      test_add_2(),
                                      test_subtract_2()
                                      )
                                  )
                        );
  console.log(mul10);

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


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ArgumentsRequired, ExchangeError, OrderNotFound } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class bkex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bkex',
            'name': 'BKEX',
            'countries': ['BVI'],
            'version': 'v2',
            'rateLimit': 1000,
            'has': {
                'createMarketOrder': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
                'fetchCurrencies': true,
                'fetchTickers': false,
                'fetchTicker': true,
                'fetchOHLCV': true,
                'fetchOrderBook': true,
                'fetchTrades': false,
            },
            'urls': {
                'api': {
                    'public': 'https://api.bkex.io/v2',
                    'private': 'https://api.bkex.io/v2/u',
                },
                'www': 'https://www.bkex.com',
                'doc': [
                    'https://bkexapi.github.io/docs/api_en.htm',
                ],
                'fees': 'https://www.bkex.com/help/instruction/33',
            },
            'api': {
                'public': {
                    'get': [
                        'common/symbols',
                        'common/currencys',
                        'exchangeInfo',
                        'q/depth',
                        'q/deals',
                        'q/tickers',
                        'q/ticker/price',
                        'q/kline',
                    ],
                },
                'private': {
                    'get': [
                        'account/balance',
                        'order/openOrders',
                        'order/openOrder/detail',
                        'order/historyOrders',
                    ],
                    'post': [
                        'order/create',
                        'order/cancel',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.09,
                    'taker': 0.12,
                },
            },
        });
    }

    async fetchMarkets (params = {}) {
        const response = await this.publicGetCommonSymbols (params);
        const data = this.safeValue (response, 'data');
        const numMarkets = data.length;
        if (numMarkets < 1) {
            throw new ExchangeError (this.id + ' publicGetExchangeInfo returned empty response: ' + this.json (data));
        }
        const result = [];
        for (let i = 0; i < data.length; i++) {
            const market = data[i];
            const id = this.safeString (market, 'symbol');
            const baseId = id.split ('_')[0];
            const quoteId = id.split ('_')[1];
            const base = this.safeCurrencyCode (baseId);
            const quote = this.safeCurrencyCode (quoteId);
            const symbol = base + '/' + quote;
            const precision = {
                'amount': undefined,
                'price': this.safeInteger (market, 'pricePrecision'),
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': undefined,
                        'max': undefined,
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': undefined,
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const timestamp = this.milliseconds ();
        const market = this.market (symbol);
        const request = this.extend ({
            'symbol': market['id'],
        }, params);
        const response = await this.publicGetQTickers (request);
        const ticker = this.safeValue (response, 'data');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker[0], 'high'),
            'low': this.safeFloat (ticker[0], 'low'),
            'bid': undefined,
            'bidVolume': undefined,
            'ask': undefined,
            'askVolume': undefined,
            'vwap': undefined,
            'previousClose': undefined,
            'open': this.safeFloat (ticker[0], 'open'),
            'close': this.safeFloat (ticker[0], 'close'),
            'last': this.safeFloat (ticker[0], 'close'),
            'percentage': undefined,
            'change': this.safeFloat (ticker[0], 'change'),
            'average': undefined,
            'baseVolume': this.safeFloat (ticker[0], 'volume'),
            'quoteVolume': this.safeFloat (ticker[0], 'quoteVolume'),
            'info': ticker[0],
        };
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'symbol': symbol,
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.publicGetQDepth (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        return this.parseOrderBook (data, undefined, 'bid', 'ask');
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '5m', since = undefined, limit = undefined) {
        return [
            this.timeInSeconds (ohlcv[0]),
            this.safeFloat (ohlcv, 1),
            this.safeFloat (ohlcv, 2),
            this.safeFloat (ohlcv, 3),
            this.safeFloat (ohlcv, 4),
            this.safeFloat (ohlcv, 5),
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = 1, params = {}) {
        const request = {
            'symbol': symbol,
            'size': limit,
        };
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        if (since !== undefined) {
            request['since'] = parseInt (since / 1000);
        }
        const duration = this.parseTimeframe (timeframe);
        const timerange = limit * duration * 1000;
        if (since === undefined) {
            if (limit === undefined) {
                throw new ArgumentsRequired (this.id + ' fetchOHLCV requires a since argument or a limit argument');
            } else {
                request['to'] = this.milliseconds ();
                request['from'] = request['to'] - timerange;
            }
        } else {
            request['from'] = parseInt (since);
            request['to'] = this.sum (request['from'], timerange);
        }
        const response = await this.publicGetQKline (request);
        // {
        //     "symbol": "BTC_USDT",
        //     "volume": 12321.1234,
        //     "open": 4124.3,
        //     "close": 3873.213,
        //     "low": 3521.1,
        //     "high": 4521.5,
        //     "quoteVolume": 71031537.978665,
        //     "ts": 1529739295000
        // }
        const data = this.safeValue (response, 'data', []);
        return this.parseOHLCVs (data, undefined, timeframe, since, limit);
    }

    async fetchCurrencies (params = {}) {
        const response = await this.publicGetCommonCurrencys (params);
        const items = response['data'];
        const result = {};
        for (let i = 0; i < items.length; i++) {
            //    {
            //       "currency": "ETH",
            //       "maxWithdrawOneDay": 2000,
            //       "maxWithdrawSingle": 2000,
            //       "minWithdrawSingle": 0.1,
            //       "supportDeposit": true,
            //       "supportTrade": true,
            //       "supportWithdraw": true,
            //       "withdrawFee": 0.008
            //     },
            const item = items[i];
            const id = this.safeString (item, 'currency');
            const code = this.safeCurrencyCode (id);
            result[code] = {
                'id': id,
                'code': code,
                'name': this.safeString (item, 'currency'),
                'active': this.safeValue (item, 'supportTrade') && this.safeValue (item, 'supportDeposit'),
                'fee': this.safeFloat (item, 'withdrawFee'),
                'precision': undefined,
                'info': item,
                'limits': {
                    'amount': { 'min': undefined, 'max': undefined },
                    'price': { 'min': undefined, 'max': undefined },
                    'cost': { 'min': undefined, 'max': undefined },
                    'withdraw': { 'min': this.safeFloat (item, 'minWithdrawSingle'), 'max': this.safeFloat (item, 'maxWithdrawSingle') },
                },
            };
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const query = this.omit (params, 'type');
        const response = await this.privateGetAccountBalance (query);
        const balances = this.safeValue (response, 'data');
        const wallets = this.safeValue (balances, 'WALLET');
        const result = { 'info': wallets };
        for (let i = 0; i < wallets.length; i++) {
            const wallet = wallets[i];
            const currencyId = wallet['currency'];
            const code = this.safeCurrencyCode (currencyId);
            const account = this.account ();
            account['free'] = this.safeFloat (wallet, 'available');
            account['total'] = this.safeFloat (wallet, 'total');
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const method = 'privatePostOrderCreate';
        const direction = side === 'buy' ? 'BID' : 'ASK';
        const request = {
            'volume': amount,
            'direction': direction,
            'symbol': symbol,
            'price': price,
            'type': type,
        };
        const response = await this[method] (this.extend (request, params));
        return {
            'id': this.safeValue (response, 'data'),
            'info': response,
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'orderId': id,
        };
        return await this.privatePostOrderCancel (this.extend (request, params));
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' fetchOrders requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': this.safeString (market, 'id'),
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.privateGetOrderOpenOrders (this.extend (request, params));
        const result = this.safeValue (response, 'data');
        return this.parseOrders (this.safeValue (result, 'data'), market, since, limit);
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        const request = {
            'orderId': id,
        };
        const response = await this.privateGetOrderOpenOrderDetail (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        if (!data) {
            throw new OrderNotFound (this.id + ' order ' + id + ' not found');
        }
        return this.parseOrder (data);
    }

    parseTrade (trade, market = undefined) {
        const timestamp = this.safeTimestamp (trade, 'createdTime');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        const id = this.safeString (trade, 'id');
        const price = this.safeFloat (trade, 'price');
        const amount = this.safeFloat (trade, 'totalVolume');
        let cost = undefined;
        if (amount !== undefined) {
            if (price !== undefined) {
                cost = price * amount;
            }
        }
        const type = undefined;
        const side = this.safeString (trade, 'type');
        return {
            'info': trade,
            'id': id,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': type,
            'side': side,
            'takerOrMaker': undefined,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {};
        if (symbol !== undefined) {
            const market = this.market (symbol);
            request['symbol'] = market['id'];
        }
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        const trades = await this.privateGetOrderHistoryOrders (this.extend (request, params));
        return this.parseTrades (trades, undefined, since, limit);
    }

    parseOrder (order, market = undefined) {
        const marketName = this.safeString (order, 'pair');
        market = market || this.findMarket (marketName);
        let timestamp = this.safeString (order, 'createdTime');
        if (timestamp !== undefined) {
            timestamp = Math.round (parseFloat (timestamp) * 1000);
        }
        const direction = this.safeValue (order, 'direction');
        const side = direction === 'BID' ? 'BUY' : 'SELL';
        const amount = this.safeFloat (order, 'totalAmount');
        const fillAmount = this.safeFloat (order, 'dealAmount', amount);
        const remaining = amount - fillAmount;
        return {
            'id': this.safeString (order, 'id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'lastTradeTimestamp': undefined,
            'status': undefined,
            'symbol': this.safeString (market, 'symbol'),
            'side': side,
            'type': this.safeString (order, 'orderType'),
            'price': this.safeFloat (order, 'price'),
            'cost': undefined,
            'amount': amount,
            'filled': fillAmount,
            'remaining': remaining,
            'fee': undefined,
            'info': order,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (method === 'GET') {
            if (Object.keys (query).length) {
                url += '?' + this.urlencode (query);
            }
        }
        if (api === 'private') {
            this.checkRequiredCredentials ();
            query = this.urlencode (query);
            if (method === 'POST') {
                body = query;
            }
            const queryArray = query.split ('&');
            const sortedQuery = this.sortBy (queryArray, 0).join ('&');
            const secret = this.encode (this.secret);
            const signature = this.hmac (sortedQuery, secret, 'sha256');
            headers = {
                'Cache-Control': 'no-cache',
                'Content-type': 'application/x-www-form-urlencoded',
                'X_ACCESS_KEY': this.apiKey,
                'X_SIGNATURE': signature,
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
        const httpCode = this.safeInteger (response, 'code', 200);
        if (response === undefined) {
            return;
        }
        if (code >= 400) {
            throw new ExchangeError (this.id + ' HTTP Error ' + code + ' reason: ' + reason);
        }
        if (httpCode >= 400) {
            const message = this.safeValue (response, 'msg', '');
            throw new ExchangeError (this.id + ' HTTP Error ' + httpCode + ' message: ' + message);
        }
    }
};
<commit_msg>fix proper symbol syntax<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ArgumentsRequired, ExchangeError, OrderNotFound } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class bkex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bkex',
            'name': 'BKEX',
            'countries': ['BVI'],
            'version': 'v2',
            'rateLimit': 1000,
            'has': {
                'createMarketOrder': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
                'fetchCurrencies': true,
                'fetchTickers': false,
                'fetchTicker': true,
                'fetchOHLCV': true,
                'fetchOrderBook': true,
                'fetchTrades': false,
            },
            'urls': {
                'api': {
                    'public': 'https://api.bkex.io/v2',
                    'private': 'https://api.bkex.io/v2/u',
                },
                'www': 'https://www.bkex.com',
                'doc': [
                    'https://bkexapi.github.io/docs/api_en.htm',
                ],
                'fees': 'https://www.bkex.com/help/instruction/33',
            },
            'api': {
                'public': {
                    'get': [
                        'common/symbols',
                        'common/currencys',
                        'exchangeInfo',
                        'q/depth',
                        'q/deals',
                        'q/tickers',
                        'q/ticker/price',
                        'q/kline',
                    ],
                },
                'private': {
                    'get': [
                        'account/balance',
                        'order/openOrders',
                        'order/openOrder/detail',
                        'order/historyOrders',
                    ],
                    'post': [
                        'order/create',
                        'order/cancel',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.09,
                    'taker': 0.12,
                },
            },
        });
    }

    async fetchMarkets (params = {}) {
        const response = await this.publicGetCommonSymbols (params);
        const data = this.safeValue (response, 'data');
        const numMarkets = data.length;
        if (numMarkets < 1) {
            throw new ExchangeError (this.id + ' publicGetExchangeInfo returned empty response: ' + this.json (data));
        }
        const result = [];
        for (let i = 0; i < data.length; i++) {
            const market = data[i];
            const id = this.safeString (market, 'symbol');
            const baseId = id.split ('_')[0];
            const quoteId = id.split ('_')[1];
            const base = this.safeCurrencyCode (baseId);
            const quote = this.safeCurrencyCode (quoteId);
            const symbol = base + '/' + quote;
            const precision = {
                'amount': undefined,
                'price': this.safeInteger (market, 'pricePrecision'),
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': undefined,
                        'max': undefined,
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': undefined,
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const timestamp = this.milliseconds ();
        const market = this.market (symbol);
        const request = this.extend ({
            'symbol': market['id'],
        }, params);
        const response = await this.publicGetQTickers (request);
        const ticker = this.safeValue (response, 'data');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker[0], 'high'),
            'low': this.safeFloat (ticker[0], 'low'),
            'bid': undefined,
            'bidVolume': undefined,
            'ask': undefined,
            'askVolume': undefined,
            'vwap': undefined,
            'previousClose': undefined,
            'open': this.safeFloat (ticker[0], 'open'),
            'close': this.safeFloat (ticker[0], 'close'),
            'last': this.safeFloat (ticker[0], 'close'),
            'percentage': undefined,
            'change': this.safeFloat (ticker[0], 'change'),
            'average': undefined,
            'baseVolume': this.safeFloat (ticker[0], 'volume'),
            'quoteVolume': this.safeFloat (ticker[0], 'quoteVolume'),
            'info': ticker[0],
        };
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': market['id'],
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.publicGetQDepth (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        return this.parseOrderBook (data, undefined, 'bid', 'ask');
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '5m', since = undefined, limit = undefined) {
        return [
            this.timeInSeconds (ohlcv[0]),
            this.safeFloat (ohlcv, 1),
            this.safeFloat (ohlcv, 2),
            this.safeFloat (ohlcv, 3),
            this.safeFloat (ohlcv, 4),
            this.safeFloat (ohlcv, 5),
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = 1, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': market['id'],
            'size': limit,
        };
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        if (since !== undefined) {
            request['since'] = parseInt (since / 1000);
        }
        const duration = this.parseTimeframe (timeframe);
        const timerange = limit * duration * 1000;
        if (since === undefined) {
            if (limit === undefined) {
                throw new ArgumentsRequired (this.id + ' fetchOHLCV requires a since argument or a limit argument');
            } else {
                request['to'] = this.milliseconds ();
                request['from'] = request['to'] - timerange;
            }
        } else {
            request['from'] = parseInt (since);
            request['to'] = this.sum (request['from'], timerange);
        }
        const response = await this.publicGetQKline (request);
        // {
        //     "symbol": "BTC_USDT",
        //     "volume": 12321.1234,
        //     "open": 4124.3,
        //     "close": 3873.213,
        //     "low": 3521.1,
        //     "high": 4521.5,
        //     "quoteVolume": 71031537.978665,
        //     "ts": 1529739295000
        // }
        const data = this.safeValue (response, 'data', []);
        return this.parseOHLCVs (data, undefined, timeframe, since, limit);
    }

    async fetchCurrencies (params = {}) {
        const response = await this.publicGetCommonCurrencys (params);
        const items = response['data'];
        const result = {};
        for (let i = 0; i < items.length; i++) {
            //    {
            //       "currency": "ETH",
            //       "maxWithdrawOneDay": 2000,
            //       "maxWithdrawSingle": 2000,
            //       "minWithdrawSingle": 0.1,
            //       "supportDeposit": true,
            //       "supportTrade": true,
            //       "supportWithdraw": true,
            //       "withdrawFee": 0.008
            //     },
            const item = items[i];
            const id = this.safeString (item, 'currency');
            const code = this.safeCurrencyCode (id);
            result[code] = {
                'id': id,
                'code': code,
                'name': this.safeString (item, 'currency'),
                'active': this.safeValue (item, 'supportTrade') && this.safeValue (item, 'supportDeposit'),
                'fee': this.safeFloat (item, 'withdrawFee'),
                'precision': undefined,
                'info': item,
                'limits': {
                    'amount': { 'min': undefined, 'max': undefined },
                    'price': { 'min': undefined, 'max': undefined },
                    'cost': { 'min': undefined, 'max': undefined },
                    'withdraw': { 'min': this.safeFloat (item, 'minWithdrawSingle'), 'max': this.safeFloat (item, 'maxWithdrawSingle') },
                },
            };
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const query = this.omit (params, 'type');
        const response = await this.privateGetAccountBalance (query);
        const balances = this.safeValue (response, 'data');
        const wallets = this.safeValue (balances, 'WALLET');
        const result = { 'info': wallets };
        for (let i = 0; i < wallets.length; i++) {
            const wallet = wallets[i];
            const currencyId = wallet['currency'];
            const code = this.safeCurrencyCode (currencyId);
            const account = this.account ();
            account['free'] = this.safeFloat (wallet, 'available');
            account['total'] = this.safeFloat (wallet, 'total');
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const method = 'privatePostOrderCreate';
        const direction = side === 'buy' ? 'BID' : 'ASK';
        const request = {
            'volume': amount,
            'direction': direction,
            'symbol': symbol,
            'price': price,
            'type': type,
        };
        const response = await this[method] (this.extend (request, params));
        return {
            'id': this.safeValue (response, 'data'),
            'info': response,
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'orderId': id,
        };
        return await this.privatePostOrderCancel (this.extend (request, params));
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' fetchOrders requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': this.safeString (market, 'id'),
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.privateGetOrderOpenOrders (this.extend (request, params));
        const result = this.safeValue (response, 'data');
        return this.parseOrders (this.safeValue (result, 'data'), market, since, limit);
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        const request = {
            'orderId': id,
        };
        const response = await this.privateGetOrderOpenOrderDetail (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        if (!data) {
            throw new OrderNotFound (this.id + ' order ' + id + ' not found');
        }
        return this.parseOrder (data);
    }

    parseTrade (trade, market = undefined) {
        const timestamp = this.safeTimestamp (trade, 'createdTime');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        const id = this.safeString (trade, 'id');
        const price = this.safeFloat (trade, 'price');
        const amount = this.safeFloat (trade, 'totalVolume');
        let cost = undefined;
        if (amount !== undefined) {
            if (price !== undefined) {
                cost = price * amount;
            }
        }
        const type = undefined;
        const side = this.safeString (trade, 'type');
        return {
            'info': trade,
            'id': id,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': type,
            'side': side,
            'takerOrMaker': undefined,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {};
        if (symbol !== undefined) {
            const market = this.market (symbol);
            request['symbol'] = market['id'];
        }
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        const trades = await this.privateGetOrderHistoryOrders (this.extend (request, params));
        return this.parseTrades (trades, undefined, since, limit);
    }

    parseOrder (order, market = undefined) {
        const marketName = this.safeString (order, 'pair');
        market = market || this.findMarket (marketName);
        let timestamp = this.safeString (order, 'createdTime');
        if (timestamp !== undefined) {
            timestamp = Math.round (parseFloat (timestamp) * 1000);
        }
        const direction = this.safeValue (order, 'direction');
        const side = direction === 'BID' ? 'BUY' : 'SELL';
        const amount = this.safeFloat (order, 'totalAmount');
        const fillAmount = this.safeFloat (order, 'dealAmount', amount);
        const remaining = amount - fillAmount;
        return {
            'id': this.safeString (order, 'id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'lastTradeTimestamp': undefined,
            'status': undefined,
            'symbol': this.safeString (market, 'symbol'),
            'side': side,
            'type': this.safeString (order, 'orderType'),
            'price': this.safeFloat (order, 'price'),
            'cost': undefined,
            'amount': amount,
            'filled': fillAmount,
            'remaining': remaining,
            'fee': undefined,
            'info': order,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (method === 'GET') {
            if (Object.keys (query).length) {
                url += '?' + this.urlencode (query);
            }
        }
        if (api === 'private') {
            this.checkRequiredCredentials ();
            query = this.urlencode (query);
            if (method === 'POST') {
                body = query;
            }
            const queryArray = query.split ('&');
            const sortedQuery = this.sortBy (queryArray, 0).join ('&');
            const secret = this.encode (this.secret);
            const signature = this.hmac (sortedQuery, secret, 'sha256');
            headers = {
                'Cache-Control': 'no-cache',
                'Content-type': 'application/x-www-form-urlencoded',
                'X_ACCESS_KEY': this.apiKey,
                'X_SIGNATURE': signature,
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
        const httpCode = this.safeInteger (response, 'code', 200);
        if (response === undefined) {
            return;
        }
        if (code >= 400) {
            throw new ExchangeError (this.id + ' HTTP Error ' + code + ' reason: ' + reason);
        }
        if (httpCode >= 400) {
            const message = this.safeValue (response, 'msg', '');
            throw new ExchangeError (this.id + ' HTTP Error ' + httpCode + ' message: ' + message);
        }
    }
};
<|endoftext|>


<commit_before>var global = (typeof window !== 'undefined' && window != null) ? window : global;
var jQuery = global.jQuery;
jQuery = jQuery || require('jquery-browserify');
var $ = jQuery;
var _ = require('underscore');
var Backbone = require('backbone');
Backbone.$ = $;
var File = require('./Backbone.File.Sync').File;
// There can be only one!!!
var AudioContext = (global.AudioContext || global.webkitAudioContext);
var audioContext = new AudioContext();
var analyser = audioContext.createAnalyser();

var AudioSource = Backbone.View.extend({
  audioContext: null,
  analyzer: null,
  render: function(){
    if(this.audioContext === null){
      // create the audio context
      this.audioContext = audioContext;
    }
    if(this.analyzer === null) {
      this.analyzer = analyser;
      this.analyzer.smoothingTimeConstant = 0.8;
      this.analyzer.fftSize = 512;
    }
    this.source = this.audioContext.createBufferSource();

    this.$el.html('<audio id="audio-source"></audio>');
    return this;
  },
  source: null
});

module.exports = AudioSource;
<commit_msg>Implements ability to play a file in AudioSource.<commit_after>var global = (typeof window !== 'undefined' && window != null) ? window : global;
var jQuery = global.jQuery;
jQuery = jQuery || require('jquery-browserify');
var $ = jQuery;
var _ = require('underscore');
var Backbone = require('backbone');
Backbone.$ = $;
var File = require('./Backbone.File.Sync').File;
// There can be only one!!!
var AudioContext = (global.AudioContext || global.webkitAudioContext);
var audioContext = new AudioContext();
var analyser = audioContext.createAnalyser();
//todo -- add a file from the MusicFiles. This could get really interesting.
var AudioSource = Backbone.View.extend({
  audioContext: null,
  analyzer: null,
  render: function(){
    if(this.audioContext === null){
      // create the audio context
      this.audioContext = audioContext;
    }
    if(this.analyzer === null) {
      this.analyzer = analyser;
      this.analyzer.smoothingTimeConstant = 0.8;
      this.analyzer.fftSize = 512;
    }
    this.source = this.audioContext.createBufferSource();
    this.source.connect(this.analyzer);
    this.source.connect(this.audioContext.destination);
    this.source.noteOn(0);
    this.trigger('audiosource:play', this.analyzer);
    this.playing = true;
    this.$el.html('<audio id="audio-source"></audio>');
    return this;
  },
  play: function(){
    this.render();
  },
  stop: function(){
    if(this.source && this.playing){
      this.trigger('audiosource:stop', this.analyzer);
      this.source.noteOff(0);
      this.source.disconnect();
    }
    return this;
  },
  source: null
});

module.exports = AudioSource;
<|endoftext|>


<commit_before>
    // Replace this line with the one on your Quickstart Guide Page
    Parse.initialize("nQkZtiTz13AY5YBulsOWNdmupWpl1JLrnykc4dYW", "jRGFMGaqXwvo1rHBxRAQARDVgJTDU0RCkd2u7XtS");

   var Blog = Parse.Object.extend("Blog");
   var Blogs = Parse. Object.extend("Blogs");

var blogs = new Blogs();
blogs.fetch({
    success: function(blogs) {
        console.log(blogs);
    },
    error: function(blogs, error) {
        console.log(error);
    }
});

<commit_msg>Update blog.js<commit_after>
    // Replace this line with the one on your Quickstart Guide Page
    Parse.initialize("nQkZtiTz13AY5YBulsOWNdmupWpl1JLrnykc4dYW", "jRGFMGaqXwvo1rHBxRAQARDVgJTDU0RCkd2u7XtS");

   var Blog = Parse.Object.extend("Blog");
   var Blogs = Parse.Object.extend({
       model: "Blog"});

var blogs = new Blogs();
blogs.fetch({
    success: function(blogs) {
        console.log(blogs);
    },
    error: function(blogs, error) {
        console.log(error);
    }
});

<|endoftext|>


<commit_before>// Set up global variables
var results = [];

var calculator = {
  "entry": "0",
  "entries": [],
  "total": 0,
  "history": "0",
  "realHistory": "0",
  "lastOperand": "",
  "operations" : {
    "+" : function(a,b) {
      return a + b;
    },
    "-" : function(a,b) {
      return a - b;
    },
    "x" : function(a,b) {
      return a * b;
    },
    "÷" : function (a,b) {
      return a / b;
    },
    "=" : function() {
      return true;
    }
  },
  "updateView" : function(){
    $(".result").html(calculator.total);
    $(".history").html(calculator.history);
  }
};

// Start the engines
$(document).ready(function() {
  $(".clear").on("click", function(){
    calculator.entry = "0";
    calculator.total = 0;
    calculator.history = "";
    calculator.lastOperand = "";
    calculator.updateView();
  });
  $("button").on("click", function(){
    var op = $(this).val();
    console.log($(this).val());
    if (calculator.operations.hasOwnProperty(op)) {
      calculator.entries.push(calculator.entry);
      if (calculator.entries.length === 1) {
        calculator.total = parseFloat(calculator.entry);
      }
      else {
        calculator.total = calculator.operations[calculator.lastOperand](parseFloat(calculator.entries[0].toPrecision(3)), parseFloat(calculator.entries[1].toPrecision(3)));
      }
      calculator.entry = "0";
      calculator.lastOperand = op;
      calculator.realHistory = calculator.history;
    }
    else if (op === "ce") {
      calculator.entry = "0";
      calculator.history = calculator.realHistory;
      op = "";
    }
    else if (op === "c") {
      calculator.entry = "0";
      calculator.total = 0;
      calculator.history = "0";
      calculator.realHistory = "0";
      calculator.lastOperand = "";
    }
    else {
      calculator.entry += op;
    }
    if (["ce", "c", "="].indexOf(op) === -1) calculator.history += op;
    calculator.updateView();
  });
});

<commit_msg>moves clearing operations to calculator obj<commit_after>// Set up global variables
var results = [];

var calculator = {
  "entry": "0",
  "entries": [],
  "total": 0,
  "history": "0",
  "realHistory": "0",
  "lastOperand": "",
  "operations" : {
    "+" : function(a,b) {
      return a + b;
    },
    "-" : function(a,b) {
      return a - b;
    },
    "x" : function(a,b) {
      return a * b;
    },
    "÷" : function (a,b) {
      return a / b;
    },
    "=" : function() {
      return true;
    }
  },
  "updateView" : function(){
    $(".result").html(calculator.total);
    $(".history").html(calculator.history);
  },
  "clearEntry" : function() {
    calculator.entry = "0";
    calculator.history = calculator.realHistory;
    op = "";
  },
  "reset" : function(){
    calculator.entry = "0";
    calculator.total = 0;
    calculator.history = "0";
    calculator.realHistory = "0";
    calculator.lastOperand = "";
  }
};

// Start the engines
$(document).ready(function() {
  $("button").on("click", function(){
    var op = $(this).val();
    console.log($(this).val());
    if (calculator.operations.hasOwnProperty(op)) {
      calculator.entries.push(calculator.entry);
      if (calculator.entries.length === 1) {
        calculator.total = parseFloat(calculator.entry);
      }
      else {
        calculator.total = calculator.operations[calculator.lastOperand](parseFloat(calculator.entries[0].toPrecision(3)), parseFloat(calculator.entries[1].toPrecision(3)));
      }
      calculator.entry = "0";
      calculator.lastOperand = op;
      calculator.realHistory = calculator.history;
    }
    else if (op === "ce") {
      calculator.clearEntry();
    }
    else if (op === "c") {
      calculator.reset();
    }
    else {
      calculator.entry += op;
    }
    if (["ce", "c", "="].indexOf(op) === -1) calculator.history += op;
    calculator.updateView();
  });
});

<|endoftext|>


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

});
<commit_msg>Update code.js<commit_after>$(document).ready(function(){
  $('#Add').on('click',Addrow);

});

function Addrow(){
  var number = ($('tbody tr').length)+1;
  var tr = '
'+
              ''+number+'	'+
              '<input type="text" placeholder="Student Name" class="form-control name">	'+
              '<input type="number" placeholder="Score" class="form-control score">	'+
              '<input type="number" placeholder="Forgiveness" class="form-control score">	'+
              '	'+
              '	'+
              '<input type="button" class="btn btn-primary btn-sm remove" value="Remove">	'+
            '
'
  $('tbody').append(tr);
}
<|endoftext|>


<commit_before>// Globals
var jsonFilename,
    jsonData,
    allPlotData,
    columnNames;

var svg;

function initialize() {
}

function loadJSON(jsonFilename) {
    /*
        Initialize the D3PO figure given a JSON specification.

        Parameters
        ----------
        jsonFilename : string
            The relative path to a D3PO JSON spec file.
    */
    d3.json(jsonFilename, function(error, _tmp) {
        if (error) {
            console.warn(error);
            alert('Unable to find file "' + jsonFilename + '"');
        }
        jsonData = _tmp;

        // TODO: figure out type of file, use appropriate reader
        d3.csv(jsonData["filename"], function(error, _tmp) {
            if (error) {
                console.warn(error);
                alert('Unable to read/parse file "' + jsonData["filename"] + '"');
            }
            allPlotData = _tmp;
            columnNames = d3.keys(allPlotData[0]);

            // draw the first state
            drawState(jsonData['states'][0]);

            var presets = d3.select("#controls .navigation").selectAll("li")
                            .data(jsonData['states']);

            presets.enter().append("li")
                   .on("click", function(e,i) {
                        drawState(jsonData['states'][i]);
                        $(".navigation li").removeClass("selected");
                        $(this).addClass("selected");
                   });

            presets.text(function(d, i){ return d['name']; });
            presets.exit().remove();

            $(".navigation li:first-of-type").addClass("selected");
        });
    });

    //
}

function domains(data, columns) {
    /*
        Get the domains (min, max) for each column in the plot data.
    */

    // Define an object to contain the domains (in data space) for each column
    var domainByDataColumn = {};

    columnNames.forEach(function(colName) {
        var domain = d3.extent(data, function(d) { return parseFloat(d[colName]); });

        // if parseFloat failed, probably string values in the column
        if (isNaN(domain[0]) || isNaN(domain[1])){
            var this_col = [];
            data.map(function(d) {
                this_col.push(d[colName]);
            });

            domainByDataColumn[colName] = this_col.unique();
        } else {
            var size = domain[1]-domain[0];
            domainByDataColumn[colName] = [domain[0] - size/25.,
                                           domain[1] + size/25.];
        }
    });

    return domainByDataColumn;
}

function isSelected (selection, d) {
    // If selection is not empty
    if (!($.isEmptyObject(selection))) {
        var xr = selection['xRange'],
            yr = selection['yRange'];
        var e = [[xr[0],yr[0]],
                 [xr[1],yr[1]]];

        var xCol = selection['xAxis'],
            yCol = selection['yAxis'];

        if (e[0][0] > d[xCol] || d[xCol] > e[1][0] || e[0][1] > d[yCol] || d[yCol] > e[1][1]) {
            return false;
        } else {
            return true;
        };

    } else { // selection is empty, all points are selected
        return true;
    }
}

function drawState(state) {
/*
    TODO
*/
    var nRows = state['grid']['nRows'],
        nCols = state['grid']['nColumns'],
        figSpec = state['figure'] || dFigureSpec;

    var figPadding = figSpec["figurePadding"],
        plotSpacing = figSpec["plotSpacing"],
        plotSize = figSpec["plotSize"];

    // Compute the height / width of the svg element based on the plot size,
    // plot spacing, and figure padding.
    var svg_height = nRows*(plotSize['height'] + plotSpacing['vertical']) +
                     figPadding['top'] + figPadding['bottom'],
        svg_width = nCols*(plotSize['width'] + plotSpacing['horizontal']) + plotSpacing['horizontal']
                     figPadding['left'] + figPadding['right'];

    // Define top level svg tag
    svg = d3.select("#svg svg");
    svg.transition()
       .duration(500)
       .ease('quad-out')
       .attr("width", svg_width)
       .attr("height", svg_height)
       .each("end", function () {
            $("body").toggleClass("hack");
            setTimeout(function (){ $("body").toggleClass("hack"); });
        });

    svg.append("g")
       .attr("transform", "translate(" + figPadding["left"] + "," + figPadding["top"] + ")");

    // Scalers for x / y axes from data space to pixel space
    // TODO: build in log support here - if statement? need to keep track of what
    //       axes are log, which are linear, etc.
    var xScaler = d3.scale.linear()
                    .range([plotSpacing['horizontal']/2,
                            plotSize['width'] + plotSpacing['horizontal']/2]),
        yScaler = d3.scale.linear()
                    .range([plotSize['height'] + plotSpacing['vertical']/2,
                            plotSpacing['vertical']/2]),
        cScaler = d3.scale.linear();

    // Functions to compute the amount to translate the individual plots by
    xPlotTranslator = function (plot) {
        index = plot["gridPosition"][1];
        return index*(plotSize['width'] + plotSpacing['horizontal']) + plotSpacing['horizontal']/2.;
    }
    yPlotTranslator = function (plot) {
        index = plot["gridPosition"][0];
        return (nRows - index - 1)*(plotSize['height'] + plotSpacing['vertical']);
    }

    // Get the domains in data units for each column in the data file
    var columnDomains = domains(allPlotData, columnNames);

    // if this plot has a color-by axis, set the domain and range of the color scaler
    if (typeof state['colorAxis'] != 'undefined') {
        cScaler.domain(columnDomains[state['colorAxis']]);
        cScaler.range(state['colorMap'] || dColorMap);
    }

    // set up the selection object if some points are highlighted
    var selection = {};
    for (var ii=0; ii < state['plots'].length; ii++) {
        var p = state['plots'][ii];
        if (typeof p['selection'] != 'undefined') {
            selection['xAxis'] = p['xAxis'],
            selection['yAxis'] = p['yAxis'],
            selection['xRange'] = p['selection']['xRange'],
            selection['yRange'] = p['selection']['yRange'];
        }
    }

    // Set up a cell group for each plot window, to then draw points and rectangle over
    var cells = d3.select("svg").selectAll("g.cell").data(state["plots"]);
    cells.enter().append("g")
         .attr("class", "cell");
    cells.exit().remove();
    cells.transition().duration(500).ease('quad-out')
         .attr("transform", function(p) { return "translate(" + xPlotTranslator(p) + ","
                                                              + yPlotTranslator(p) + ")"; })
         .each(plot);

    // Define the brush object
    var brush = d3.svg.brush()
                  .x(xScaler).y(yScaler)
                  .on("brushstart", brushstart)
                  .on("brush", brushmove)
                  .on("brushend", brushend);

    // have the cells call the brush
    cells.call(brush);

    // Add axes to the plots
    // TODO: figure out how to give user better control over ticks?
    var xAxisD3 = d3.svg.axis()
                .scale(xScaler)
                .orient("bottom")
                .ticks(5)
                .tickSize(dTickSize);

    var yAxisD3 = d3.svg.axis()
                .scale(yScaler)
                .orient("left")
                .ticks(5)
                .tickSize(dTickSize);

    // Draw / update axes
    var xAxis = d3.select("svg").selectAll(".x.axis")
                  .data(state["plots"]);
    xAxis.enter().append("g")
         .attr("class", "x axis");
    xAxis.exit().remove();
    xAxis.transition().duration(500).ease('quad-out')
         .attr("transform", function(p, i) {
            return "translate(" + xPlotTranslator(p) + ","
                                + (yPlotTranslator(p) + plotSize['height'] + 15) + ")";
        }).each(function(p) {
            xScaler.domain(columnDomains[p['xAxis']]);
            d3.select(this).call(xAxisD3);
        });

    var yAxis = d3.select("svg").selectAll(".y.axis")
                  .data(state["plots"]);
    yAxis.enter().append("g")
         .attr("class", "y axis");
    yAxis.exit().remove();
    yAxis.transition().duration(500).ease('quad-out')
         .attr("transform", function(p, i) {
            return "translate(" + (xPlotTranslator(p) + plotSpacing['horizontal']/2 + 10) + ","
                                + yPlotTranslator(p) + ")";
        }).each(function(p) {
            yScaler.domain(columnDomains[p['yAxis']]);
            d3.select(this).call(yAxisD3);
        });

    // Add axis labels
    var xLabel = svg.selectAll(".x-label")
                    .data(state["plots"]);
    xLabel.enter().append("text")
          .attr("class", "axis-label x-label");
    xLabel.exit().remove();
    xLabel.text(function(p, i) { return p['xAxis']; });
    xLabel.attr("x", function(p) { return xPlotTranslator(p) + plotSpacing['horizontal']/2 + plotSize['width']/2. - $(this).width()/2.; })
          .attr("y", function(p) { return yPlotTranslator(p) + plotSpacing['vertical']/2 + plotSize['height'] + 50; });

    var yLabel = svg.selectAll(".y-label")
                    .data(state["plots"]);
    yLabel.enter().append("text")
          .attr("class", "axis-label y-label");
    yLabel.exit().remove();
    yLabel.text(function(p,i) { return p['yAxis']; });
    yLabel.attr("x", function(p) { return -((plotSpacing['vertical']/2-yPlotTranslator(p)) + plotSize['height']/2. + $(this).width()/2.); }) // deliberately backwards cause rotated
          .attr("y", function(p) { return xPlotTranslator(p); });

    var brushCell;
    // Clear the previously-active brush, if any.
    function brushstart(p) {
        if (brushCell !== this) {
            d3.select(brushCell).call(brush.clear());
            xScaler.domain(columnDomains[p['xAxis']]);
            yScaler.domain(columnDomains[p['yAxis']]);
            brushCell = this;
        }
    }

    // Highlight the selected circles.
    function brushmove(p) {
        var e = brush.extent(),
            xCol = p['xAxis'],
            yCol = p['yAxis'];

        svg.selectAll("circle")
           .style("fill", function (d) { return cScaler(d[state['colorAxis']]) || dMarkerFill; })
           .attr("opacity", function (d) { return dMarkerOpacity; })
           .classed("hidden", function(d) {
              return e[0][0] > d[xCol] || d[xCol] > e[1][0]
                      || e[0][1] > d[yCol] || d[yCol] > e[1][1];
        });
    }

    // If the brush is empty, select all circles.
    function brushend() {
        if (brush.empty()) svg.selectAll("circle").classed("hidden", false);
    }

    // TODO: wtf
    function plot(p) {
        var cell = d3.select(this);

        xScaler.domain(columnDomains[p['xAxis']]);
        yScaler.domain(columnDomains[p['yAxis']]);

        var marker = p['marker'];

        if (typeof marker != 'undefined') {
            opacity = marker['opacity'] || dMarkerOpacity;
            size = marker['size'] || dMarkerSize;
            fill = marker['fill'] || dMarkerFill;
        } else {
            opacity = dMarkerOpacity;
            size = dMarkerSize;
            fill = dMarkerFill;
        }

        var rect = cell.selectAll("rect.frame").data([1]);
        rect.enter().append("rect");
        rect.exit().remove();
        rect.transition().duration(500).ease("quad-out")
            .attr("class", "frame")
            .attr("x", plotSpacing['horizontal'] / 2)
            .attr("y", plotSpacing['vertical'] / 2)
            .attr("width", plotSize['width'])
            .attr("height", plotSize['height']);

        var circ = cell.selectAll("circle").data(allPlotData)
        circ.enter().append("circle");
        circ.exit().remove();
        circ.transition().duration(500).ease("quad-out")
            .attr("cx", function(d) { return xScaler(d[p['xAxis']]); })
            .attr("cy", function(d) { return yScaler(d[p['yAxis']]); })
            .attr("r", size)
            .style("fill", function (d) {
                if (isSelected(selection, d)) {
                    return cScaler(d[state['colorAxis']]) || fill;
                } else {
                    return "#cccccc";
                }
            })
            .attr("opacity", function (d) {
                if (isSelected(selection, d)) {
                    return opacity;
                } else {
                    return 0.5;
                }
            });
    }

    // Finally, update caption
    var caption = d3.select("#caption")
                    .style('opacity', 0)
                    .text(state.caption || "")
                    .transition()
                    .duration(500)
                    .style('opacity', 1);
}<commit_msg>Add selection on attribute<commit_after>// Globals
var jsonFilename,
    jsonData,
    allPlotData,
    columnNames,
    selectionDispatch = {};

var svg;

function initialize() {
}

function loadJSON(jsonFilename) {
    /*
        Initialize the D3PO figure given a JSON specification.

        Parameters
        ----------
        jsonFilename : string
            The relative path to a D3PO JSON spec file.
    */
    d3.json(jsonFilename, function(error, _tmp) {
        if (error) {
            console.warn(error);
            alert('Unable to find file "' + jsonFilename + '"');
        }
        jsonData = _tmp;

        // TODO: figure out type of file, use appropriate reader
        d3.csv(jsonData["filename"], function(error, _tmp) {
            if (error) {
                console.warn(error);
                alert('Unable to read/parse file "' + jsonData["filename"] + '"');
            }
            allPlotData = _tmp;
            columnNames = d3.keys(allPlotData[0]);

            // draw the first state
            drawState(jsonData['states'][0]);

            var presets = d3.select("#controls .navigation").selectAll("li")
                            .data(jsonData['states']);

            presets.enter().append("li")
                   .on("click", function(e,i) {
                        drawState(jsonData['states'][i]);
                        $(".navigation li").removeClass("selected");
                        $(this).addClass("selected");
                   });

            presets.text(function(d, i){ return d['name']; });
            presets.exit().remove();

            $(".navigation li:first-of-type").addClass("selected");
        });
    });

    //
}

function domains(data, columns) {
    /*
        Get the domains (min, max) for each column in the plot data.
    */

    // Define an object to contain the domains (in data space) for each column
    var domainByDataColumn = {};

    columnNames.forEach(function(colName) {
        var domain = d3.extent(data, function(d) { return parseFloat(d[colName]); });

        // if parseFloat failed, probably string values in the column
        if (isNaN(domain[0]) || isNaN(domain[1])){
            var this_col = [];
            data.map(function(d) {
                this_col.push(d[colName]);
            });

            domainByDataColumn[colName] = this_col.unique();
        } else {
            var size = domain[1]-domain[0];
            domainByDataColumn[colName] = [domain[0] - size/25.,
                                           domain[1] + size/25.];
        }
    });

    return domainByDataColumn;
}

function isSelectedBox(selection, d) {
    // test for a selection based on a box
    var xr = selection['xRange'],
        yr = selection['yRange'];
    var e = [
        [xr[0], yr[0]],
        [xr[1], yr[1]]
    ];

    var xCol = selection['xAxis'],
        yCol = selection['yAxis'];

    if (e[0][0] > d[xCol] || d[xCol] > e[1][0] || e[0][1] > d[yCol] || d[yCol] > e[1][1]) {
        return false;
    } else {
        return true;
    }
}

selectionDispatch['box'] = isSelectedBox;

function isSelectedAttribute(selection, d) {
    // test for selection based on the value of a binary-valued column in the data
    var att = selection['attribute'];
    return d[att] > 0;
}
selectionDispatch['attribute'] = isSelectedAttribute;

function isSelected(selection, d) {
    if ($.isEmptyObject(selection)) {
        return true;
    } // empty selection defaults to select all

    // determine what kind of selection to perform
    var selectionType = selection['type'] || 'box';
    return selectionDispatch[selectionType](selection, d);
}

function drawState(state) {
/*
    TODO
*/
    var nRows = state['grid']['nRows'],
        nCols = state['grid']['nColumns'],
        figSpec = state['figure'] || dFigureSpec;

    var figPadding = figSpec["figurePadding"],
        plotSpacing = figSpec["plotSpacing"],
        plotSize = figSpec["plotSize"];

    // Compute the height / width of the svg element based on the plot size,
    // plot spacing, and figure padding.
    var svg_height = nRows*(plotSize['height'] + plotSpacing['vertical']) +
                     figPadding['top'] + figPadding['bottom'],
        svg_width = nCols*(plotSize['width'] + plotSpacing['horizontal']) + plotSpacing['horizontal']
                     figPadding['left'] + figPadding['right'];

    // Define top level svg tag
    svg = d3.select("#svg svg");
    svg.transition()
       .duration(500)
       .ease('quad-out')
       .attr("width", svg_width)
       .attr("height", svg_height)
       .each("end", function () {
            $("body").toggleClass("hack");
            setTimeout(function (){ $("body").toggleClass("hack"); });
        });

    svg.append("g")
       .attr("transform", "translate(" + figPadding["left"] + "," + figPadding["top"] + ")");

    // Scalers for x / y axes from data space to pixel space
    // TODO: build in log support here - if statement? need to keep track of what
    //       axes are log, which are linear, etc.
    var xScaler = d3.scale.linear()
                    .range([plotSpacing['horizontal']/2,
                            plotSize['width'] + plotSpacing['horizontal']/2]),
        yScaler = d3.scale.linear()
                    .range([plotSize['height'] + plotSpacing['vertical']/2,
                            plotSpacing['vertical']/2]),
        cScaler = d3.scale.linear();

    // Functions to compute the amount to translate the individual plots by
    xPlotTranslator = function (plot) {
        index = plot["gridPosition"][1];
        return index*(plotSize['width'] + plotSpacing['horizontal']) + plotSpacing['horizontal']/2.;
    }
    yPlotTranslator = function (plot) {
        index = plot["gridPosition"][0];
        return (nRows - index - 1)*(plotSize['height'] + plotSpacing['vertical']);
    }

    // Get the domains in data units for each column in the data file
    var columnDomains = domains(allPlotData, columnNames);

    // if this plot has a color-by axis, set the domain and range of the color scaler
    if (typeof state['colorAxis'] != 'undefined') {
        cScaler.domain(columnDomains[state['colorAxis']]);
        cScaler.range(state['colorMap'] || dColorMap);
    }

    // set up the selection object if some points are highlighted
    var selection = {};
    for (var ii=0; ii < state['plots'].length; ii++) {
        var p = state['plots'][ii];
        if (typeof p['selection'] != 'undefined') {
            selection['xAxis'] = p['xAxis'];
            selection['yAxis'] = p['yAxis'];
            for (var item in p['selection'])
                selection[item] = p['selection'][item];
        }
    }

    // Set up a cell group for each plot window, to then draw points and rectangle over
    var cells = d3.select("svg").selectAll("g.cell").data(state["plots"]);
    cells.enter().append("g")
         .attr("class", "cell");
    cells.exit().remove();
    cells.transition().duration(500).ease('quad-out')
         .attr("transform", function(p) { return "translate(" + xPlotTranslator(p) + ","
                                                              + yPlotTranslator(p) + ")"; })
         .each(plot);

    // Define the brush object
    var brush = d3.svg.brush()
                  .x(xScaler).y(yScaler)
                  .on("brushstart", brushstart)
                  .on("brush", brushmove)
                  .on("brushend", brushend);

    // have the cells call the brush
    cells.call(brush);

    // Add axes to the plots
    // TODO: figure out how to give user better control over ticks?
    var xAxisD3 = d3.svg.axis()
                .scale(xScaler)
                .orient("bottom")
                .ticks(5)
                .tickSize(dTickSize);

    var yAxisD3 = d3.svg.axis()
                .scale(yScaler)
                .orient("left")
                .ticks(5)
                .tickSize(dTickSize);

    // Draw / update axes
    var xAxis = d3.select("svg").selectAll(".x.axis")
                  .data(state["plots"]);
    xAxis.enter().append("g")
         .attr("class", "x axis");
    xAxis.exit().remove();
    xAxis.transition().duration(500).ease('quad-out')
         .attr("transform", function(p, i) {
            return "translate(" + xPlotTranslator(p) + ","
                                + (yPlotTranslator(p) + plotSize['height'] + 15) + ")";
        }).each(function(p) {
            xScaler.domain(columnDomains[p['xAxis']]);
            d3.select(this).call(xAxisD3);
        });

    var yAxis = d3.select("svg").selectAll(".y.axis")
                  .data(state["plots"]);
    yAxis.enter().append("g")
         .attr("class", "y axis");
    yAxis.exit().remove();
    yAxis.transition().duration(500).ease('quad-out')
         .attr("transform", function(p, i) {
            return "translate(" + (xPlotTranslator(p) + plotSpacing['horizontal']/2 + 10) + ","
                                + yPlotTranslator(p) + ")";
        }).each(function(p) {
            yScaler.domain(columnDomains[p['yAxis']]);
            d3.select(this).call(yAxisD3);
        });

    // Add axis labels
    var xLabel = svg.selectAll(".x-label")
                    .data(state["plots"]);
    xLabel.enter().append("text")
          .attr("class", "axis-label x-label");
    xLabel.exit().remove();
    xLabel.text(function(p, i) { return p['xAxis']; });
    xLabel.attr("x", function(p) { return xPlotTranslator(p) + plotSpacing['horizontal']/2 + plotSize['width']/2. - $(this).width()/2.; })
          .attr("y", function(p) { return yPlotTranslator(p) + plotSpacing['vertical']/2 + plotSize['height'] + 50; });

    var yLabel = svg.selectAll(".y-label")
                    .data(state["plots"]);
    yLabel.enter().append("text")
          .attr("class", "axis-label y-label");
    yLabel.exit().remove();
    yLabel.text(function(p,i) { return p['yAxis']; });
    yLabel.attr("x", function(p) { return -((plotSpacing['vertical']/2-yPlotTranslator(p)) + plotSize['height']/2. + $(this).width()/2.); }) // deliberately backwards cause rotated
          .attr("y", function(p) { return xPlotTranslator(p); });

    var brushCell;
    // Clear the previously-active brush, if any.
    function brushstart(p) {
        if (brushCell !== this) {
            d3.select(brushCell).call(brush.clear());
            xScaler.domain(columnDomains[p['xAxis']]);
            yScaler.domain(columnDomains[p['yAxis']]);
            brushCell = this;
        }
    }

    // Highlight the selected circles.
    function brushmove(p) {
        var e = brush.extent(),
            xCol = p['xAxis'],
            yCol = p['yAxis'];

        svg.selectAll("circle")
           .style("fill", function (d) { return cScaler(d[state['colorAxis']]) || dMarkerFill; })
           .attr("opacity", function (d) { return dMarkerOpacity; })
           .classed("hidden", function(d) {
              return e[0][0] > d[xCol] || d[xCol] > e[1][0]
                      || e[0][1] > d[yCol] || d[yCol] > e[1][1];
        });
    }

    // If the brush is empty, select all circles.
    function brushend() {
        if (brush.empty()) svg.selectAll("circle").classed("hidden", false);
    }

    // TODO: wtf
    function plot(p) {
        var cell = d3.select(this);

        xScaler.domain(columnDomains[p['xAxis']]);
        yScaler.domain(columnDomains[p['yAxis']]);

        var marker = p['marker'];

        if (typeof marker != 'undefined') {
            opacity = marker['opacity'] || dMarkerOpacity;
            size = marker['size'] || dMarkerSize;
            fill = marker['fill'] || dMarkerFill;
        } else {
            opacity = dMarkerOpacity;
            size = dMarkerSize;
            fill = dMarkerFill;
        }

        var rect = cell.selectAll("rect.frame").data([1]);
        rect.enter().append("rect");
        rect.exit().remove();
        rect.transition().duration(500).ease("quad-out")
            .attr("class", "frame")
            .attr("x", plotSpacing['horizontal'] / 2)
            .attr("y", plotSpacing['vertical'] / 2)
            .attr("width", plotSize['width'])
            .attr("height", plotSize['height']);

        var circ = cell.selectAll("circle").data(allPlotData)
        circ.enter().append("circle");
        circ.exit().remove();
        circ.transition().duration(500).ease("quad-out")
            .attr("cx", function(d) { return xScaler(d[p['xAxis']]); })
            .attr("cy", function(d) { return yScaler(d[p['yAxis']]); })
            .attr("r", size)
            .style("fill", function (d) {
                if (isSelected(selection, d)) {
                    return cScaler(d[state['colorAxis']]) || fill;
                } else {
                    return "#cccccc";
                }
            })
            .attr("opacity", function (d) {
                if (isSelected(selection, d)) {
                    return opacity;
                } else {
                    return 0.5;
                }
            });
    }

    // Finally, update caption
    var caption = d3.select("#caption")
                    .style('opacity', 0)
                    .text(state.caption || "")
                    .transition()
                    .duration(500)
                    .style('opacity', 1);
}<|endoftext|>


<commit_before>'use strict';

function div_color(){
    core_audio_start({
      'id': 'boop',
    });

    document.getElementById('box').style.background = '#' + core_random_hex();
}

function start(){
    running = true;
    start_time = core_date_to_timestamp();
    change_time = core_random_integer({
      'max': 9000,
    }) + 999;
    core_interval_modify({
      'clear': 'clearTimeout',
      'id': 'timer',
      'interval': change_time,
      'set': 'setTimeout',
      'todo': div_color,
    });

    document.getElementById('box').style.background = '#000';

    core_html_modify({
      'id': 'start-button',
      'properties': {
        'onclick': stop,
        'value': 'Stop Timer [ESC]',
      },
    });
}

function stop(){
    if(!running){
        return;
    }

    running = false;
    var final_time = -(change_time - (core_date_to_timestamp() - start_time));
    core_interval_pause_all();

    document.getElementById('result').innerHTML = final_time > 0
      ? '+' + final_time + 'ms'
      : 'Too soon :(';

    core_html_modify({
      'id': 'start-button',
      'properties': {
        'onclick': start,
        'value': 'Start Timer [H]',
      },
    });
}
<commit_msg>changed var to let<commit_after>'use strict';

function div_color(){
    core_audio_start({
      'id': 'boop',
    });

    document.getElementById('box').style.background = '#' + core_random_hex();
}

function start(){
    running = true;
    start_time = core_date_to_timestamp();
    change_time = core_random_integer({
      'max': 9000,
    }) + 999;
    core_interval_modify({
      'clear': 'clearTimeout',
      'id': 'timer',
      'interval': change_time,
      'set': 'setTimeout',
      'todo': div_color,
    });

    document.getElementById('box').style.background = '#000';

    core_html_modify({
      'id': 'start-button',
      'properties': {
        'onclick': stop,
        'value': 'Stop Timer [ESC]',
      },
    });
}

function stop(){
    if(!running){
        return;
    }

    running = false;
    let final_time = -(change_time - (core_date_to_timestamp() - start_time));
    core_interval_pause_all();

    document.getElementById('result').innerHTML = final_time > 0
      ? '+' + final_time + 'ms'
      : 'Too soon :(';

    core_html_modify({
      'id': 'start-button',
      'properties': {
        'onclick': start,
        'value': 'Start Timer [H]',
      },
    });
}
<|endoftext|>