text:
#include "../../public/error_code.h"
#include "../../public/message.h"
#include "../include/socket_wrapper.h"
#include "../include/utils.h"
#include "json_opt.h"
#include "global.h"
#include "tlv_define.h"
#include "dispatcher.h"
#include "connection.h"

Dispatcher::Dispatcher(string data_protocol)
: data_protocol_(data_protocol)
{

}

Dispatcher::~Dispatcher()
{

}

int32_t Dispatcher::HandleConnect(ConnectionInfo *conn_info)
{
    LOG_DEBUG(g_logger, "connect, client ip:port is %s:%u", conn_info->cip.c_str(), conn_info->cport);

    return 0;
}

int32_t Dispatcher::HandleTimeout(ConnectionInfo *conn_info)
{
    LOG_DEBUG(g_logger, "connect timeout, client ip:port is %s:%u", conn_info->cip.c_str(), conn_info->cport);
    HandleClose(conn_info);

    return 0;
}

int32_t Dispatcher::HandleClose(ConnectionInfo *conn_info)
{
    LOG_DEBUG(g_logger, "close connect, client ip:port is %s:%u", conn_info->cip.c_str(), conn_info->cport);

    return 0;
}

int32_t Dispatcher::HandleError(ConnectionInfo *conn_info)
{
    LOG_DEBUG(g_logger, "connect error, client ip:port is %s:%u", conn_info->cip.c_str(), conn_info->cport);
    HandleClose(conn_info);

    return 0;
}

/*
 * json dispatcher
 *
 * */
JsonDispatcher::JsonDispatcher()
: Dispatcher(DATA_PROTOCOL_JSON)
{

}

JsonDispatcher::~JsonDispatcher()
{

}

int32_t JsonDispatcher::HandleMsg(ConnectionInfo *conn_info, string &msg_info)
{
    LOG_DEBUG(g_logger, "handle json msg, client ip:port is %s:%u, msg is %s", conn_info->cip.c_str(), conn_info->cport, msg_info.c_str());

    int32_t ret;
    CJsonOpt json_opt;
    json_opt.setJsonString(msg_info);

    if (!json_opt.JsonParseCommon())
    {
        LOG_ERROR(g_logger, "json parse common error");
        return -ERROR_PARSE_MSG;
    }

    string method;
    ret = json_opt.GetMethod(method);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "json parse command error");
        return -ERROR_PARSE_METHOD;
    }

    if (method == METHOD_GET_VOICESERVER_ADDR)
    {
        ret = HandleGetVoiceServerAddr(conn_info, json_opt);
        if (ret != 0)
        {
            LOG_ERROR(g_logger, "error is %s", ret);
            return ret;
        }
    }
    else
    {
        LOG_ERROR(g_logger, "invalid json method, method is %s", method.c_str());
    }

    LOG_DEBUG(g_logger, "handle json msg end, client ip:port is %s:%u, msg is %s", conn_info->cip.c_str(), conn_info->cport, msg_info.c_str());

    return 0;
}

int32_t JsonDispatcher::HandleGetVoiceServerAddr(ConnectionInfo *conn_info, CJsonOpt &json_opt)
{
    int ret = 0;
    int server_port = 0;
    string client_ip;
    string dev_ip;
    string server_ip;
    string public_addr_str("public_addr");
    string default_public_addr("123.56.101.52");
    string tlv_listen_port_str("tlv_listen_port");
    int default_server_port = 15040;

    ret = json_opt.JsonParseGetVoiceServerAddr(client_ip, dev_ip);
    if (ret != 0)
    {
        goto out;
    }

    // get voice server addr
    server_ip = g_config->Read(public_addr_str, default_public_addr);
    server_port = g_config->Read(tlv_listen_port_str, default_server_port);

out:
    string resp_str = json_opt.JsonJoinGetVoiceServerAddrResp(ret, server_ip, server_port);
    string response_msg = utils::ReplaceString(resp_str, "\\r\\n", "\\\\r\\\\n");
    response_msg.append("\r\n");
    if (!SocketOperate::WriteSfd(conn_info->cfd, response_msg.c_str(), response_msg.length()))
    {
        LOG_ERROR(g_logger, "write reponse msg error, fd is %d, reponse msg is %s", conn_info->cfd, response_msg.c_str());
        ret = -ERROR_PUSH_MESSAGE;
    }

    return ret;
}

/*
 * tlv dispatcher
 *
 *
 * */
TlvDispatcher::TlvDispatcher()
: Dispatcher(DATA_PROTOCOL_TLV)
{

}

TlvDispatcher::~TlvDispatcher()
{

}

int32_t TlvDispatcher::HandleMsg(ConnectionInfo *conn_info, string &tlv_data)
{
    LOG_DEBUG(g_logger, "handle tlv msg, client ip:port is %s:%u", conn_info->cip.c_str(), conn_info->cport);

    int32_t ret;
    const char *msg_data = tlv_data.c_str();
    size_t msg_size = tlv_data.size();

    const char *parsing_ptr = msg_data;

    // 解析mid
    uint32_t mid_type = DecodeFixed32(parsing_ptr);
    uint32_t mid_len = DecodeFixed32(parsing_ptr + 4);
    uint32_t mid = DecodeFixed32(parsing_ptr + 8);
    if (mid_type != TYPE_MID || mid_len != 4)
    {
        LOG_ERROR(g_logger, "parse mid error");
        return -ERROR_TLV_PARSE_MID;
    }
    parsing_ptr = parsing_ptr + kMsgHeaderSize + mid_len;

    uint32_t cmd = DecodeFixed32(parsing_ptr);
    uint32_t len = DecodeFixed32(parsing_ptr + 4);

    if (msg_size != kMsgHeaderSize + mid_len + kMsgHeaderSize + len)
    {
        LOG_ERROR(g_logger, "parse cmd length error");
        return -ERROR_TLV_PARSE_CMD;
    }

    Slice cmd_value(parsing_ptr + kMsgHeaderSize, len);
    switch(cmd)
    {
        case TYPE_HEARTBEAT:
            ret = HandleHeartbeat(conn_info, mid, cmd_value);
            break;

        case TYPE_CLIENT_BUILD_VC:
            ret = HandleClientBuildVc(conn_info, mid, cmd_value);
            break;

        case TYPE_CLIENT_START_SEND:
            ret = HandleClientStartSend(conn_info, mid, cmd_value);
            break;

        case TYPE_PUSH_CLIENT_START_SEND:
            ret = HandleOnPushStartSend(conn_info, mid, cmd_value);
            break;

        case TYPE_CLIENT_SEND_VOICE_DATA:
            ret = HandleClientSendVoice(conn_info, mid, cmd_value);
            break;

        case TYPE_PUSH_CLIENT_VOICE_DATA:
            ret = HandleOnPushClientVoice(conn_info, mid, cmd_value);
            break;

        case TYPE_CLIENT_FREE_VC:
            ret = HandleClientFreeVc(conn_info, mid, cmd_value);
            break;

        case TYPE_DEV_BUILD_VC:
            ret = HandleDevBuildVc(conn_info, mid, cmd_value);
            break;

        case TYPE_DEV_FREE_VC:
            ret = HandleDevFreeVc(conn_info, mid, cmd_value);
            break;

        default:
            break;
    }

    if (ret == 0)
    {
        LOG_DEBUG(g_logger, "tlv HandleMsg ok");
    }
    else
    {
        LOG_DEBUG(g_logger, "tlv handle msg error, ret %d", ret);
    }

    return ret;
}

void TlvDispatcher::EncodeCommonTlv(string *resp_msg, uint32_t msg_len, uint32_t mid)
{
    PutFixed32(resp_msg, TYPE_LENGTH);
    PutFixed32(resp_msg, 4);
    PutFixed32(resp_msg, msg_len);

    PutFixed32(resp_msg, TYPE_MID);
    PutFixed32(resp_msg, 4);
    PutFixed32(resp_msg, mid);
}

void TlvDispatcher::EncodeRet(string *resp_msg, uint32_t on_cmd, int32_t ret)
{
    PutFixed32(resp_msg, on_cmd);
    PutFixed32(resp_msg, 4);
    PutFixed32(resp_msg, ret);
}

int32_t TlvDispatcher::SendMsg(int fd, string msg)
{
    if (!SocketOperate::WriteSfd(fd, msg.c_str(), msg.size()))
    {
        return -ERROR_TLV_SEND_MSG;
    }

    return 0;
}

int32_t TlvDispatcher::ForwardMsgToDev(int push_fd, uint32_t push_mid, string &push_msg, PushMsgContext *ct)
{
    int32_t ret = 0;

    LOG_DEBUG(g_logger, "forward msg to dev, mid is %u", push_mid);

    ret = SendMsg(push_fd, push_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send msg error, mid %u", push_mid);
        return ret;
    }

    double timeout = g_config->Read("tlv_push_msg_timeout", 5.0);
    push_msg_timer_queue_.AddEventAfter(timeout, push_mid, ct);

    LOG_DEBUG(g_logger, "forward msg to dev ok, mid is %u", push_mid);

    return 0;
}

void TlvDispatcher::PackHeartBeatRespMsg(uint32_t mid, int32_t ret, string &resp_msg)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize;

    EncodeCommonTlv(&resp_msg, msg_len, mid);
    EncodeRet(&resp_msg, TYPE_ON_HEARTBEAT, ret);
}

int32_t TlvDispatcher::HandleHeartbeat(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret = 0;
    uint32_t type;
    uint32_t len;

    LOG_DEBUG(g_logger, "handle heartbeat, mid %s", mid);

    const char *data = cmd_value.data();
    //size_t size = cmd_value.size();

    type = DecodeFixed32(data);

    if (type == TYPE_CLIENT_ID)
    {
        len = DecodeFixed32(data + 4);
        if (len > MAX_GUID_LEN)
        {
            LOG_ERROR(g_logger, "parse length of client id error, because length is bigger than %d", MAX_GUID_LEN);
            ret = -ERROR_TLV_PARSE_CLIENT_ID;
            goto SEND_RESPONSE;
        }

        string guid(data + kMsgHeaderSize, len);
        LOG_DEBUG(g_logger, "heartbeat of client, client guid %s", guid.c_str());
    }
    else if (type == TYPE_DEV_ID)
    {
        len = DecodeFixed32(data + 4);
        if (len > MAX_GUID_LEN)
        {
            LOG_ERROR(g_logger, "parse length of dev id error, because length is bigger than %d", MAX_GUID_LEN);
            ret = -ERROR_TLV_PARSE_DEV_ID;
            goto SEND_RESPONSE;
        }
        string guid(data + kMsgHeaderSize, len);
        LOG_DEBUG(g_logger, "heartbeat of dev, dev guid %s", guid.c_str());
    }

SEND_RESPONSE:
    string resp_msg;
    PackHeartBeatRespMsg(mid, ret, resp_msg);
    ret = SendMsg(conn_info->cfd, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send response msg of client build voice channle error, ret is %d, mid is %u", ret, mid);
        return -ERROR_TLV_SEND_MSG;
    }

    return 0;
}

void TlvDispatcher::PackClientBuildVcRespMsg(uint32_t mid, int32_t ret, string &resp_msg)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize + 4;

    EncodeCommonTlv(&resp_msg, msg_len, mid);
    EncodeRet(&resp_msg, TYPE_ON_CLIENT_BUILD_VC, ret);
}

int32_t TlvDispatcher::HandleClientBuildVc(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret;
    uint32_t type;
    uint32_t len;
    string client_id;
    string dev_id;
    ClientVcInfo client_vc_info;

    LOG_DEBUG(g_logger, "client build voice channel, and mid is %u", mid);

    //int size = cmd_value.size();
    const char *data = cmd_value.data();

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of client_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_CLIENT_ID;
        goto SEND_RESPONSE;
    }
    client_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of dev_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_DEV_ID;
        goto SEND_RESPONSE;
    }
    dev_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    conn_info->guid_type = GUID_CLIENT;
    conn_info->guid = client_id;

    LOG_DEBUG(g_logger, "mid is %u, client_id is %s, dev_id is %s", mid, client_id.c_str(), dev_id.c_str());

    client_vc_info.client_id = client_id;
    client_vc_info.client_fd = conn_info->cfd;
    client_vc_info.client_bev = conn_info->buffer_event;
    client_vc_info.dev_id = dev_id;
    ret = vc_manager_.ConnectByClient(client_id, client_vc_info);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "connect by client error, ret is %d", ret);
        goto SEND_RESPONSE;
    }

    LOG_DEBUG(g_logger, "client build voice channel ok, and mid is %u, client id is %s, dev id is %s",
                        mid, client_id.c_str(), dev_id.c_str());

SEND_RESPONSE:
    string resp_msg;
    PackClientBuildVcRespMsg(mid, ret, resp_msg);
    ret = SendMsg(conn_info->cfd, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send response msg of client build voice channle error, ret is %d, mid is %u", ret, mid);
        return  -ERROR_TLV_SEND_MSG;
    }

    return 0;
}

void TlvDispatcher::PackStartSendPushMsg(string &push_msg, uint32_t &push_mid)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize;

    push_mid = g_push_msg_mid.incrementAndGet();
    EncodeCommonTlv(&push_msg, msg_len, push_mid);

    PutFixed32(&push_msg, TYPE_PUSH_CLIENT_START_SEND);
    PutFixed32(&push_msg, 0);

   return;
}

int32_t TlvDispatcher::HandleClientStartSend(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret = 0;
    int dev_fd = -1;
    string dev_id;
    uint32_t push_mid = 0;
    string push_msg;
    PushMsgContext *ct = NULL;

    LOG_DEBUG(g_logger, "client start to send, and mid is %u", mid);

    //const char *data = cmd_value.data();
    int size = cmd_value.size();

    if (size != 0)
    {
        LOG_ERROR(g_logger, "cmd value of client start send error");
        ret = -ERROR_TLV_LEN_NOT_0;
        goto SEND_RESPONSE;
    }

    // 转发到client
    if (conn_info->guid_type != GUID_CLIENT || conn_info->guid == "")
    {
        LOG_ERROR(g_logger, "client not build voice channel, mid %u, guid type %d, guid %s", mid,
                        conn_info->guid_type, conn_info->guid.c_str());
        ret = -ERROR_CLIENT_NOT_BUILD_VC;
        goto SEND_RESPONSE;
    }

    ret = vc_manager_.RouteClientToDev(conn_info->guid, dev_id, dev_fd);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "can't find dev for client, mid %u, guid type %d, guid %s", mid,
                        conn_info->guid_type, conn_info->guid.c_str());
        ret = -ERROR_CANNOT_FIND_DEV_FOR_CLIENT;
        goto SEND_RESPONSE;
    }

    PackStartSendPushMsg(push_msg, push_mid);

    ct = new PushMsgContext(mid, conn_info->cfd, push_mid, TYPE_ON_CLIENT_START_SEND);
    ret = ForwardMsgToDev(dev_fd, push_mid, push_msg, ct);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "forward msg to dev error, client_id %s, dev_id %s, ret %d", conn_info->guid.c_str(),
                        dev_id.c_str(), ret);
        goto SEND_RESPONSE;
    }

    LOG_DEBUG(g_logger, "forward client start send msg to dev ok, mid is %u, client_id %s, dev_id %s",
                        mid, conn_info->guid.c_str(), dev_id.c_str());
    return 0;

SEND_RESPONSE:
    string resp_msg;
    PackStartSendRespMsg(mid, resp_msg, ret);
    ret = SendMsg(conn_info->cfd, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send response msg of client start send error, ret %d, mid %u", ret, mid);
        return -ERROR_TLV_SEND_MSG;
    }

    return 0;
}

void TlvDispatcher::PackStartSendRespMsg(uint32_t mid, string &resp_msg, int32_t ret)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize;

    EncodeCommonTlv(&resp_msg, msg_len, mid);

    PutFixed32(&resp_msg, TYPE_ON_CLIENT_START_SEND);
    PutFixed32(&resp_msg, ret);

    return;
}

int32_t TlvDispatcher::HandleOnPushStartSend(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret;
    LOG_DEBUG(g_logger, "handle on push start send, and mid is %u", mid);

    //int size = cmd_value.size();
    const char *data = cmd_value.data();

    int32_t on_push_ret = DecodeFixed32(data);

    // 取消等待推送消息的回复消息的超时事件
    PushMsgInfo push_msg_info;
    ret = push_msg_timer_queue_.GetAndCancelEvent(mid, push_msg_info);
    if (ret != 0)
    {
        LOG_INFO(g_logger, "get and cancel event error, ret %d, mid %u", ret, mid);
        return 0;
    }

    string resp_msg;
    PackStartSendRespMsg(push_msg_info.recv_mid_, resp_msg, on_push_ret);
    ret = SendMsg(push_msg_info.recv_cfd_, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send client start send response msg error, mid %u, ret %d",
                            push_msg_info.recv_mid_, ret);
    }

    return 0;
}

void TlvDispatcher::PackSendVoicePushMsg(string &push_msg, uint32_t &push_mid, Slice &data)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize + data.size();

    push_mid = g_push_msg_mid.incrementAndGet();
    EncodeCommonTlv(&push_msg, msg_len, push_mid);

    PutFixed32(&push_msg, TYPE_PUSH_CLIENT_VOICE_DATA);
    PutFixed32(&push_msg, data.size());
    push_msg.append(data.data(), data.size());
}

int32_t TlvDispatcher::HandleClientSendVoice(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret = 0;
    int dev_fd;
    string dev_id;
    PushMsgContext *ct = NULL;
    uint32_t push_mid;
    string push_msg;

    LOG_DEBUG(g_logger, "client send voice data, and mid is %u", mid);

    //const char *data = cmd_value.data();
    //int size = cmd_value.size();

    // 转发到client
    if (conn_info->guid_type != GUID_CLIENT || conn_info->guid == "")
    {
        LOG_ERROR(g_logger, "client not build voice channel, mid %u, guid type %d, guid %s", mid,
                        conn_info->guid_type, conn_info->guid.c_str());
        ret = -ERROR_CLIENT_NOT_BUILD_VC;
        goto SEND_RESPONSE;
    }

    ret = vc_manager_.RouteClientToDev(conn_info->guid, dev_id, dev_fd);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "can't find dev for client, mid %u, guid type %d, guid %s", mid,
                        conn_info->guid_type, conn_info->guid.c_str());
        ret = -ERROR_CANNOT_FIND_DEV_FOR_CLIENT;
        goto SEND_RESPONSE;
    }

    PackSendVoicePushMsg(push_msg, push_mid, cmd_value);
    ct = new PushMsgContext(mid, conn_info->cfd, push_mid, TYPE_ON_CLIENT_SEND_VOICE_DATA);
    assert(ct != NULL);
    ret = ForwardMsgToDev(dev_fd, push_mid, push_msg, ct);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "forward msg to dev error, client_id %s, dev_id %s, ret %d", conn_info->guid.c_str(),
                        dev_id.c_str(), ret);
        goto SEND_RESPONSE;
    }

    LOG_DEBUG(g_logger, "forward client send voice msg to dev ok, mid is %u, client_id %s, dev_id %s",
                        mid, conn_info->guid.c_str(), dev_id.c_str());
    return 0;

SEND_RESPONSE:
    LOG_DEBUG(g_logger, "forward client send voice msg to dev error, mid is %u, client_id %s",
                        mid, conn_info->guid.c_str());
    string resp_msg;
    PackClientSendVoiceRespMsg(mid, resp_msg, ret);
    ret = SendMsg(conn_info->cfd, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send response msg of client send voice error, ret %d, mid %u", ret, mid);
        return -ERROR_TLV_SEND_MSG;
    }

    return 0;
}

void TlvDispatcher::PackClientSendVoiceRespMsg(uint32_t mid, string &resp_msg, int32_t ret)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize;

    EncodeCommonTlv(&resp_msg, msg_len, mid);

    PutFixed32(&resp_msg, TYPE_ON_CLIENT_SEND_VOICE_DATA);
    PutFixed32(&resp_msg, ret);

    return;
}

int32_t TlvDispatcher::HandleOnPushClientVoice(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret;
    LOG_DEBUG(g_logger, "handle on push send voice msg, and mid is %u", mid);

    //int size = cmd_value.size();
    const char *data = cmd_value.data();

    int32_t on_push_ret = DecodeFixed32(data);

    // 取消等待推送消息的回复消息的超时事件
    PushMsgInfo push_msg_info;
    ret = push_msg_timer_queue_.GetAndCancelEvent(mid, push_msg_info);
    if (ret != 0)
    {
        LOG_INFO(g_logger, "get and cancel event error, ret %d, mid %u", ret, mid);
        return 0;
    }

    string resp_msg;
    PackClientSendVoiceRespMsg(push_msg_info.recv_mid_, resp_msg, on_push_ret);
    ret = SendMsg(push_msg_info.recv_cfd_, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send client start send response msg error, mid %u, ret %d",
                            push_msg_info.recv_mid_, ret);
        // 发送失败也不要返回错误,因为返回错误会关闭当前连接,而当前连接是设备端的连接
    }

    return 0;
}

void TlvDispatcher::PackClientFreeVcRespMsg(uint32_t mid, string &resp_msg, int32_t ret)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize + 4;

    EncodeCommonTlv(&resp_msg, msg_len, mid);
    EncodeRet(&resp_msg, TYPE_ON_CLIENT_FREE_VC, ret);
}

int32_t TlvDispatcher::HandleClientFreeVc(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret;
    uint32_t type;
    uint32_t len;
    string client_id;
    string dev_id;

    LOG_DEBUG(g_logger, "client free voice channle, mid is %u", mid);

    const char *data = cmd_value.data();
    //size_t size = cmd_value.size();

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of client_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_CLIENT_ID;
        goto SEND_RESPONSE;
    }
    client_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of dev_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_DEV_ID;
        goto SEND_RESPONSE;
    }
    dev_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    ret = vc_manager_.DisconnectByClient(client_id, dev_id);

SEND_RESPONSE:
    string resp_msg;
    PackClientFreeVcRespMsg(mid, resp_msg, ret);
    ret = SendMsg(conn_info->cfd, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send response msg of free vc, ret is %d, mid is %u", ret, mid);
        return -ERROR_TLV_SEND_MSG;
    }

    // 返回错误,触发释放本端通道
    return -ERROR_CLIENT_VC_INVALID;
}

void TlvDispatcher::PackDevBuildVcRespMsg(uint32_t mid, string &resp_msg, int32_t ret)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize + 4;

    EncodeCommonTlv(&resp_msg, msg_len, mid);
    EncodeRet(&resp_msg, TYPE_ON_DEV_BUILD_VC, ret);
}

int32_t TlvDispatcher::HandleDevBuildVc(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret;
    uint32_t type;
    uint32_t len;
    string client_id;
    string dev_id;
    DevVcInfo dev_vc_info;

    LOG_DEBUG(g_logger, "device build voice channel, and mid is %u", mid);

    //int size = cmd_value.size();
    const char *data = cmd_value.data();

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of client_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_CLIENT_ID;
        goto SEND_RESPONSE;
    }
    client_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of dev_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_DEV_ID;
        goto SEND_RESPONSE;
    }
    dev_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    conn_info->guid_type = GUID_DEV;
    conn_info->guid = dev_id;

    LOG_DEBUG(g_logger, "mid is %u, client_id is %s, dev_id is %s", mid, client_id.c_str(), dev_id.c_str());

    dev_vc_info.dev_id = dev_id;
    dev_vc_info.dev_fd = conn_info->cfd;
    dev_vc_info.dev_bev = conn_info->buffer_event;
    dev_vc_info.client_id = client_id;
    ret = vc_manager_.ConnectByDev(dev_id, dev_vc_info);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "connect by dev error, ret is %d", ret);
        goto SEND_RESPONSE;
    }

    LOG_DEBUG(g_logger, "client build voice channel ok, and mid is %u, client id is %s, dev id is %s",
                        mid, client_id.c_str(), dev_id.c_str());

SEND_RESPONSE:
    string resp_msg;
    PackClientBuildVcRespMsg(mid, ret, resp_msg);
    ret = SendMsg(conn_info->cfd, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send response msg of dev build voice channle error, ret is %d, mid is %u", ret, mid);
        return -ERROR_TLV_SEND_MSG;
    }

    return 0;
}

void TlvDispatcher::PackDevFreeVcRespMsg(uint32_t mid, string &resp_msg, int32_t ret)
{
    uint32_t msg_len = kMsgHeaderSize + 4 + kMsgHeaderSize + 4 + kMsgHeaderSize + 4;

    EncodeCommonTlv(&resp_msg, msg_len, mid);
    EncodeRet(&resp_msg, TYPE_ON_DEV_FREE_VC, ret);
}

int32_t TlvDispatcher::HandleDevFreeVc(ConnectionInfo *conn_info, uint32_t mid, Slice &cmd_value)
{
    int32_t ret;
    uint32_t type;
    uint32_t len;
    string client_id;
    string dev_id;

    LOG_DEBUG(g_logger, "dev free voice channle, mid is %u", mid);

    const char *data = cmd_value.data();
    //size_t size = cmd_value.size();

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of client_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_CLIENT_ID;
        goto SEND_RESPONSE;
    }
    client_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    type = DecodeFixed32(data);
    len = DecodeFixed32(data + 4);
    if (len > MAX_GUID_LEN)
    {
        LOG_ERROR(g_logger, "parse length of dev_id error, because length is bigger than %d", MAX_GUID_LEN);
        ret = -ERROR_TLV_PARSE_DEV_ID;
        goto SEND_RESPONSE;
    }
    dev_id.assign(data + kMsgHeaderSize, len);
    data += kMsgHeaderSize + len;

    ret = vc_manager_.DisconnectByDev(dev_id, client_id);

SEND_RESPONSE:
    string resp_msg;
    PackClientFreeVcRespMsg(mid, resp_msg, ret);

    ret = SendMsg(conn_info->cfd, resp_msg);
    if (ret != 0)
    {
        LOG_ERROR(g_logger, "send response msg of dev free vc, ret is %d, mid is %u", ret, mid);
        return -ERROR_TLV_SEND_MSG;
    }

    // 返回错误,以触发释放本端通道
    return -ERROR_DEV_VC_INVALID;
}


text:
from FoodScan import AntiCaptcha, WuList
from FoodScan.ShopSync import *
from config import *

# Shops:
kl = Kaufland(kaufland_email, kaufland_password, AntiCaptcha(anti_captcha_key))
# ayn = AllYouNeed(all_you_need_email, all_you_need_password)

# Syncer:
#  Polling wunderlist for changes
# ShopSync(kl, shop_sync_config, asynchron=False)

#  Webhook that wunderlist can call when the list changes
ShopSync(kl, WuList(shop_sync_config),
         web_hook_url=web_hook_url,
         web_server_ip=web_server_ip,
         web_server_port=web_server_port,
         asynchron=False)

redpajama_set_name: RedPajamaGithub


text:
package sqlite3

import (
	"bytes"
	"context"
	"reflect"
	"testing"

	"github.com/thrasher-corp/sqlboiler/boil"
	"github.com/thrasher-corp/sqlboiler/queries"
	"github.com/thrasher-corp/sqlboiler/randomize"
	"github.com/thrasher-corp/sqlboiler/strmangle"
)

var (
	// Relationships sometimes use the reflection helper queries.Equal/queries.Assign
	// so force a package dependency in case they don't.
	_ = queries.Equal
)

func testExchanges(t *testing.T) {
	t.Parallel()

	query := Exchanges()

	if query.Query == nil {
		t.Error("expected a query, got nothing")
	}
}

func testExchangesDelete(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	if rowsAff, err := o.Delete(ctx, tx); err != nil {
		t.Error(err)
	} else if rowsAff != 1 {
		t.Error("should only have deleted one row, but affected:", rowsAff)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 0 {
		t.Error("want zero records, got:", count)
	}
}

func testExchangesQueryDeleteAll(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	if rowsAff, err := Exchanges().DeleteAll(ctx, tx); err != nil {
		t.Error(err)
	} else if rowsAff != 1 {
		t.Error("should only have deleted one row, but affected:", rowsAff)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 0 {
		t.Error("want zero records, got:", count)
	}
}

func testExchangesSliceDeleteAll(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	slice := ExchangeSlice{o}

	if rowsAff, err := slice.DeleteAll(ctx, tx); err != nil {
		t.Error(err)
	} else if rowsAff != 1 {
		t.Error("should only have deleted one row, but affected:", rowsAff)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 0 {
		t.Error("want zero records, got:", count)
	}
}

func testExchangesExists(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	e, err := ExchangeExists(ctx, tx, o.ID)
	if err != nil {
		t.Errorf("Unable to check if Exchange exists: %s", err)
	}
	if !e {
		t.Errorf("Expected ExchangeExists to return true, but got false.")
	}
}

func testExchangesFind(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	exchangeFound, err := FindExchange(ctx, tx, o.ID)
	if err != nil {
		t.Error(err)
	}

	if exchangeFound == nil {
		t.Error("want a record, got nil")
	}
}

func testExchangesBind(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	if err = Exchanges().Bind(ctx, tx, o); err != nil {
		t.Error(err)
	}
}

func testExchangesOne(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	if x, err := Exchanges().One(ctx, tx); err != nil {
		t.Error(err)
	} else if x == nil {
		t.Error("expected to get a non nil record")
	}
}

func testExchangesAll(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	exchangeOne := &Exchange{}
	exchangeTwo := &Exchange{}
	if err = randomize.Struct(seed, exchangeOne, exchangeDBTypes, false, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}
	if err = randomize.Struct(seed, exchangeTwo, exchangeDBTypes, false, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = exchangeOne.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}
	if err = exchangeTwo.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	slice, err := Exchanges().All(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if len(slice) != 2 {
		t.Error("want 2 records, got:", len(slice))
	}
}

func testExchangesCount(t *testing.T) {
	t.Parallel()

	var err error
	seed := randomize.NewSeed()
	exchangeOne := &Exchange{}
	exchangeTwo := &Exchange{}
	if err = randomize.Struct(seed, exchangeOne, exchangeDBTypes, false, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}
	if err = randomize.Struct(seed, exchangeTwo, exchangeDBTypes, false, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = exchangeOne.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}
	if err = exchangeTwo.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 2 {
		t.Error("want 2 records, got:", count)
	}
}

func exchangeBeforeInsertHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeAfterInsertHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeAfterSelectHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeBeforeUpdateHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeAfterUpdateHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeBeforeDeleteHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeAfterDeleteHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeBeforeUpsertHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func exchangeAfterUpsertHook(ctx context.Context, e boil.ContextExecutor, o *Exchange) error {
	*o = Exchange{}
	return nil
}

func testExchangesHooks(t *testing.T) {
	t.Parallel()

	var err error

	ctx := context.Background()
	empty := &Exchange{}
	o := &Exchange{}

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, o, exchangeDBTypes, false); err != nil {
		t.Errorf("Unable to randomize Exchange object: %s", err)
	}

	AddExchangeHook(boil.BeforeInsertHook, exchangeBeforeInsertHook)
	if err = o.doBeforeInsertHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doBeforeInsertHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected BeforeInsertHook function to empty object, but got: %#v", o)
	}
	exchangeBeforeInsertHooks = []ExchangeHook{}

	AddExchangeHook(boil.AfterInsertHook, exchangeAfterInsertHook)
	if err = o.doAfterInsertHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doAfterInsertHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected AfterInsertHook function to empty object, but got: %#v", o)
	}
	exchangeAfterInsertHooks = []ExchangeHook{}

	AddExchangeHook(boil.AfterSelectHook, exchangeAfterSelectHook)
	if err = o.doAfterSelectHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doAfterSelectHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected AfterSelectHook function to empty object, but got: %#v", o)
	}
	exchangeAfterSelectHooks = []ExchangeHook{}

	AddExchangeHook(boil.BeforeUpdateHook, exchangeBeforeUpdateHook)
	if err = o.doBeforeUpdateHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doBeforeUpdateHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected BeforeUpdateHook function to empty object, but got: %#v", o)
	}
	exchangeBeforeUpdateHooks = []ExchangeHook{}

	AddExchangeHook(boil.AfterUpdateHook, exchangeAfterUpdateHook)
	if err = o.doAfterUpdateHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doAfterUpdateHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected AfterUpdateHook function to empty object, but got: %#v", o)
	}
	exchangeAfterUpdateHooks = []ExchangeHook{}

	AddExchangeHook(boil.BeforeDeleteHook, exchangeBeforeDeleteHook)
	if err = o.doBeforeDeleteHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doBeforeDeleteHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected BeforeDeleteHook function to empty object, but got: %#v", o)
	}
	exchangeBeforeDeleteHooks = []ExchangeHook{}

	AddExchangeHook(boil.AfterDeleteHook, exchangeAfterDeleteHook)
	if err = o.doAfterDeleteHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doAfterDeleteHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected AfterDeleteHook function to empty object, but got: %#v", o)
	}
	exchangeAfterDeleteHooks = []ExchangeHook{}

	AddExchangeHook(boil.BeforeUpsertHook, exchangeBeforeUpsertHook)
	if err = o.doBeforeUpsertHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doBeforeUpsertHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected BeforeUpsertHook function to empty object, but got: %#v", o)
	}
	exchangeBeforeUpsertHooks = []ExchangeHook{}

	AddExchangeHook(boil.AfterUpsertHook, exchangeAfterUpsertHook)
	if err = o.doAfterUpsertHooks(ctx, nil); err != nil {
		t.Errorf("Unable to execute doAfterUpsertHooks: %s", err)
	}
	if !reflect.DeepEqual(o, empty) {
		t.Errorf("Expected AfterUpsertHook function to empty object, but got: %#v", o)
	}
	exchangeAfterUpsertHooks = []ExchangeHook{}
}

func testExchangesInsert(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 1 {
		t.Error("want one record, got:", count)
	}
}

func testExchangesInsertWhitelist(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Whitelist(exchangeColumnsWithoutDefault...)); err != nil {
		t.Error(err)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 1 {
		t.Error("want one record, got:", count)
	}
}

func testExchangeOneToOneCandleUsingExchangeNameCandle(t *testing.T) {
	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var foreign Candle
	var local Exchange

	seed := randomize.NewSeed()
	if err := randomize.Struct(seed, &foreign, candleDBTypes, true, candleColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Candle struct: %s", err)
	}
	if err := randomize.Struct(seed, &local, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	if err := local.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	foreign.ExchangeNameID = local.ID
	if err := foreign.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	check, err := local.ExchangeNameCandle().One(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}

	if check.ExchangeNameID != foreign.ExchangeNameID {
		t.Errorf("want: %v, got %v", foreign.ExchangeNameID, check.ExchangeNameID)
	}

	slice := ExchangeSlice{&local}
	if err = local.L.LoadExchangeNameCandle(ctx, tx, false, (*[]*Exchange)(&slice), nil); err != nil {
		t.Fatal(err)
	}
	if local.R.ExchangeNameCandle == nil {
		t.Error("struct should have been eager loaded")
	}

	local.R.ExchangeNameCandle = nil
	if err = local.L.LoadExchangeNameCandle(ctx, tx, true, &local, nil); err != nil {
		t.Fatal(err)
	}
	if local.R.ExchangeNameCandle == nil {
		t.Error("struct should have been eager loaded")
	}
}

func testExchangeOneToOneTradeUsingExchangeNameTrade(t *testing.T) {
	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var foreign Trade
	var local Exchange

	seed := randomize.NewSeed()
	if err := randomize.Struct(seed, &foreign, tradeDBTypes, true, tradeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Trade struct: %s", err)
	}
	if err := randomize.Struct(seed, &local, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	if err := local.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	foreign.ExchangeNameID = local.ID
	if err := foreign.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	check, err := local.ExchangeNameTrade().One(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}

	if check.ExchangeNameID != foreign.ExchangeNameID {
		t.Errorf("want: %v, got %v", foreign.ExchangeNameID, check.ExchangeNameID)
	}

	slice := ExchangeSlice{&local}
	if err = local.L.LoadExchangeNameTrade(ctx, tx, false, (*[]*Exchange)(&slice), nil); err != nil {
		t.Fatal(err)
	}
	if local.R.ExchangeNameTrade == nil {
		t.Error("struct should have been eager loaded")
	}

	local.R.ExchangeNameTrade = nil
	if err = local.L.LoadExchangeNameTrade(ctx, tx, true, &local, nil); err != nil {
		t.Fatal(err)
	}
	if local.R.ExchangeNameTrade == nil {
		t.Error("struct should have been eager loaded")
	}
}

func testExchangeOneToOneSetOpCandleUsingExchangeNameCandle(t *testing.T) {
	var err error

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c Candle

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, false, strmangle.SetComplement(exchangePrimaryKeyColumns, exchangeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	if err = randomize.Struct(seed, &b, candleDBTypes, false, strmangle.SetComplement(candlePrimaryKeyColumns, candleColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	if err = randomize.Struct(seed, &c, candleDBTypes, false, strmangle.SetComplement(candlePrimaryKeyColumns, candleColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	for i, x := range []*Candle{&b, &c} {
		err = a.SetExchangeNameCandle(ctx, tx, i != 0, x)
		if err != nil {
			t.Fatal(err)
		}

		if a.R.ExchangeNameCandle != x {
			t.Error("relationship struct not set to correct value")
		}
		if x.R.ExchangeName != &a {
			t.Error("failed to append to foreign relationship struct")
		}

		if a.ID != x.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID)
		}

		zero := reflect.Zero(reflect.TypeOf(x.ExchangeNameID))
		reflect.Indirect(reflect.ValueOf(&x.ExchangeNameID)).Set(zero)

		if err = x.Reload(ctx, tx); err != nil {
			t.Fatal("failed to reload", err)
		}

		if a.ID != x.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID, x.ExchangeNameID)
		}

		if _, err = x.Delete(ctx, tx); err != nil {
			t.Fatal("failed to delete x", err)
		}
	}
}
func testExchangeOneToOneSetOpTradeUsingExchangeNameTrade(t *testing.T) {
	var err error

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c Trade

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, false, strmangle.SetComplement(exchangePrimaryKeyColumns, exchangeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	if err = randomize.Struct(seed, &b, tradeDBTypes, false, strmangle.SetComplement(tradePrimaryKeyColumns, tradeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	if err = randomize.Struct(seed, &c, tradeDBTypes, false, strmangle.SetComplement(tradePrimaryKeyColumns, tradeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	for i, x := range []*Trade{&b, &c} {
		err = a.SetExchangeNameTrade(ctx, tx, i != 0, x)
		if err != nil {
			t.Fatal(err)
		}

		if a.R.ExchangeNameTrade != x {
			t.Error("relationship struct not set to correct value")
		}
		if x.R.ExchangeName != &a {
			t.Error("failed to append to foreign relationship struct")
		}

		if a.ID != x.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID)
		}

		zero := reflect.Zero(reflect.TypeOf(x.ExchangeNameID))
		reflect.Indirect(reflect.ValueOf(&x.ExchangeNameID)).Set(zero)

		if err = x.Reload(ctx, tx); err != nil {
			t.Fatal("failed to reload", err)
		}

		if a.ID != x.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID, x.ExchangeNameID)
		}

		if _, err = x.Delete(ctx, tx); err != nil {
			t.Fatal("failed to delete x", err)
		}
	}
}

func testExchangeToManyExchangeNameDatahistoryjobs(t *testing.T) {
	var err error
	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c Datahistoryjob

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	if err = randomize.Struct(seed, &b, datahistoryjobDBTypes, false, datahistoryjobColumnsWithDefault...); err != nil {
		t.Fatal(err)
	}
	if err = randomize.Struct(seed, &c, datahistoryjobDBTypes, false, datahistoryjobColumnsWithDefault...); err != nil {
		t.Fatal(err)
	}

	b.ExchangeNameID = a.ID
	c.ExchangeNameID = a.ID

	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = c.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	check, err := a.ExchangeNameDatahistoryjobs().All(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}

	bFound, cFound := false, false
	for _, v := range check {
		if v.ExchangeNameID == b.ExchangeNameID {
			bFound = true
		}
		if v.ExchangeNameID == c.ExchangeNameID {
			cFound = true
		}
	}

	if !bFound {
		t.Error("expected to find b")
	}
	if !cFound {
		t.Error("expected to find c")
	}

	slice := ExchangeSlice{&a}
	if err = a.L.LoadExchangeNameDatahistoryjobs(ctx, tx, false, (*[]*Exchange)(&slice), nil); err != nil {
		t.Fatal(err)
	}
	if got := len(a.R.ExchangeNameDatahistoryjobs); got != 2 {
		t.Error("number of eager loaded records wrong, got:", got)
	}

	a.R.ExchangeNameDatahistoryjobs = nil
	if err = a.L.LoadExchangeNameDatahistoryjobs(ctx, tx, true, &a, nil); err != nil {
		t.Fatal(err)
	}
	if got := len(a.R.ExchangeNameDatahistoryjobs); got != 2 {
		t.Error("number of eager loaded records wrong, got:", got)
	}

	if t.Failed() {
		t.Logf("%#v", check)
	}
}

func testExchangeToManySecondaryExchangeDatahistoryjobs(t *testing.T) {
	var err error
	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c Datahistoryjob

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	if err = randomize.Struct(seed, &b, datahistoryjobDBTypes, false, datahistoryjobColumnsWithDefault...); err != nil {
		t.Fatal(err)
	}
	if err = randomize.Struct(seed, &c, datahistoryjobDBTypes, false, datahistoryjobColumnsWithDefault...); err != nil {
		t.Fatal(err)
	}

	queries.Assign(&b.SecondaryExchangeID, a.ID)
	queries.Assign(&c.SecondaryExchangeID, a.ID)
	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = c.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	check, err := a.SecondaryExchangeDatahistoryjobs().All(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}

	bFound, cFound := false, false
	for _, v := range check {
		if queries.Equal(v.SecondaryExchangeID, b.SecondaryExchangeID) {
			bFound = true
		}
		if queries.Equal(v.SecondaryExchangeID, c.SecondaryExchangeID) {
			cFound = true
		}
	}

	if !bFound {
		t.Error("expected to find b")
	}
	if !cFound {
		t.Error("expected to find c")
	}

	slice := ExchangeSlice{&a}
	if err = a.L.LoadSecondaryExchangeDatahistoryjobs(ctx, tx, false, (*[]*Exchange)(&slice), nil); err != nil {
		t.Fatal(err)
	}
	if got := len(a.R.SecondaryExchangeDatahistoryjobs); got != 2 {
		t.Error("number of eager loaded records wrong, got:", got)
	}

	a.R.SecondaryExchangeDatahistoryjobs = nil
	if err = a.L.LoadSecondaryExchangeDatahistoryjobs(ctx, tx, true, &a, nil); err != nil {
		t.Fatal(err)
	}
	if got := len(a.R.SecondaryExchangeDatahistoryjobs); got != 2 {
		t.Error("number of eager loaded records wrong, got:", got)
	}

	if t.Failed() {
		t.Logf("%#v", check)
	}
}

func testExchangeToManyExchangeNameWithdrawalHistories(t *testing.T) {
	var err error
	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c WithdrawalHistory

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	if err = randomize.Struct(seed, &b, withdrawalHistoryDBTypes, false, withdrawalHistoryColumnsWithDefault...); err != nil {
		t.Fatal(err)
	}
	if err = randomize.Struct(seed, &c, withdrawalHistoryDBTypes, false, withdrawalHistoryColumnsWithDefault...); err != nil {
		t.Fatal(err)
	}

	b.ExchangeNameID = a.ID
	c.ExchangeNameID = a.ID

	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = c.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	check, err := a.ExchangeNameWithdrawalHistories().All(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}

	bFound, cFound := false, false
	for _, v := range check {
		if v.ExchangeNameID == b.ExchangeNameID {
			bFound = true
		}
		if v.ExchangeNameID == c.ExchangeNameID {
			cFound = true
		}
	}

	if !bFound {
		t.Error("expected to find b")
	}
	if !cFound {
		t.Error("expected to find c")
	}

	slice := ExchangeSlice{&a}
	if err = a.L.LoadExchangeNameWithdrawalHistories(ctx, tx, false, (*[]*Exchange)(&slice), nil); err != nil {
		t.Fatal(err)
	}
	if got := len(a.R.ExchangeNameWithdrawalHistories); got != 2 {
		t.Error("number of eager loaded records wrong, got:", got)
	}

	a.R.ExchangeNameWithdrawalHistories = nil
	if err = a.L.LoadExchangeNameWithdrawalHistories(ctx, tx, true, &a, nil); err != nil {
		t.Fatal(err)
	}
	if got := len(a.R.ExchangeNameWithdrawalHistories); got != 2 {
		t.Error("number of eager loaded records wrong, got:", got)
	}

	if t.Failed() {
		t.Logf("%#v", check)
	}
}

func testExchangeToManyAddOpExchangeNameDatahistoryjobs(t *testing.T) {
	var err error

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c, d, e Datahistoryjob

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, false, strmangle.SetComplement(exchangePrimaryKeyColumns, exchangeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	foreigners := []*Datahistoryjob{&b, &c, &d, &e}
	for _, x := range foreigners {
		if err = randomize.Struct(seed, x, datahistoryjobDBTypes, false, strmangle.SetComplement(datahistoryjobPrimaryKeyColumns, datahistoryjobColumnsWithoutDefault)...); err != nil {
			t.Fatal(err)
		}
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = c.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	foreignersSplitByInsertion := [][]*Datahistoryjob{
		{&b, &c},
		{&d, &e},
	}

	for i, x := range foreignersSplitByInsertion {
		err = a.AddExchangeNameDatahistoryjobs(ctx, tx, i != 0, x...)
		if err != nil {
			t.Fatal(err)
		}

		first := x[0]
		second := x[1]

		if a.ID != first.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID, first.ExchangeNameID)
		}
		if a.ID != second.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID, second.ExchangeNameID)
		}

		if first.R.ExchangeName != &a {
			t.Error("relationship was not added properly to the foreign slice")
		}
		if second.R.ExchangeName != &a {
			t.Error("relationship was not added properly to the foreign slice")
		}

		if a.R.ExchangeNameDatahistoryjobs[i*2] != first {
			t.Error("relationship struct slice not set to correct value")
		}
		if a.R.ExchangeNameDatahistoryjobs[i*2+1] != second {
			t.Error("relationship struct slice not set to correct value")
		}

		count, err := a.ExchangeNameDatahistoryjobs().Count(ctx, tx)
		if err != nil {
			t.Fatal(err)
		}
		if want := int64((i + 1) * 2); count != want {
			t.Error("want", want, "got", count)
		}
	}
}
func testExchangeToManyAddOpSecondaryExchangeDatahistoryjobs(t *testing.T) {
	var err error

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c, d, e Datahistoryjob

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, false, strmangle.SetComplement(exchangePrimaryKeyColumns, exchangeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	foreigners := []*Datahistoryjob{&b, &c, &d, &e}
	for _, x := range foreigners {
		if err = randomize.Struct(seed, x, datahistoryjobDBTypes, false, strmangle.SetComplement(datahistoryjobPrimaryKeyColumns, datahistoryjobColumnsWithoutDefault)...); err != nil {
			t.Fatal(err)
		}
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = c.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	foreignersSplitByInsertion := [][]*Datahistoryjob{
		{&b, &c},
		{&d, &e},
	}

	for i, x := range foreignersSplitByInsertion {
		err = a.AddSecondaryExchangeDatahistoryjobs(ctx, tx, i != 0, x...)
		if err != nil {
			t.Fatal(err)
		}

		first := x[0]
		second := x[1]

		if !queries.Equal(a.ID, first.SecondaryExchangeID) {
			t.Error("foreign key was wrong value", a.ID, first.SecondaryExchangeID)
		}
		if !queries.Equal(a.ID, second.SecondaryExchangeID) {
			t.Error("foreign key was wrong value", a.ID, second.SecondaryExchangeID)
		}

		if first.R.SecondaryExchange != &a {
			t.Error("relationship was not added properly to the foreign slice")
		}
		if second.R.SecondaryExchange != &a {
			t.Error("relationship was not added properly to the foreign slice")
		}

		if a.R.SecondaryExchangeDatahistoryjobs[i*2] != first {
			t.Error("relationship struct slice not set to correct value")
		}
		if a.R.SecondaryExchangeDatahistoryjobs[i*2+1] != second {
			t.Error("relationship struct slice not set to correct value")
		}

		count, err := a.SecondaryExchangeDatahistoryjobs().Count(ctx, tx)
		if err != nil {
			t.Fatal(err)
		}
		if want := int64((i + 1) * 2); count != want {
			t.Error("want", want, "got", count)
		}
	}
}

func testExchangeToManySetOpSecondaryExchangeDatahistoryjobs(t *testing.T) {
	var err error

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c, d, e Datahistoryjob

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, false, strmangle.SetComplement(exchangePrimaryKeyColumns, exchangeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	foreigners := []*Datahistoryjob{&b, &c, &d, &e}
	for _, x := range foreigners {
		if err = randomize.Struct(seed, x, datahistoryjobDBTypes, false, strmangle.SetComplement(datahistoryjobPrimaryKeyColumns, datahistoryjobColumnsWithoutDefault)...); err != nil {
			t.Fatal(err)
		}
	}

	if err = a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = c.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	err = a.SetSecondaryExchangeDatahistoryjobs(ctx, tx, false, &b, &c)
	if err != nil {
		t.Fatal(err)
	}

	count, err := a.SecondaryExchangeDatahistoryjobs().Count(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}
	if count != 2 {
		t.Error("count was wrong:", count)
	}

	err = a.SetSecondaryExchangeDatahistoryjobs(ctx, tx, true, &d, &e)
	if err != nil {
		t.Fatal(err)
	}

	count, err = a.SecondaryExchangeDatahistoryjobs().Count(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}
	if count != 2 {
		t.Error("count was wrong:", count)
	}

	if !queries.IsValuerNil(b.SecondaryExchangeID) {
		t.Error("want b's foreign key value to be nil")
	}
	if !queries.IsValuerNil(c.SecondaryExchangeID) {
		t.Error("want c's foreign key value to be nil")
	}
	if !queries.Equal(a.ID, d.SecondaryExchangeID) {
		t.Error("foreign key was wrong value", a.ID, d.SecondaryExchangeID)
	}
	if !queries.Equal(a.ID, e.SecondaryExchangeID) {
		t.Error("foreign key was wrong value", a.ID, e.SecondaryExchangeID)
	}

	if b.R.SecondaryExchange != nil {
		t.Error("relationship was not removed properly from the foreign struct")
	}
	if c.R.SecondaryExchange != nil {
		t.Error("relationship was not removed properly from the foreign struct")
	}
	if d.R.SecondaryExchange != &a {
		t.Error("relationship was not added properly to the foreign struct")
	}
	if e.R.SecondaryExchange != &a {
		t.Error("relationship was not added properly to the foreign struct")
	}

	if a.R.SecondaryExchangeDatahistoryjobs[0] != &d {
		t.Error("relationship struct slice not set to correct value")
	}
	if a.R.SecondaryExchangeDatahistoryjobs[1] != &e {
		t.Error("relationship struct slice not set to correct value")
	}
}

func testExchangeToManyRemoveOpSecondaryExchangeDatahistoryjobs(t *testing.T) {
	var err error

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c, d, e Datahistoryjob

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, false, strmangle.SetComplement(exchangePrimaryKeyColumns, exchangeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	foreigners := []*Datahistoryjob{&b, &c, &d, &e}
	for _, x := range foreigners {
		if err = randomize.Struct(seed, x, datahistoryjobDBTypes, false, strmangle.SetComplement(datahistoryjobPrimaryKeyColumns, datahistoryjobColumnsWithoutDefault)...); err != nil {
			t.Fatal(err)
		}
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	err = a.AddSecondaryExchangeDatahistoryjobs(ctx, tx, true, foreigners...)
	if err != nil {
		t.Fatal(err)
	}

	count, err := a.SecondaryExchangeDatahistoryjobs().Count(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}
	if count != 4 {
		t.Error("count was wrong:", count)
	}

	err = a.RemoveSecondaryExchangeDatahistoryjobs(ctx, tx, foreigners[:2]...)
	if err != nil {
		t.Fatal(err)
	}

	count, err = a.SecondaryExchangeDatahistoryjobs().Count(ctx, tx)
	if err != nil {
		t.Fatal(err)
	}
	if count != 2 {
		t.Error("count was wrong:", count)
	}

	if !queries.IsValuerNil(b.SecondaryExchangeID) {
		t.Error("want b's foreign key value to be nil")
	}
	if !queries.IsValuerNil(c.SecondaryExchangeID) {
		t.Error("want c's foreign key value to be nil")
	}

	if b.R.SecondaryExchange != nil {
		t.Error("relationship was not removed properly from the foreign struct")
	}
	if c.R.SecondaryExchange != nil {
		t.Error("relationship was not removed properly from the foreign struct")
	}
	if d.R.SecondaryExchange != &a {
		t.Error("relationship to a should have been preserved")
	}
	if e.R.SecondaryExchange != &a {
		t.Error("relationship to a should have been preserved")
	}

	if len(a.R.SecondaryExchangeDatahistoryjobs) != 2 {
		t.Error("should have preserved two relationships")
	}

	// Removal doesn't do a stable deletion for performance so we have to flip the order
	if a.R.SecondaryExchangeDatahistoryjobs[1] != &d {
		t.Error("relationship to d should have been preserved")
	}
	if a.R.SecondaryExchangeDatahistoryjobs[0] != &e {
		t.Error("relationship to e should have been preserved")
	}
}

func testExchangeToManyAddOpExchangeNameWithdrawalHistories(t *testing.T) {
	var err error

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()

	var a Exchange
	var b, c, d, e WithdrawalHistory

	seed := randomize.NewSeed()
	if err = randomize.Struct(seed, &a, exchangeDBTypes, false, strmangle.SetComplement(exchangePrimaryKeyColumns, exchangeColumnsWithoutDefault)...); err != nil {
		t.Fatal(err)
	}
	foreigners := []*WithdrawalHistory{&b, &c, &d, &e}
	for _, x := range foreigners {
		if err = randomize.Struct(seed, x, withdrawalHistoryDBTypes, false, strmangle.SetComplement(withdrawalHistoryPrimaryKeyColumns, withdrawalHistoryColumnsWithoutDefault)...); err != nil {
			t.Fatal(err)
		}
	}

	if err := a.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = b.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}
	if err = c.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Fatal(err)
	}

	foreignersSplitByInsertion := [][]*WithdrawalHistory{
		{&b, &c},
		{&d, &e},
	}

	for i, x := range foreignersSplitByInsertion {
		err = a.AddExchangeNameWithdrawalHistories(ctx, tx, i != 0, x...)
		if err != nil {
			t.Fatal(err)
		}

		first := x[0]
		second := x[1]

		if a.ID != first.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID, first.ExchangeNameID)
		}
		if a.ID != second.ExchangeNameID {
			t.Error("foreign key was wrong value", a.ID, second.ExchangeNameID)
		}

		if first.R.ExchangeName != &a {
			t.Error("relationship was not added properly to the foreign slice")
		}
		if second.R.ExchangeName != &a {
			t.Error("relationship was not added properly to the foreign slice")
		}

		if a.R.ExchangeNameWithdrawalHistories[i*2] != first {
			t.Error("relationship struct slice not set to correct value")
		}
		if a.R.ExchangeNameWithdrawalHistories[i*2+1] != second {
			t.Error("relationship struct slice not set to correct value")
		}

		count, err := a.ExchangeNameWithdrawalHistories().Count(ctx, tx)
		if err != nil {
			t.Fatal(err)
		}
		if want := int64((i + 1) * 2); count != want {
			t.Error("want", want, "got", count)
		}
	}
}

func testExchangesReload(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	if err = o.Reload(ctx, tx); err != nil {
		t.Error(err)
	}
}

func testExchangesReloadAll(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	slice := ExchangeSlice{o}

	if err = slice.ReloadAll(ctx, tx); err != nil {
		t.Error(err)
	}
}

func testExchangesSelect(t *testing.T) {
	t.Parallel()

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	slice, err := Exchanges().All(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if len(slice) != 1 {
		t.Error("want one record, got:", len(slice))
	}
}

var (
	exchangeDBTypes = map[string]string{`ID`: `TEXT`, `Name`: `TEXT`}
	_               = bytes.MinRead
)

func testExchangesUpdate(t *testing.T) {
	t.Parallel()

	if 0 == len(exchangePrimaryKeyColumns) {
		t.Skip("Skipping table with no primary key columns")
	}
	if len(exchangeAllColumns) == len(exchangePrimaryKeyColumns) {
		t.Skip("Skipping table with only primary key columns")
	}

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 1 {
		t.Error("want one record, got:", count)
	}

	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangePrimaryKeyColumns...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	if rowsAff, err := o.Update(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	} else if rowsAff != 1 {
		t.Error("should only affect one row but affected", rowsAff)
	}
}

func testExchangesSliceUpdateAll(t *testing.T) {
	t.Parallel()

	if len(exchangeAllColumns) == len(exchangePrimaryKeyColumns) {
		t.Skip("Skipping table with only primary key columns")
	}

	seed := randomize.NewSeed()
	var err error
	o := &Exchange{}
	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangeColumnsWithDefault...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	ctx := context.Background()
	tx := MustTx(boil.BeginTx(ctx, nil))
	defer func() { _ = tx.Rollback() }()
	if err = o.Insert(ctx, tx, boil.Infer()); err != nil {
		t.Error(err)
	}

	count, err := Exchanges().Count(ctx, tx)
	if err != nil {
		t.Error(err)
	}

	if count != 1 {
		t.Error("want one record, got:", count)
	}

	if err = randomize.Struct(seed, o, exchangeDBTypes, true, exchangePrimaryKeyColumns...); err != nil {
		t.Errorf("Unable to randomize Exchange struct: %s", err)
	}

	// Remove Primary keys and unique columns from what we plan to update
	var fields []string
	if strmangle.StringSliceMatch(exchangeAllColumns, exchangePrimaryKeyColumns) {
		fields = exchangeAllColumns
	} else {
		fields = strmangle.SetComplement(
			exchangeAllColumns,
			exchangePrimaryKeyColumns,
		)
	}

	value := reflect.Indirect(reflect.ValueOf(o))
	typ := reflect.TypeOf(o).Elem()
	n := typ.NumField()

	updateMap := M{}
	for _, col := range fields {
		for i := 0; i < n; i++ {
			f := typ.Field(i)
			if f.Tag.Get("boil") == col {
				updateMap[col] = value.Field(i).Interface()
			}
		}
	}

	slice := ExchangeSlice{o}
	if rowsAff, err := slice.UpdateAll(ctx, tx, updateMap); err != nil {
		t.Error(err)
	} else if rowsAff != 1 {
		t.Error("wanted one record updated but got", rowsAff)
	}
}


text:
[![Join the chat at https://gitter.im/Der-Eddy/phaser-school](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Der-Eddy/phaser-school?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Made with [Phaser Framework](https://github.com/photonstorm/phaser)

Live Demo: [Link](https://der-eddy.github.io/phaser-school/eddy.html)

Screenshot:
![screenshot](http://abload.de/img/2015-03-16195815paunn.png)


text:
import Polyglot from 'node-polyglot';

function createMiddleware(options) {
    options = options || {};
    return (req, res, next) => {
        req.polyglot = new Polyglot();
        if (typeof options === 'function') {
            var getPhrases = options;
            getPhrases((err, phrases) => {
                if (err) return next(err);
                req.polyglot.extend(phrases);
                return next();
            });
        }
        else {
            var phrases = typeof options === 'object' ? options : {};
            req.polyglot.extend(phrases);
            return next();
        }
    };
}

export default createMiddleware;


text:
#pragma once

#include <string>
#include <iostream>
#include <fstream>

#define P3D_DEFAULT_PLUGIN_LOG_FILENAME "p3dActiveXlog.log"

class PPLogger
{
public:
    PPLogger( );
    virtual ~PPLogger( );

    void Open( const std::string &rootDir );
    static std::ofstream& Log( ) { return m_logfile; }

protected:
  static bool m_isOpen;
  static std::ofstream m_logfile;
};

#define nout PPLogger::Log( )


text:
from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase

from .provider import StackExchangeProvider

class StackExchangeTests(OAuth2TestsMixin, TestCase):
    provider_id = StackExchangeProvider.id

    def get_mocked_response(self):
        return MockedResponse(200, """
        {
          "has_more": false,
           "items": [
              {
                "is_employee": false,
                 "last_access_date": 1356200390,
                 "display_name": "pennersr",
                 "account_id": 291652,
                 "badge_counts": {
                     "bronze": 2,
                     "silver": 2,
                     "gold": 0
                 },
                 "last_modified_date": 1356199552,
                 "profile_image": "http://www.gravatar.com/avatar/053d648486d567d3143d6bad8df8cfeb?d=identicon&r=PG",
                 "user_type": "registered",
                 "creation_date": 1296223711,
                 "reputation_change_quarter": 148,
                 "reputation_change_year": 378,
                 "reputation": 504,
                 "link": "http://stackoverflow.com/users/593944/pennersr",
                 "reputation_change_week": 0,
                 "user_id": 593944,
                 "reputation_change_month": 10,
                 "reputation_change_day": 0
              }
           ],
           "quota_max": 10000,
           "quota_remaining": 9999
        }""")


text:
namespace Sparrow.Pipelines
{
    public abstract class PipelineBase
    {
        public GameTime LastFrame { get; protected set; }
        public abstract void ProcessFrame(FrameState frame);
    }
}


text:
<?php

declare(strict_types = 1);

namespace KoolKode\Async\Stream;

use KoolKode\Async\AbstractPromise;
use KoolKode\Async\Context;
use KoolKode\Async\Promise;

class SyncReader implements ReadableStream
{
    use ReadableStreamTrait;

    protected $stream;

    protected $reads;

    public function __construct(ReadableStream $stream)
    {
        $this->stream = $stream;
        $this->reads = new \SplQueue();
    }

    /**
     * {@inheritdoc}
     */
    public function close(?\Throwable $e = null): void
    {
        $this->stream->close($e);
    }

    /**
     * {@inheritdoc}
     */
    public function read(Context $context, int $length = 8192): Promise
    {
        if ($length < 1) {
            throw new \InvalidArgumentException('Read length must be greater than 0, given ' . $length);
        }

        $start = $this->reads->isEmpty();
        $this->reads->enqueue($read = new SyncRead($context, $length));

        if ($start) {
            $this->executeRead();
        }

        return $context->keepBusy($read->promise());
    }

    /**
     * {@inheritdoc}
     */
    public function readBuffer(Context $context, int $length, bool $enforceLength = true): Promise
    {
        if ($length < 1) {
            throw new \InvalidArgumentException('Read length must be greater than 0, given ' . $length);
        }

        $start = $this->reads->isEmpty();
        $this->reads->enqueue($read = new SyncRead($context, $length, $enforceLength));

        if ($start) {
            $this->executeRead();
        }

        return $context->keepBusy($read->promise());
    }

    /**
     * {@inheritdoc}
     */
    public function readTo(Context $context, string $delimiter, int $length = 0xFFFF): Promise
    {
        $start = $this->reads->isEmpty();
        $this->reads->enqueue($read = new SyncRead($context, $length, $delimiter));

        if ($start) {
            $this->executeRead();
        }

        return $context->keepBusy($read->promise());
    }

    protected function executeRead(): void
    {
        while (!$this->reads->isEmpty()) {
            $read = $this->reads->bottom();

            if ($read->state & AbstractPromise::PENDING) {
                if (\is_string($read->arg)) {
                    $promise = $this->stream->readTo($read->context, $read->arg, $read->length);
                } elseif ($read->arg === null) {
                    $promise = $this->stream->read($read->context, $read->length);
                } else {
                    $promise = $this->stream->readBuffer($read->context, $read->length, $read->arg);
                }

                $done = false;

                $promise->when(function (?\Throwable $e, $v = null) use (& $done, $read) {
                    if ($e) {
                        $read->fail($e);
                    } else {
                        $read->resolve($v);
                    }

                    $this->reads->dequeue();

                    if ($done) {
                        $this->executeRead();
                    } else {
                        $done = true;
                    }
                });

                if (!$done) {
                    $done = true;

                    break;
                }
            }
        }
    }
}