_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q251600 | PlyProperty._read_bin | train | def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
| python | {
"resource": ""
} |
q251601 | color_stream_st | train | def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs):
"""
Read filenames from the input stream and detect their palette.
"""
for line in istream:
filename = line.strip()
try:
palette = extract_colors(filename, **kwargs)
except Exception | python | {
"resource": ""
} |
q251602 | color_stream_mt | train | def color_stream_mt(istream=sys.stdin, n=config.N_PROCESSES, **kwargs):
"""
Read filenames from the input stream and detect their palette using
multiple processes.
"""
queue = multiprocessing.Queue(1000)
lock = multiprocessing.Lock()
pool = [multiprocessing.Process(target=color_process, arg... | python | {
"resource": ""
} |
q251603 | color_process | train | def color_process(queue, lock):
"Receive filenames and get the colors from their images."
while True:
block = queue.get()
if block == config.SENTINEL:
break
for filename in block:
| python | {
"resource": ""
} |
q251604 | extract_colors | train | def extract_colors(
filename_or_img, min_saturation=config.MIN_SATURATION,
min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS,
min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED):
"""
Determine what the major colors are in the given image.
"""
if Ima... | python | {
"resource": ""
} |
q251605 | save_palette_as_image | train | def save_palette_as_image(filename, palette):
"Save palette as a PNG with labeled, colored blocks"
output_filename = '%s_palette.png' % filename[:filename.rfind('.')]
size = (80 * len(palette.colors), 80)
im = Image.new('RGB', size)
draw = ImageDraw.Draw(im)
for i, c in enumerate(palette.colors)... | python | {
"resource": ""
} |
q251606 | autocrop | train | def autocrop(im, bgcolor):
"Crop away a border of the given background color."
if im.mode != "RGB":
im = im.convert("RGB")
| python | {
"resource": ""
} |
q251607 | convert_to_influx | train | def convert_to_influx(mac, payload):
'''
Convert data into RuuviCollector naming schme and scale
returns:
Object to be written to InfluxDB
'''
dataFormat = payload["data_format"] if ('data_format' in payload) else None
fields = {}
fields["temperature"] = payload["tempe... | python | {
"resource": ""
} |
q251608 | _run_get_data_background | train | def _run_get_data_background(macs, queue, shared_data, bt_device):
"""
Background process function for RuuviTag Sensors
"""
run_flag = RunFlag()
def add_data(data):
if not shared_data['run_flag']:
run_flag.running = False
| python | {
"resource": ""
} |
q251609 | RuuviTagReactive._data_update | train | def _data_update(subjects, queue, run_flag):
"""
Get data from backgound process and notify all subscribed observers with the new data
"""
while run_flag.running:
while not queue.empty():
| python | {
"resource": ""
} |
q251610 | data_update | train | async def data_update(queue):
"""
Update data sent by the background process to global allData variable
"""
global allData
while True:
while not queue.empty():
data = queue.get()
allData[data[0]] = data[1]
| python | {
"resource": ""
} |
q251611 | RuuviTagSensor.convert_data | train | def convert_data(raw):
"""
Validate that data is from RuuviTag and get correct data part.
Returns:
tuple (int, string): Data Format type and Sensor data
"""
# TODO: Check from raw data correct data format
# Now this returns 2 also for Data Format 4
da... | python | {
"resource": ""
} |
q251612 | RuuviTagSensor.find_ruuvitags | train | def find_ruuvitags(bt_device=''):
"""
Find all RuuviTags. Function will print the mac and the state of the sensors when found.
Function will execute as long as it is stopped. Stop ecexution with Crtl+C.
Returns:
dict: MAC and state of found sensors
"""
log.i... | python | {
"resource": ""
} |
q251613 | RuuviTagSensor.get_data_for_sensors | train | def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''):
"""
Get lates data for sensors in the MAC's list.
Args:
macs (array): MAC addresses
search_duratio_sec (int): Search duration in seconds. Default 5
bt_device (string): Bluetooth device id
... | python | {
"resource": ""
} |
q251614 | RuuviTagSensor.get_datas | train | def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''):
"""
Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object)... | python | {
"resource": ""
} |
q251615 | RuuviTagSensor._get_ruuvitag_datas | train | def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''):
"""
Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Defa... | python | {
"resource": ""
} |
q251616 | RuuviTag.update | train | def update(self):
"""
Get lates data from the sensor and update own state.
Returns:
dict: Latest state
"""
(data_format, data) = RuuviTagSensor.get_data(self._mac, self._bt_device)
if data == self._data:
return self._state
| python | {
"resource": ""
} |
q251617 | write_to_influxdb | train | def write_to_influxdb(received_data):
'''
Convert data into RuuviCollecor naming schme and scale
'''
dataFormat = received_data[1]["data_format"] if ('data_format' in received_data[1]) else None
fields = {}
fields["temperature"] = received_data[1]["temperature"] if ('temperature' i... | python | {
"resource": ""
} |
q251618 | update_data | train | def update_data():
"""
Update data sent by background process to global allData
"""
global allData
while not q.empty():
allData = q.get() | python | {
"resource": ""
} |
q251619 | Df5Decoder._get_acceleration | train | def _get_acceleration(self, data):
'''Return acceleration mG'''
if (data[7:8] == 0x7FFF or
data[9:10] == 0x7FFF or
data[11:12] == 0x7FFF):
return (None, None, None)
acc_x = twos_complement((data[7] << 8) + data[8], 16)
| python | {
"resource": ""
} |
q251620 | Df5Decoder._get_powerinfo | train | def _get_powerinfo(self, data):
'''Return battery voltage and tx power '''
power_info = (data[13] & 0xFF) << 8 | (data[14] & 0xFF)
battery_voltage = rshift(power_info, 5) + 1600
tx_power = (power_info & 0b11111) * 2 - 40
if rshift(power_info, 5) == 0b11111111111:
| python | {
"resource": ""
} |
q251621 | split_key | train | def split_key(key, max_keys=0):
"""Splits a key but allows dots in the key name if they're scaped properly.
Splitting this complex key:
complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme."
split_key(complex_key)
results in:
['', 'dont\.splitme', 'd\.o\. origen', 'splitme\... | python | {
"resource": ""
} |
q251622 | DottedList.to_python | train | def to_python(self):
"""Returns a plain python list and converts to plain python objects all
this object's descendants.
"""
result = list(self)
for index, value in enumerate(result):
| python | {
"resource": ""
} |
q251623 | DottedDict.to_python | train | def to_python(self):
"""Returns a plain python dict and converts to plain python objects all
this object's descendants.
"""
result = dict(self)
for key, value in iteritems(result):
| python | {
"resource": ""
} |
q251624 | IRCClient.handle_nick | train | def handle_nick(self, params):
"""
Handle the initial setting of the user's nickname and nick changes.
"""
nick = params
# Valid nickname?
if re.search(r'[^a-zA-Z0-9\-\[\]\'`^{}_]', nick):
raise IRCError.from_name('erroneusnickname', ':%s' % nick)
if... | python | {
"resource": ""
} |
q251625 | IRCClient.handle_user | train | def handle_user(self, params):
"""
Handle the USER command which identifies the user to the server.
"""
params = params.split(' ', 3)
if len(params) != 4:
raise IRCError.from_name(
'needmoreparams',
| python | {
"resource": ""
} |
q251626 | IRCClient.handle_privmsg | train | def handle_privmsg(self, params):
"""
Handle sending a private message to a user or channel.
"""
target, sep, msg = params.partition(' ')
if not msg:
raise IRCError.from_name(
'needmoreparams',
'PRIVMSG :Not enough parameters')
... | python | {
"resource": ""
} |
q251627 | IRCClient._send_to_others | train | def _send_to_others(self, message, channel):
"""
Send the message to all clients in the specified channel except for
self.
"""
other_clients = [
client for client | python | {
"resource": ""
} |
q251628 | IRCClient.handle_topic | train | def handle_topic(self, params):
"""
Handle a topic command.
"""
channel_name, sep, topic = params.partition(' ')
channel = self.server.channels.get(channel_name)
if not channel:
raise IRCError.from_name(
'nosuchnick', 'PRIVMSG :%s' % channel_n... | python | {
"resource": ""
} |
q251629 | IRCClient.handle_quit | train | def handle_quit(self, params):
"""
Handle the client breaking off the connection with a QUIT command.
"""
response = ':%s QUIT :%s' % (self.client_ident(), params.lstrip(':'))
# Send quit message to all clients in all channels user is in, and
# remove the user from the | python | {
"resource": ""
} |
q251630 | IRCClient.handle_dump | train | def handle_dump(self, params):
"""
Dump internal server information for debugging purposes.
"""
print("Clients:", self.server.clients)
for client in self.server.clients.values():
print(" ", client)
for channel in client.channels.values():
p... | python | {
"resource": ""
} |
q251631 | IRCClient.client_ident | train | def client_ident(self):
"""
Return the client identifier as included in many command replies.
"""
| python | {
"resource": ""
} |
q251632 | IRCClient.finish | train | def finish(self):
"""
The client conection is finished. Do some cleanup to ensure that the
client doesn't linger around in any channel or the client list, in case
the client didn't properly close the connection with PART and QUIT.
"""
log.info('Client disconnected: %s', s... | python | {
"resource": ""
} |
q251633 | AioConnection.send_raw | train | def send_raw(self, string):
"""Send raw string to the server, via the asyncio transport.
The string will be padded with appropriate CR LF.
"""
log.debug('RAW: {}'.format(string))
if self.transport is None:
| python | {
"resource": ""
} |
q251634 | _parse_modes | train | def _parse_modes(mode_string, unary_modes=""):
"""
Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _pa... | python | {
"resource": ""
} |
q251635 | Tag.from_group | train | def from_group(cls, group):
"""
Construct tags from the regex group
"""
if not group:
return
| python | {
"resource": ""
} |
q251636 | Arguments.from_group | train | def from_group(group):
"""
Construct arguments from the regex group
>>> Arguments.from_group('foo')
['foo']
>>> Arguments.from_group(None)
[]
>>> Arguments.from_group('')
[]
>>> Arguments.from_group('foo bar')
| python | {
"resource": ""
} |
q251637 | FeatureSet.set | train | def set(self, name, value=True):
"set a feature value"
| python | {
"resource": ""
} |
q251638 | FeatureSet.load | train | def load(self, arguments):
"Load the values from the a ServerConnection arguments"
| python | {
"resource": ""
} |
q251639 | FeatureSet._parse_PREFIX | train | def _parse_PREFIX(value):
"channel user prefixes"
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
| python | {
"resource": ""
} |
q251640 | SingleServerIRCBot._connect | train | def _connect(self):
"""
Establish a connection to the server at the front of the server_list.
"""
server = self.servers.peek()
try:
self.connect(
server.host, server.port, self._nickname,
| python | {
"resource": ""
} |
q251641 | SingleServerIRCBot.jump_server | train | def jump_server(self, msg="Changing servers"):
"""Connect to a new server, possibly disconnecting from the current.
The bot will skip to next server in the server_list each time
jump_server is called.
"""
| python | {
"resource": ""
} |
q251642 | SingleServerIRCBot.on_ctcp | train | def on_ctcp(self, connection, event):
"""Default handler for ctcp events.
Replies to VERSION and PING requests and relays DCC requests
to the on_dccchat method.
"""
nick = event.source.nick
if event.arguments[0] == "VERSION":
connection.ctcp_reply(nick, "VERS... | python | {
"resource": ""
} |
q251643 | Channel.set_mode | train | def set_mode(self, mode, value=None):
"""Set mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
"""
if mode | python | {
"resource": ""
} |
q251644 | Channel.clear_mode | train | def clear_mode(self, mode, value=None):
"""Clear mode on the channel.
Arguments:
mode -- The mode (a single-character string).
| python | {
"resource": ""
} |
q251645 | ip_numstr_to_quad | train | def ip_numstr_to_quad(num):
"""
Convert an IP number as an integer given in ASCII
representation to an IP address string.
>>> ip_numstr_to_quad('3232235521')
'192.168.0.1'
>>> ip_numstr_to_quad(3232235521)
'192.168.0.1'
| python | {
"resource": ""
} |
q251646 | ServerConnection.as_nick | train | def as_nick(self, name):
"""
Set the nick for the duration of the context.
| python | {
"resource": ""
} |
q251647 | ServerConnection.process_data | train | def process_data(self):
"read and process input from self.socket"
try:
reader = getattr(self.socket, 'read', self.socket.recv)
new_data = reader(2 ** 14)
except socket.error:
# The server hung up.
self.disconnect("Connection reset by peer")
... | python | {
"resource": ""
} |
q251648 | ServerConnection.ctcp | train | def ctcp(self, ctcptype, target, parameter=""):
"""Send a CTCP command."""
ctcptype = ctcptype.upper()
| python | {
"resource": ""
} |
q251649 | ServerConnection.kick | train | def kick(self, channel, nick, comment=""):
"""Send a KICK command."""
| python | {
"resource": ""
} |
q251650 | ServerConnection.list | train | def list(self, channels=None, server=""):
"""Send a LIST command."""
| python | {
"resource": ""
} |
q251651 | ServerConnection.part | train | def part(self, channels, message=""):
"""Send a PART command."""
| python | {
"resource": ""
} |
q251652 | ServerConnection.privmsg_many | train | def privmsg_many(self, targets, text):
"""Send a PRIVMSG command to multiple targets."""
| python | {
"resource": ""
} |
q251653 | ServerConnection.user | train | def user(self, username, realname):
"""Send a USER command."""
cmd | python | {
"resource": ""
} |
q251654 | ServerConnection.whowas | train | def whowas(self, nick, max="", server=""):
"""Send a WHOWAS command."""
| python | {
"resource": ""
} |
q251655 | ServerConnection.set_keepalive | train | def set_keepalive(self, interval):
"""
Set a keepalive to occur every ``interval`` on this connection.
"""
| python | {
"resource": ""
} |
q251656 | Reactor.server | train | def server(self):
"""Creates and returns a ServerConnection object."""
| python | {
"resource": ""
} |
q251657 | Reactor.process_data | train | def process_data(self, sockets):
"""Called when there is more data to read on connection sockets.
Arguments:
sockets -- A list of socket objects.
See documentation for Reactor.__init__.
"""
with self.mutex:
log.log(logging.DEBUG - 2, | python | {
"resource": ""
} |
q251658 | Reactor.process_once | train | def process_once(self, timeout=0):
"""Process data from connections once.
Arguments:
timeout -- How long the select() call should wait if no
data is available.
This method should be called periodically to check and process
| python | {
"resource": ""
} |
q251659 | Reactor.disconnect_all | train | def disconnect_all(self, message=""):
"""Disconnects all connections."""
with self.mutex:
| python | {
"resource": ""
} |
q251660 | Reactor.add_global_handler | train | def add_global_handler(self, event, handler, priority=0):
"""Adds a global handler function for a specific event type.
Arguments:
event -- Event type (a string). Check the values of
numeric_events for possible event types.
handler -- Callback function tak... | python | {
"resource": ""
} |
q251661 | Reactor.remove_global_handler | train | def remove_global_handler(self, event, handler):
"""Removes a global handler function.
Arguments:
event -- Event type (a string).
handler -- Callback function.
| python | {
"resource": ""
} |
q251662 | Reactor.dcc | train | def dcc(self, dcctype="chat"):
"""Creates and returns a DCCConnection object.
Arguments:
dcctype -- "chat" for DCC CHAT connections or "raw" for
DCC SEND (or other DCC types). If "chat", | python | {
"resource": ""
} |
q251663 | Reactor._handle_event | train | def _handle_event(self, connection, event):
"""
Handle an Event event incoming on ServerConnection connection.
"""
with self.mutex:
matching_handlers = sorted(
| python | {
"resource": ""
} |
q251664 | DCCConnection.disconnect | train | def disconnect(self, message=""):
"""Hang up the connection and close the object.
Arguments:
message -- Quit message.
"""
try:
del self.connected
except AttributeError:
return
try:
self.socket.shutdown(socket.SHUT_WR)
... | python | {
"resource": ""
} |
q251665 | DCCConnection.privmsg | train | def privmsg(self, text):
"""
Send text to DCC peer.
The text will be padded with a newline if it's a DCC CHAT session.
"""
| python | {
"resource": ""
} |
q251666 | DCCConnection.send_bytes | train | def send_bytes(self, bytes):
"""
Send data to DCC peer.
"""
try:
self.socket.send(bytes)
log.debug("TO PEER: | python | {
"resource": ""
} |
q251667 | SimpleIRCClient.dcc | train | def dcc(self, *args, **kwargs):
"""Create and associate a new DCCConnection object.
Use the returned object to listen for or connect to
a DCC peer.
"""
dcc | python | {
"resource": ""
} |
q251668 | SimpleIRCClient.dcc_connect | train | def dcc_connect(self, address, port, dcctype="chat"):
"""Connect to a DCC peer.
Arguments:
address -- IP address of the peer.
port -- Port to connect to.
Returns a DCCConnection instance.
| python | {
"resource": ""
} |
q251669 | SimpleIRCClient.dcc_listen | train | def dcc_listen(self, dcctype="chat"):
"""Listen for connections from a DCC peer.
Returns a DCCConnection instance.
"""
| python | {
"resource": ""
} |
q251670 | dequote | train | def dequote(message):
"""
Dequote a message according to CTCP specifications.
The function returns a list where each element can be either a
string (normal message) or a tuple of one or two strings (tagged
messages). If a tuple has only one element (ie is a singleton),
| python | {
"resource": ""
} |
q251671 | connect | train | def connect(server, password=None,
factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None):
""" Connect to a VNCServer and return a Client instance that is usable
in the main thread of non-Twisted Python Applications, EXPERIMENTAL.
>>> from vncdotool import api
>>> with api.... | python | {
"resource": ""
} |
q251672 | VNCDoToolClient.keyPress | train | def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
| python | {
"resource": ""
} |
q251673 | VNCDoToolClient.mousePress | train | def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
| python | {
"resource": ""
} |
q251674 | VNCDoToolClient.mouseDown | train | def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
| python | {
"resource": ""
} |
q251675 | VNCDoToolClient.captureRegion | train | def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
| python | {
"resource": ""
} |
q251676 | VNCDoToolClient.expectScreen | train | def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
| python | {
"resource": ""
} |
q251677 | VNCDoToolClient.expectRegion | train | def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
| python | {
"resource": ""
} |
q251678 | VNCDoToolClient.setImageMode | train | def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax ... | python | {
"resource": ""
} |
q251679 | RFBClient._handleDecodeHextileRAW | train | def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile | python | {
"resource": ""
} |
q251680 | RFBClient._handleDecodeHextileSubrectsColoured | train | def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]... | python | {
"resource": ""
} |
q251681 | RFBClient.fillRectangle | train | def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
| python | {
"resource": ""
} |
q251682 | RFBDes.setKey | train | def setKey(self, key):
"""RFB protocol for authentication requires client to encrypt
challenge sent by server with password using DES method. However,
bits in each byte of the password are put in reverse order before
using it as encryption key."""
newkey = []
for... | python | {
"resource": ""
} |
q251683 | MiniSeries.not_played | train | def not_played(self) -> int:
"""The number of games in the player's promos that they haven't played yet."""
| python | {
"resource": ""
} |
q251684 | _rgetattr | train | def _rgetattr(obj, key):
"""Recursive getattr for handling dots in keys."""
for k | python | {
"resource": ""
} |
q251685 | Picker.draw | train | def draw(self):
"""draw the curses ui on the screen, handle scroll if needed"""
self.screen.clear()
x, y = 1, 1 # start point
max_y, max_x = self.screen.getmaxyx()
max_rows = max_y - y # the max rows we can draw
lines, current_line = self.get_lines()
# calcul... | python | {
"resource": ""
} |
q251686 | get_file | train | def get_file(file_id: str, download):
"""
Get a specific file from GridFS.
Returns a binary stream response or HTTP 404 if not found.
"""
data = current_app.config["data"] # type: DataStorage
dao = data.get_files_dao()
file_fp, filename, upload_date = dao.get(file_id)
if download:
... | python | {
"resource": ""
} |
q251687 | get_files_zip | train | def get_files_zip(run_id: int, filetype: _FileType):
"""Send all artifacts or sources of a run as ZIP."""
data = current_app.config["data"]
dao_runs = data.get_run_dao()
dao_files = data.get_files_dao()
run = dao_runs.get(run_id)
if filetype == _FileType.ARTIFACT:
target_files = run['ar... | python | {
"resource": ""
} |
q251688 | MongoFilesDAO.get | train | def get(self, file_id: Union[str, bson.ObjectId]) -> [typing.BinaryIO, str, datetime.datetime]:
"""
Return the file identified by a file_id string.
The return value is a file-like object which also has the following attributes:
filename: str
upload_date: datetime
""" | python | {
"resource": ""
} |
q251689 | GenericDAO.find_record | train | def find_record(self, collection_name, query):
"""
Return the first record mathing the given Mongo query.
:param collection_name: Name of the collection to search in.
:param query: MongoDB Query, e.g. {_id: 123}
:return: A single MongoDB record or None if not found.
:ra... | python | {
"resource": ""
} |
q251690 | GenericDAO.find_records | train | def find_records(self, collection_name, query={}, sort_by=None,
sort_direction=None, start=0, limit=None):
"""
Return a cursor of records from the given MongoDB collection.
:param collection_name: Name of the MongoDB collection to query.
:param query: Standard Mongo... | python | {
"resource": ""
} |
q251691 | GenericDAO._get_database | train | def _get_database(self, database_name):
"""
Get PyMongo client pointing to the current database.
:return: MongoDB client of the current database.
:raise DataSourceError
"""
try:
| python | {
"resource": ""
} |
q251692 | GenericDAO._get_collection | train | def _get_collection(self, collection_name):
"""
Get PyMongo client pointing to the current DB and the given collection.
:return: MongoDB client of the current database and given collection.
:raise DataSourceError
"""
try:
return self._database[collection_name... | python | {
"resource": ""
} |
q251693 | MongoRunDAO.get | train | def get(self, run_id):
"""
Get a single run from the database.
:param run_id: The ID of the run.
:return: The whole object from the database.
:raise NotFoundError when not found
"""
id = self._parse_id(run_id)
run = self.generic_dao.find_record(self.coll... | python | {
"resource": ""
} |
q251694 | MongoRunDAO._apply_sort | train | def _apply_sort(cursor, sort_by, sort_direction):
"""
Apply sort to a cursor.
:param cursor: The cursor to apply sort on.
:param sort_by: The field name to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:return:
"""
| python | {
"resource": ""
} |
q251695 | MongoRunDAO._to_mongo_query | train | def _to_mongo_query(query):
"""
Convert the query received by the Sacred Web API to a MongoDB query.
Takes a query in format
{"type": "and", "filters": [
{"field": "host.hostname", "operator": "==", "value": "ntbacer"},
{"type": "or", "filters": [
{"field":... | python | {
"resource": ""
} |
q251696 | MongoRunDAO._simple_clause_to_query | train | def _simple_clause_to_query(clause):
"""
Convert a clause from the Sacred Web API format to the MongoDB format.
:param clause: A clause to be converted. It must have "field",
"operator" and "value" fields.
:return: A MongoDB clause.
"""
# It's a regular clause
... | python | {
"resource": ""
} |
q251697 | MongoRunDAO._status_filter_to_query | train | def _status_filter_to_query(clause):
"""
Convert a clause querying for an experiment state RUNNING or DEAD.
Queries that check for experiment state RUNNING and DEAD need to be
replaced by the logic that decides these two states as both of them
are stored in the Mongo Database as... | python | {
"resource": ""
} |
q251698 | MongoRunDAO.delete | train | def delete(self, run_id):
"""
Delete run with the given id from the backend.
:param run_id: Id of the run to delete.
:raise NotImplementedError If not supported by the backend.
:raise DataSourceError General data source error.
:raise NotFoundError The run was not found. ... | python | {
"resource": ""
} |
q251699 | add_mongo_config | train | def add_mongo_config(app, simple_connection_string,
mongo_uri, collection_name):
"""
Configure the application to use MongoDB.
:param app: Flask application
:param simple_connection_string:
Expects host:port:database_name or database_name
Mutally_exc... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.