human
Complete this python program:
def _do_batched_write_command(namespace, operation, command, docs, check_keys, opts, ctx):
assistant
#Here is the Python code you requested.

    """Execute a batch of insert, update, or delete commands.
    """
    max_bson_size = ctx.max_bson_size
    max_write_batch_size = ctx.max_write_batch_size
    max_cmd_size = (max_bson_size + _COMMAND_OVERHEAD)
    ordered = command.get('ordered', True)
    buf = StringIO()
    buf.write(_ZERO_64)
    buf.write('\x00\x00\x00\x00\xd4\x07\x00\x00')
    buf.write(_ZERO_32)
    buf.write(b(namespace))
    buf.write(_ZERO_8)
    buf.write(_SKIPLIM)
    command_start = buf.tell()
    buf.write(bson.BSON.encode(command))
    buf.seek((-1), 2)
    buf.truncate()
    try:
        buf.write(_OP_MAP[operation])
    except KeyError:
        raise InvalidOperation('Unknown    command')
    if (operation in (_UPDATE, _DELETE)):
        check_keys = False
    list_start = (buf.tell() - 4)
    to_send = []
    def send_message():
        'Finalize    and    send    the    current    OP_QUERY    message.\n                                '
        buf.write(_ZERO_16)
        length = buf.tell()
        buf.seek(list_start)
        buf.write(struct.pack('<i', ((length - list_start) - 1)))
        buf.seek(command_start)
        buf.write(struct.pack('<i', (length - command_start)))
        buf.seek(4)
        request_id = _randint()
        buf.write(struct.pack('<i', request_id))
        buf.seek(0)
        buf.write(struct.pack('<i', length))
        return ctx.write_command(request_id, buf.getvalue(), to_send)
    results = []
    idx = 0
    idx_offset = 0
    has_docs = False
    for doc in docs:
        has_docs = True
        key = b(str(idx))
        value = bson.BSON.encode(doc, check_keys, opts)
        enough_data = ((((buf.tell() + len(key)) + len(value)) + 2) >= max_cmd_size)
        enough_documents = (idx >= max_write_batch_size)
        if (enough_data or enough_documents):
            if (not idx):
                write_op = ('insert' if (operation == _INSERT) else None)
                _raise_document_too_large(write_op, len(value), max_bson_size)
            result = send_message()
            results.append((idx_offset, result))
            if (ordered and ('writeErrors'...