_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q22400 | _zlib_no_compress | train | def _zlib_no_compress(data):
"""Compress data with zlib level 0."""
cobj = zlib.compressobj(0)
return b"".join([cobj.compress(data), cobj.flush()]) | python | {
"resource": ""
} |
q22401 | _parse_codec_options | train | def _parse_codec_options(options):
"""Parse BSON codec options."""
return CodecOptions(
document_class=options.get(
'document_class', DEFAULT_CODEC_OPTIONS.document_class),
tz_aware=options.get(
'tz_aware', DEFAULT_CODEC_OPTIONS.tz_aware),
uuid_representation=opti... | python | {
"resource": ""
} |
q22402 | CodecOptions._arguments_repr | train | def _arguments_repr(self):
"""Representation of the arguments used to create this object."""
document_class_repr = (
'dict' if self.document_class is dict
else repr(self.document_class))
uuid_rep_repr = UUID_REPRESENTATION_NAMES.get(self.uuid_representation,
... | python | {
"resource": ""
} |
q22403 | _merge_command | train | def _merge_command(run, full_result, offset, result):
"""Merge a write command result into the full bulk result.
"""
affected = result.get("n", 0)
if run.op_type == _INSERT:
full_result["nInserted"] += affected
elif run.op_type == _DELETE:
full_result["nRemoved"] += affected
e... | python | {
"resource": ""
} |
q22404 | _raise_bulk_write_error | train | def _raise_bulk_write_error(full_result):
"""Raise a BulkWriteError from the full bulk api result.
"""
if full_result["writeErrors"]:
full_result["writeErrors"].sort(
key=lambda error: error["index"])
raise BulkWriteError(full_result) | python | {
"resource": ""
} |
q22405 | _Bulk.add_update | train | def add_update(self, selector, update, multi=False, upsert=False,
collation=None, array_filters=None):
"""Create an update document and add it to the list of ops.
"""
validate_ok_for_update(update)
cmd = SON([('q', selector), ('u', update),
('multi',... | python | {
"resource": ""
} |
q22406 | _Bulk.execute_insert_no_results | train | def execute_insert_no_results(self, sock_info, run, op_id, acknowledged):
"""Execute insert, returning no results.
"""
command = SON([('insert', self.collection.name),
('ordered', self.ordered)])
concern = {'w': int(self.ordered)}
command['writeConcern'] = ... | python | {
"resource": ""
} |
q22407 | _Bulk.execute_op_msg_no_results | train | def execute_op_msg_no_results(self, sock_info, generator):
"""Execute write commands with OP_MSG and w=0 writeConcern, unordered.
"""
db_name = self.collection.database.name
client = self.collection.database.client
listeners = client._event_listeners
op_id = _randint()
... | python | {
"resource": ""
} |
q22408 | _Bulk.execute_command_no_results | train | def execute_command_no_results(self, sock_info, generator):
"""Execute write commands with OP_MSG and w=0 WriteConcern, ordered.
"""
full_result = {
"writeErrors": [],
"writeConcernErrors": [],
"nInserted": 0,
"nUpserted": 0,
"nMatched"... | python | {
"resource": ""
} |
q22409 | Server.run_operation_with_response | train | def run_operation_with_response(
self,
sock_info,
operation,
set_slave_okay,
listeners,
exhaust,
unpack_res):
"""Run a _Query or _GetMore operation and return a Response object.
This method is used only to run _Query/_G... | python | {
"resource": ""
} |
q22410 | ServerDescription.retryable_writes_supported | train | def retryable_writes_supported(self):
"""Checks if this server supports retryable writes."""
return (
self._ls_timeout_minutes is not None and
self._server_type in (SERVER_TYPE.Mongos, SERVER_TYPE.RSPrimary)) | python | {
"resource": ""
} |
q22411 | _compress | train | def _compress(operation, data, ctx):
"""Takes message data, compresses it, and adds an OP_COMPRESSED header."""
compressed = ctx.compress(data)
request_id = _randint()
header = _pack_compression_header(
_COMPRESSION_HEADER_SIZE + len(compressed), # Total message length
request_id, # Req... | python | {
"resource": ""
} |
q22412 | _insert | train | def _insert(collection_name, docs, check_keys, flags, opts):
"""Get an OP_INSERT message"""
encode = _dict_to_bson # Make local. Uses extensions.
if len(docs) == 1:
encoded = encode(docs[0], check_keys, opts)
return b"".join([
b"\x00\x00\x00\x00", # Flags don't matter for one d... | python | {
"resource": ""
} |
q22413 | _insert_compressed | train | def _insert_compressed(
collection_name, docs, check_keys, continue_on_error, opts, ctx):
"""Internal compressed unacknowledged insert message helper."""
op_insert, max_bson_size = _insert(
collection_name, docs, check_keys, continue_on_error, opts)
rid, msg = _compress(2002, op_insert, ctx)... | python | {
"resource": ""
} |
q22414 | _insert_uncompressed | train | def _insert_uncompressed(collection_name, docs, check_keys,
safe, last_error_args, continue_on_error, opts):
"""Internal insert message helper."""
op_insert, max_bson_size = _insert(
collection_name, docs, check_keys, continue_on_error, opts)
rid, msg = __pack_message(2002, op_insert)
... | python | {
"resource": ""
} |
q22415 | _update | train | def _update(collection_name, upsert, multi, spec, doc, check_keys, opts):
"""Get an OP_UPDATE message."""
flags = 0
if upsert:
flags += 1
if multi:
flags += 2
encode = _dict_to_bson # Make local. Uses extensions.
encoded_update = encode(doc, check_keys, opts)
return b"".join... | python | {
"resource": ""
} |
q22416 | _update_compressed | train | def _update_compressed(
collection_name, upsert, multi, spec, doc, check_keys, opts, ctx):
"""Internal compressed unacknowledged update message helper."""
op_update, max_bson_size = _update(
collection_name, upsert, multi, spec, doc, check_keys, opts)
rid, msg = _compress(2001, op_update, ct... | python | {
"resource": ""
} |
q22417 | _update_uncompressed | train | def _update_uncompressed(collection_name, upsert, multi, spec,
doc, safe, last_error_args, check_keys, opts):
"""Internal update message helper."""
op_update, max_bson_size = _update(
collection_name, upsert, multi, spec, doc, check_keys, opts)
rid, msg = __pack_message(2001... | python | {
"resource": ""
} |
q22418 | _op_msg_compressed | train | def _op_msg_compressed(flags, command, identifier, docs, check_keys, opts,
ctx):
"""Internal OP_MSG message helper."""
msg, total_size, max_bson_size = _op_msg_no_header(
flags, command, identifier, docs, check_keys, opts)
rid, msg = _compress(2013, msg, ctx)
return rid, m... | python | {
"resource": ""
} |
q22419 | _op_msg_uncompressed | train | def _op_msg_uncompressed(flags, command, identifier, docs, check_keys, opts):
"""Internal compressed OP_MSG message helper."""
data, total_size, max_bson_size = _op_msg_no_header(
flags, command, identifier, docs, check_keys, opts)
request_id, op_message = __pack_message(2013, data)
return reque... | python | {
"resource": ""
} |
q22420 | _query | train | def _query(options, collection_name, num_to_skip,
num_to_return, query, field_selector, opts, check_keys):
"""Get an OP_QUERY message."""
encoded = _dict_to_bson(query, check_keys, opts)
if field_selector:
efs = _dict_to_bson(field_selector, False, opts)
else:
efs = b""
ma... | python | {
"resource": ""
} |
q22421 | _query_compressed | train | def _query_compressed(options, collection_name, num_to_skip,
num_to_return, query, field_selector,
opts, check_keys=False, ctx=None):
"""Internal compressed query message helper."""
op_query, max_bson_size = _query(
options,
collection_name,
nu... | python | {
"resource": ""
} |
q22422 | _query_uncompressed | train | def _query_uncompressed(options, collection_name, num_to_skip,
num_to_return, query, field_selector, opts, check_keys=False):
"""Internal query message helper."""
op_query, max_bson_size = _query(
options,
collection_name,
num_to_skip,
num_to_return,
query,
... | python | {
"resource": ""
} |
q22423 | _get_more | train | def _get_more(collection_name, num_to_return, cursor_id):
"""Get an OP_GET_MORE message."""
return b"".join([
_ZERO_32,
_make_c_string(collection_name),
_pack_int(num_to_return),
_pack_long_long(cursor_id)]) | python | {
"resource": ""
} |
q22424 | _get_more_compressed | train | def _get_more_compressed(collection_name, num_to_return, cursor_id, ctx):
"""Internal compressed getMore message helper."""
return _compress(
2005, _get_more(collection_name, num_to_return, cursor_id), ctx) | python | {
"resource": ""
} |
q22425 | _delete | train | def _delete(collection_name, spec, opts, flags):
"""Get an OP_DELETE message."""
encoded = _dict_to_bson(spec, False, opts) # Uses extensions.
return b"".join([
_ZERO_32,
_make_c_string(collection_name),
_pack_int(flags),
encoded]), len(encoded) | python | {
"resource": ""
} |
q22426 | _delete_compressed | train | def _delete_compressed(collection_name, spec, opts, flags, ctx):
"""Internal compressed unacknowledged delete message helper."""
op_delete, max_bson_size = _delete(collection_name, spec, opts, flags)
rid, msg = _compress(2006, op_delete, ctx)
return rid, msg, max_bson_size | python | {
"resource": ""
} |
q22427 | _delete_uncompressed | train | def _delete_uncompressed(
collection_name, spec, safe, last_error_args, opts, flags=0):
"""Internal delete message helper."""
op_delete, max_bson_size = _delete(collection_name, spec, opts, flags)
rid, msg = __pack_message(2006, op_delete)
if safe:
rid, gle, _ = __last_error(collection_n... | python | {
"resource": ""
} |
q22428 | _raise_document_too_large | train | def _raise_document_too_large(operation, doc_size, max_size):
"""Internal helper for raising DocumentTooLarge."""
if operation == "insert":
raise DocumentTooLarge("BSON document too large (%d bytes)"
" - the connected server supports"
" BSON ... | python | {
"resource": ""
} |
q22429 | _do_batched_insert | train | def _do_batched_insert(collection_name, docs, check_keys,
safe, last_error_args, continue_on_error, opts,
ctx):
"""Insert `docs` using multiple batches.
"""
def _insert_message(insert_message, send_safe):
"""Build the insert message with header and GLE.
... | python | {
"resource": ""
} |
q22430 | _batched_op_msg_impl | train | def _batched_op_msg_impl(
operation, command, docs, check_keys, ack, opts, ctx, buf):
"""Create a batched OP_MSG write."""
max_bson_size = ctx.max_bson_size
max_write_batch_size = ctx.max_write_batch_size
max_message_size = ctx.max_message_size
flags = b"\x00\x00\x00\x00" if ack else b"\x02... | python | {
"resource": ""
} |
q22431 | _encode_batched_op_msg | train | def _encode_batched_op_msg(
operation, command, docs, check_keys, ack, opts, ctx):
"""Encode the next batched insert, update, or delete operation
as OP_MSG.
"""
buf = StringIO()
to_send, _ = _batched_op_msg_impl(
operation, command, docs, check_keys, ack, opts, ctx, buf)
return ... | python | {
"resource": ""
} |
q22432 | _batched_op_msg_compressed | train | def _batched_op_msg_compressed(
operation, command, docs, check_keys, ack, opts, ctx):
"""Create the next batched insert, update, or delete operation
with OP_MSG, compressed.
"""
data, to_send = _encode_batched_op_msg(
operation, command, docs, check_keys, ack, opts, ctx)
request_id... | python | {
"resource": ""
} |
q22433 | _batched_op_msg | train | def _batched_op_msg(
operation, command, docs, check_keys, ack, opts, ctx):
"""OP_MSG implementation entry point."""
buf = StringIO()
# Save space for message length and request id
buf.write(_ZERO_64)
# responseTo, opCode
buf.write(b"\x00\x00\x00\x00\xdd\x07\x00\x00")
to_send, leng... | python | {
"resource": ""
} |
q22434 | _do_batched_op_msg | train | def _do_batched_op_msg(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Create the next batched insert, update, or delete operation
using OP_MSG.
"""
command['$db'] = namespace.split('.', 1)[0]
if 'writeConcern' in command:
ack = bool(command['writeConcern'].get('w', ... | python | {
"resource": ""
} |
q22435 | _batched_write_command_compressed | train | def _batched_write_command_compressed(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Create the next batched insert, update, or delete command, compressed.
"""
data, to_send = _encode_batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx)
re... | python | {
"resource": ""
} |
q22436 | _encode_batched_write_command | train | def _encode_batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Encode the next batched insert, update, or delete command.
"""
buf = StringIO()
to_send, _ = _batched_write_command_impl(
namespace, operation, command, docs, check_keys, opts, ctx, buf)
... | python | {
"resource": ""
} |
q22437 | _batched_write_command | train | def _batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Create the next batched insert, update, or delete command.
"""
buf = StringIO()
# Save space for message length and request id
buf.write(_ZERO_64)
# responseTo, opCode
buf.write(b"\x00\x00\x0... | python | {
"resource": ""
} |
q22438 | _do_batched_write_command | train | def _do_batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Batched write commands entry point."""
if ctx.sock_info.compression_context:
return _batched_write_command_compressed(
namespace, operation, command, docs, check_keys, opts, ctx)
return... | python | {
"resource": ""
} |
q22439 | _do_bulk_write_command | train | def _do_bulk_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Bulk write commands entry point."""
if ctx.sock_info.max_wire_version > 5:
return _do_batched_op_msg(
namespace, operation, command, docs, check_keys, opts, ctx)
return _do_batched_write_c... | python | {
"resource": ""
} |
q22440 | _batched_write_command_impl | train | def _batched_write_command_impl(
namespace, operation, command, docs, check_keys, opts, ctx, buf):
"""Create a batched OP_QUERY write command."""
max_bson_size = ctx.max_bson_size
max_write_batch_size = ctx.max_write_batch_size
# Max BSON object size + 16k - 2 bytes for ending NUL bytes.
# S... | python | {
"resource": ""
} |
q22441 | _OpReply.raw_response | train | def raw_response(self, cursor_id=None):
"""Check the response header from the database, without decoding BSON.
Check the response for errors and unpack.
Can raise CursorNotFound, NotMasterError, ExecutionTimeout, or
OperationFailure.
:Parameters:
- `cursor_id` (optio... | python | {
"resource": ""
} |
q22442 | _OpReply.unpack | train | def unpack(cls, msg):
"""Construct an _OpReply from raw bytes."""
# PYTHON-945: ignore starting_from field.
flags, cursor_id, _, number_returned = cls.UNPACK_FROM(msg)
# Convert Python 3 memoryview to bytes. Note we should call
# memoryview.tobytes() if we start using memoryview... | python | {
"resource": ""
} |
q22443 | _OpMsg.unpack_response | train | def unpack_response(self, cursor_id=None,
codec_options=_UNICODE_REPLACE_CODEC_OPTIONS,
user_fields=None, legacy_response=False):
"""Unpack a OP_MSG command response.
:Parameters:
- `cursor_id` (optional): Ignored, for compatibility with _OpRepl... | python | {
"resource": ""
} |
q22444 | _OpMsg.unpack | train | def unpack(cls, msg):
"""Construct an _OpMsg from raw bytes."""
flags, first_payload_type, first_payload_size = cls.UNPACK_FROM(msg)
if flags != 0:
raise ProtocolError("Unsupported OP_MSG flags (%r)" % (flags,))
if first_payload_type != 0:
raise ProtocolError(
... | python | {
"resource": ""
} |
q22445 | TopologyDescription.has_known_servers | train | def has_known_servers(self):
"""Whether there are any Servers of types besides Unknown."""
return any(s for s in self._server_descriptions.values()
if s.is_server_type_known) | python | {
"resource": ""
} |
q22446 | MongoClient._cache_index | train | def _cache_index(self, dbname, collection, index, cache_for):
"""Add an index to the index cache for ensure_index operations."""
now = datetime.datetime.utcnow()
expire = datetime.timedelta(seconds=cache_for) + now
with self.__index_cache_lock:
if dbname not in self.__index_... | python | {
"resource": ""
} |
q22447 | MongoClient.close | train | def close(self):
"""Cleanup client resources and disconnect from MongoDB.
On MongoDB >= 3.6, end all server sessions created by this client by
sending one or more endSessions commands.
Close all sockets in the connection pools and stop the monitor threads.
If this instance is u... | python | {
"resource": ""
} |
q22448 | MongoClient._select_server | train | def _select_server(self, server_selector, session, address=None):
"""Select a server to run an operation on this client.
:Parameters:
- `server_selector`: The server selector to use if the session is
not pinned and no address is given.
- `session`: The ClientSession for ... | python | {
"resource": ""
} |
q22449 | MongoClient._reset_on_error | train | def _reset_on_error(self, server_address, session):
"""On "not master" or "node is recovering" errors reset the server
according to the SDAM spec.
Unpin the session on transient transaction errors.
"""
try:
try:
yield
except PyMongoError a... | python | {
"resource": ""
} |
q22450 | MongoClient._retryable_write | train | def _retryable_write(self, retryable, func, session):
"""Internal retryable write helper."""
with self._tmp_session(session) as s:
return self._retry_with_session(retryable, func, s, None) | python | {
"resource": ""
} |
q22451 | MongoClient.close_cursor | train | def close_cursor(self, cursor_id, address=None):
"""DEPRECATED - Send a kill cursors message soon with the given id.
Raises :class:`TypeError` if `cursor_id` is not an instance of
``(int, long)``. What closing the cursor actually means
depends on this client's cursor manager.
T... | python | {
"resource": ""
} |
q22452 | MongoClient._kill_cursors | train | def _kill_cursors(self, cursor_ids, address, topology, session):
"""Send a kill cursors message with the given ids."""
listeners = self._event_listeners
publish = listeners.enabled_for_commands
if address:
# address could be a tuple or _CursorAddress, but
# select... | python | {
"resource": ""
} |
q22453 | MongoClient._process_periodic_tasks | train | def _process_periodic_tasks(self):
"""Process any pending kill cursors requests and
maintain connection pool parameters."""
address_to_cursor_ids = defaultdict(list)
# Other threads or the GC may append to the queue concurrently.
while True:
try:
addr... | python | {
"resource": ""
} |
q22454 | MongoClient.start_session | train | def start_session(self,
causal_consistency=True,
default_transaction_options=None):
"""Start a logical session.
This method takes the same parameters as
:class:`~pymongo.client_session.SessionOptions`. See the
:mod:`~pymongo.client_session` mo... | python | {
"resource": ""
} |
q22455 | MongoClient.server_info | train | def server_info(self, session=None):
"""Get information about the MongoDB server we're connected to.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter.
"""
... | python | {
"resource": ""
} |
q22456 | MongoClient.list_databases | train | def list_databases(self, session=None, **kwargs):
"""Get a cursor over the databases of the connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
- `**kwargs` (optional): Optional parameters of the
`listDatab... | python | {
"resource": ""
} |
q22457 | MongoClient.list_database_names | train | def list_database_names(self, session=None):
"""Get a list of the names of all databases on the connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionadded:: 3.6
"""
return [doc["name"]
... | python | {
"resource": ""
} |
q22458 | MongoClient.get_default_database | train | def get_default_database(self, default=None, codec_options=None,
read_preference=None, write_concern=None, read_concern=None):
"""Get the database named in the MongoDB connection URI.
>>> uri = 'mongodb://host/my_database'
>>> client = MongoClient(uri)
>>> db = client.get_de... | python | {
"resource": ""
} |
q22459 | MongoClient._database_default_options | train | def _database_default_options(self, name):
"""Get a Database instance with the default settings."""
return self.get_database(
name, codec_options=DEFAULT_CODEC_OPTIONS,
read_preference=ReadPreference.PRIMARY,
write_concern=DEFAULT_WRITE_CONCERN) | python | {
"resource": ""
} |
q22460 | _handle_option_deprecations | train | def _handle_option_deprecations(options):
"""Issue appropriate warnings when deprecated options are present in the
options dictionary. Removes deprecated option key, value pairs if the
options dictionary is found to also have the renamed option."""
undeprecated_options = _CaseInsensitiveDictionary()
... | python | {
"resource": ""
} |
q22461 | _normalize_options | train | def _normalize_options(options):
"""Renames keys in the options dictionary to their internally-used
names."""
normalized_options = {}
for key, value in iteritems(options):
optname = str(key).lower()
intname = INTERNAL_URI_OPTION_NAME_MAP.get(optname, key)
normalized_options[intna... | python | {
"resource": ""
} |
q22462 | split_options | train | def split_options(opts, validate=True, warn=False, normalize=True):
"""Takes the options portion of a MongoDB URI, validates each option
and returns the options in a dictionary.
:Parameters:
- `opt`: A string representing MongoDB URI options.
- `validate`: If ``True`` (the default), validat... | python | {
"resource": ""
} |
q22463 | GridFS.new_file | train | def new_file(self, **kwargs):
"""Create a new file in GridFS.
Returns a new :class:`~gridfs.grid_file.GridIn` instance to
which data can be written. Any keyword arguments will be
passed through to :meth:`~gridfs.grid_file.GridIn`.
If the ``"_id"`` of the file is manually specif... | python | {
"resource": ""
} |
q22464 | GridFS.get_version | train | def get_version(self, filename=None, version=-1, session=None, **kwargs):
"""Get a file from GridFS by ``"filename"`` or metadata fields.
Returns a version of the file in GridFS whose filename matches
`filename` and whose metadata fields match the supplied keyword
arguments, as an insta... | python | {
"resource": ""
} |
q22465 | GridFS.get_last_version | train | def get_last_version(self, filename=None, session=None, **kwargs):
"""Get the most recent version of a file in GridFS by ``"filename"``
or metadata fields.
Equivalent to calling :meth:`get_version` with the default
`version` (``-1``).
:Parameters:
- `filename`: ``"fil... | python | {
"resource": ""
} |
q22466 | GridFSBucket.upload_from_stream | train | def upload_from_stream(self, filename, source, chunk_size_bytes=None,
metadata=None, session=None):
"""Uploads a user file to a GridFS bucket.
Reads the contents of the user file from `source` and uploads
it to the file `filename`. Source can be a string or file-like ... | python | {
"resource": ""
} |
q22467 | GridFSBucket.rename | train | def rename(self, file_id, new_filename, session=None):
"""Renames the stored file with the specified file_id.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
# Get _id of file to rename
file_id = fs.upload_from_stream("test_file", "data I want ... | python | {
"resource": ""
} |
q22468 | Database.with_options | train | def with_options(self, codec_options=None, read_preference=None,
write_concern=None, read_concern=None):
"""Get a clone of this database changing the specified settings.
>>> db1.read_preference
Primary()
>>> from pymongo import ReadPreference
>>> db2... | python | {
"resource": ""
} |
q22469 | Database.watch | train | def watch(self, pipeline=None, full_document='default', resume_after=None,
max_await_time_ms=None, batch_size=None, collation=None,
start_at_operation_time=None, session=None):
"""Watch changes on this database.
Performs an aggregation with an implicit initial ``$changeStrea... | python | {
"resource": ""
} |
q22470 | Database._retryable_read_command | train | def _retryable_read_command(self, command, value=1, check=True,
allowable_errors=None, read_preference=None,
codec_options=DEFAULT_CODEC_OPTIONS, session=None, **kwargs):
"""Same as command but used for retryable read commands."""
if read_preference is None:
r... | python | {
"resource": ""
} |
q22471 | Database.list_collections | train | def list_collections(self, session=None, filter=None, **kwargs):
"""Get a cursor over the collectons of this database.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
- `filter` (optional): A query document to filter the list of
... | python | {
"resource": ""
} |
q22472 | Database.validate_collection | train | def validate_collection(self, name_or_collection,
scandata=False, full=False, session=None):
"""Validate a collection.
Returns a dict of validation info. Raises CollectionInvalid if
validation fails.
:Parameters:
- `name_or_collection`: A Collectio... | python | {
"resource": ""
} |
q22473 | Database.profiling_level | train | def profiling_level(self, session=None):
"""Get the database's current profiling level.
Returns one of (:data:`~pymongo.OFF`,
:data:`~pymongo.SLOW_ONLY`, :data:`~pymongo.ALL`).
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
... | python | {
"resource": ""
} |
q22474 | Database.set_profiling_level | train | def set_profiling_level(self, level, slow_ms=None, session=None):
"""Set the database's profiling level.
:Parameters:
- `level`: Specifies a profiling level, see list of possible values
below.
- `slow_ms`: Optionally modify the threshold for the profile to
co... | python | {
"resource": ""
} |
q22475 | CommandCursor._try_next | train | def _try_next(self, get_more_allowed):
"""Advance the cursor blocking for at most one getMore command."""
if not len(self.__data) and not self.__killed and get_more_allowed:
self._refresh()
if len(self.__data):
coll = self.__collection
return coll.database._fi... | python | {
"resource": ""
} |
q22476 | ObjectId._random | train | def _random(cls):
"""Generate a 5-byte random number once per process.
"""
pid = os.getpid()
if pid != cls._pid:
cls._pid = pid
cls.__random = _random_bytes()
return cls.__random | python | {
"resource": ""
} |
q22477 | SocketInfo.command | train | def command(self, dbname, spec, slave_ok=False,
read_preference=ReadPreference.PRIMARY,
codec_options=DEFAULT_CODEC_OPTIONS, check=True,
allowable_errors=None, check_keys=False,
read_concern=None,
write_concern=None,
parse_w... | python | {
"resource": ""
} |
q22478 | SocketInfo.validate_session | train | def validate_session(self, client, session):
"""Validate this session before use with client.
Raises error if this session is logged in as a different user or
the client is not the one that created the session.
"""
if session:
if session._client is not client:
... | python | {
"resource": ""
} |
q22479 | SocketInfo.send_cluster_time | train | def send_cluster_time(self, command, session, client):
"""Add cluster time for MongoDB >= 3.6."""
if self.max_wire_version >= 6 and client:
client._send_cluster_time(command, session) | python | {
"resource": ""
} |
q22480 | Pool.remove_stale_sockets | train | def remove_stale_sockets(self):
"""Removes stale sockets then adds new ones if pool is too small."""
if self.opts.max_idle_time_seconds is not None:
with self.lock:
while (self.sockets and
self.sockets[-1].idle_time_seconds() > self.opts.max_idle_time_s... | python | {
"resource": ""
} |
q22481 | SocketChecker.socket_closed | train | def socket_closed(self, sock):
"""Return True if we know socket has been closed, False otherwise.
"""
while True:
try:
if self._poller:
with self._lock:
self._poller.register(sock, _EVENT_MASK)
try:
... | python | {
"resource": ""
} |
q22482 | _get_object_size | train | def _get_object_size(data, position, obj_end):
"""Validate and return a BSON document's size."""
try:
obj_size = _UNPACK_INT(data[position:position + 4])[0]
except struct.error as exc:
raise InvalidBSON(str(exc))
end = position + obj_size - 1
if data[end:end + 1] != b"\x00":
... | python | {
"resource": ""
} |
q22483 | _elements_to_dict | train | def _elements_to_dict(data, position, obj_end, opts, result=None):
"""Decode a BSON document into result."""
if result is None:
result = opts.document_class()
end = obj_end - 1
while position < end:
key, value, position = _element_to_dict(data, position, obj_end, opts)
result[key... | python | {
"resource": ""
} |
q22484 | _datetime_to_millis | train | def _datetime_to_millis(dtm):
"""Convert datetime to milliseconds since epoch UTC."""
if dtm.utcoffset() is not None:
dtm = dtm - dtm.utcoffset()
return int(calendar.timegm(dtm.timetuple()) * 1000 +
dtm.microsecond // 1000) | python | {
"resource": ""
} |
q22485 | _decode_all_selective | train | def _decode_all_selective(data, codec_options, fields):
"""Decode BSON data to a single document while using user-provided
custom decoding logic.
`data` must be a string representing a valid, BSON-encoded document.
:Parameters:
- `data`: BSON data
- `codec_options`: An instance of
... | python | {
"resource": ""
} |
q22486 | _validate_session_write_concern | train | def _validate_session_write_concern(session, write_concern):
"""Validate that an explicit session is not used with an unack'ed write.
Returns the session to use for the next operation.
"""
if session:
if write_concern is not None and not write_concern.acknowledged:
# For unacknowled... | python | {
"resource": ""
} |
q22487 | ClientSession._inherit_option | train | def _inherit_option(self, name, val):
"""Return the inherited TransactionOption value."""
if val:
return val
txn_opts = self.options.default_transaction_options
val = txn_opts and getattr(txn_opts, name)
if val:
return val
return getattr(self.clien... | python | {
"resource": ""
} |
q22488 | ClientSession.with_transaction | train | def with_transaction(self, callback, read_concern=None, write_concern=None,
read_preference=None):
"""Execute a callback in a transaction.
This method starts a transaction on this session, executes ``callback``
once, and then commits the transaction. For example::
... | python | {
"resource": ""
} |
q22489 | ClientSession.commit_transaction | train | def commit_transaction(self):
"""Commit a multi-statement transaction.
.. versionadded:: 3.7
"""
self._check_ended()
retry = False
state = self._transaction.state
if state is _TxnState.NONE:
raise InvalidOperation("No transaction started")
eli... | python | {
"resource": ""
} |
q22490 | ClientSession.abort_transaction | train | def abort_transaction(self):
"""Abort a multi-statement transaction.
.. versionadded:: 3.7
"""
self._check_ended()
state = self._transaction.state
if state is _TxnState.NONE:
raise InvalidOperation("No transaction started")
elif state is _TxnState.ST... | python | {
"resource": ""
} |
q22491 | ClientSession._finish_transaction_with_retry | train | def _finish_transaction_with_retry(self, command_name, explict_retry):
"""Run commit or abort with one retry after any retryable error.
:Parameters:
- `command_name`: Either "commitTransaction" or "abortTransaction".
- `explict_retry`: True when this is an explict commit retry attem... | python | {
"resource": ""
} |
q22492 | ClientSession._advance_cluster_time | train | def _advance_cluster_time(self, cluster_time):
"""Internal cluster time helper."""
if self._cluster_time is None:
self._cluster_time = cluster_time
elif cluster_time is not None:
if cluster_time["clusterTime"] > self._cluster_time["clusterTime"]:
self._clu... | python | {
"resource": ""
} |
q22493 | ClientSession.advance_cluster_time | train | def advance_cluster_time(self, cluster_time):
"""Update the cluster time for this session.
:Parameters:
- `cluster_time`: The
:data:`~pymongo.client_session.ClientSession.cluster_time` from
another `ClientSession` instance.
"""
if not isinstance(cluster... | python | {
"resource": ""
} |
q22494 | ClientSession._advance_operation_time | train | def _advance_operation_time(self, operation_time):
"""Internal operation time helper."""
if self._operation_time is None:
self._operation_time = operation_time
elif operation_time is not None:
if operation_time > self._operation_time:
self._operation_time ... | python | {
"resource": ""
} |
q22495 | ClientSession.advance_operation_time | train | def advance_operation_time(self, operation_time):
"""Update the operation time for this session.
:Parameters:
- `operation_time`: The
:data:`~pymongo.client_session.ClientSession.operation_time` from
another `ClientSession` instance.
"""
if not isinstan... | python | {
"resource": ""
} |
q22496 | ClientSession._process_response | train | def _process_response(self, reply):
"""Process a response to a command that was run with this session."""
self._advance_cluster_time(reply.get('$clusterTime'))
self._advance_operation_time(reply.get('operationTime'))
if self._in_transaction and self._transaction.sharded:
reco... | python | {
"resource": ""
} |
q22497 | ClientSession._pin_mongos | train | def _pin_mongos(self, server):
"""Pin this session to the given mongos Server."""
self._transaction.sharded = True
self._transaction.pinned_address = server.description.address | python | {
"resource": ""
} |
q22498 | _parse_write_concern | train | def _parse_write_concern(options):
"""Parse write concern options."""
concern = options.get('w')
wtimeout = options.get('wtimeoutms')
j = options.get('journal')
fsync = options.get('fsync')
return WriteConcern(concern, wtimeout, j, fsync) | python | {
"resource": ""
} |
q22499 | _parse_ssl_options | train | def _parse_ssl_options(options):
"""Parse ssl options."""
use_ssl = options.get('ssl')
if use_ssl is not None:
validate_boolean('ssl', use_ssl)
certfile = options.get('ssl_certfile')
keyfile = options.get('ssl_keyfile')
passphrase = options.get('ssl_pem_passphrase')
ca_certs = optio... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.