code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
@functools.wraps(f)
@coroutine
def _wrapper(self, *args, **kwargs):
result = yield f(self, *args, **kwargs)
# Don't call isinstance(), not checking subclasses.
if result.__class__ == pymongo_class:
# Delegate to the current object to wrap the result.
rai... | def pymongo_class_wrapper(f, pymongo_class) | Executes the coroutine f and wraps its result in a Motor class.
See WrapAsync. | 3.797318 | 3.627936 | 1.046688 |
cursor_class = create_class_with_framework(
AgnosticChangeStream, self._framework, self.__module__)
# Latent cursor that will send initial command on first "async for".
return cursor_class(self, pipeline, full_document, resume_after,
max_await_ti... | 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 cluster.
Returns a :class:`~MotorChangeStream` cursor which iterates over changes
on all databases in this cluster. Introduced in MongoDB 4.0.
See the documentation for :meth:`MotorCollection.watch` for more
details and examples.
:Parameters:
- ... | 7.035011 | 10.803885 | 0.651156 |
self.delegate.start_transaction(read_concern=read_concern,
write_concern=write_concern,
read_preference=read_preference)
return _MotorTransactionContext(self) | def start_transaction(self, read_concern=None, write_concern=None,
read_preference=None) | Start a multi-statement transaction.
Takes the same arguments as
:class:`~pymongo.client_session.TransactionOptions`.
Best used in a context manager block:
.. code-block:: python3
# Use "await" for start_session, but not for start_transaction.
async with await cli... | 2.737781 | 4.256124 | 0.643257 |
cursor = self.delegate.find(*unwrap_args_session(args),
**unwrap_kwargs_session(kwargs))
cursor_class = create_class_with_framework(
AgnosticCursor, self._framework, self.__module__)
return cursor_class(cursor, self) | def find(self, *args, **kwargs) | Create a :class:`MotorCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not require an ``await`` expression, because
``find`` merely creates a
:class:`MotorCursor` without performing any operations on the server.
``Mot... | 8.098561 | 7.758674 | 1.043807 |
cursor = self.delegate.find_raw_batches(*unwrap_args_session(args),
**unwrap_kwargs_session(kwargs))
cursor_class = create_class_with_framework(
AgnosticRawBatchCursor, self._framework, self.__module__)
return cursor_class(cur... | def find_raw_batches(self, *args, **kwargs) | Query the database and retrieve batches of raw BSON.
Similar to the :meth:`find` method but returns each batch as bytes.
This example demonstrates how to work with raw batches, but in practice
raw batches should be passed to an external library that can decode
BSON into another data ty... | 7.097168 | 7.99652 | 0.887532 |
cursor_class = create_class_with_framework(
AgnosticLatentCommandCursor, self._framework, self.__module__)
# Latent cursor that will send initial command on first "async for".
return cursor_class(self, self._async_aggregate, pipeline,
**unwrap_kw... | def aggregate(self, pipeline, **kwargs) | Execute an aggregation pipeline on this collection.
The aggregation can be run on a secondary if the client is connected
to a replica set and its ``read_preference`` is not :attr:`PRIMARY`.
:Parameters:
- `pipeline`: a single command or list of aggregation commands
- `sessi... | 24.923159 | 22.962973 | 1.085363 |
cursor_class = create_class_with_framework(
AgnosticLatentCommandCursor, self._framework, self.__module__)
# Latent cursor that will send initial command on first "async for".
return cursor_class(self, self._async_aggregate_raw_batches, pipeline,
... | def aggregate_raw_batches(self, pipeline, **kwargs) | Perform an aggregation and retrieve batches of raw BSON.
Similar to the :meth:`aggregate` method but returns each batch as bytes.
This example demonstrates how to work with raw batches, but in practice
raw batches should be passed to an external library that can decode
BSON into anothe... | 22.366833 | 20.610815 | 1.085199 |
cursor_class = create_class_with_framework(
AgnosticLatentCommandCursor, self._framework, self.__module__)
# Latent cursor that will send initial command on first "async for".
return cursor_class(self, self._async_list_indexes, session=session) | def list_indexes(self, session=None) | Get a cursor over the index documents for this collection. ::
async def print_indexes():
async for index in db.test.list_indexes():
print(index)
If the only index is the default index on ``_id``, this might print::
SON([('v', 1), ('key', SON([('_id', 1)])... | 21.635141 | 20.592152 | 1.05065 |
if not self.alive:
raise pymongo.errors.InvalidOperation(
"Can't call get_more() on a MotorCursor that has been"
" exhausted or killed.")
self.started = True
return self._refresh() | def _get_more(self) | Initial query or getMore. Returns a Future. | 7.151349 | 5.333087 | 1.34094 |
if not self._buffer_size() and self.alive:
# Return the Future, which resolves to number of docs fetched or 0.
return self._get_more()
elif self._buffer_size():
future = self._framework.get_future(self.get_io_loop())
future.set_result(True)
... | def fetch_next(self) | A Future used with `gen.coroutine`_ to asynchronously retrieve the
next document in the result set, fetching a batch of documents from the
server if necessary. Resolves to ``False`` if there are no more
documents, otherwise :meth:`next_object` is guaranteed to return a
document.
... | 5.281805 | 5.123435 | 1.030911 |
if length is not None:
if not isinstance(length, int):
raise TypeError('length must be an int, not %r' % length)
elif length < 0:
raise ValueError('length must be non-negative')
if self._query_flags() & _QUERY_OPTIONS['tailable_cursor']:
... | def to_list(self, length) | Get a list of documents.
.. testsetup:: to_list
MongoClient().test.test_collection.delete_many({})
MongoClient().test.test_collection.insert_many([{'_id': i} for i in range(4)])
from tornado import ioloop
.. doctest:: to_list
>>> from motor.motor_tornado impo... | 3.817969 | 3.452181 | 1.105959 |
if not self.closed:
self.closed = True
yield self._framework.yieldable(self._close()) | def close(self) | Explicitly kill this cursor on the server. Call like (in Tornado):
.. code-block:: python
yield cursor.close() | 10.04034 | 9.087818 | 1.104813 |
loop = self.get_io_loop()
return self._framework.run_on_executor(loop, self._next) | def next(self) | Advance the cursor.
This method blocks until the next change document is returned or an
unrecoverable error is raised.
Raises :exc:`StopAsyncIteration` if this change stream is closed.
You can iterate the change stream by calling
``await change_stream.next()`` repeatedly, or w... | 10.375585 | 14.679328 | 0.706816 |
if self.delegate:
return self._close()
# Never started.
future = self._framework.get_future(self.get_io_loop())
future.set_result(None)
return future | def close(self) | Close this change stream.
Stops any "async for" loops using this change stream. | 9.454823 | 9.43436 | 1.002169 |
@functools.wraps(sync_method)
def method(self, *args, **kwargs):
if unwrap_class is not None:
# Don't call isinstance(), not checking subclasses.
unwrapped_args = [
obj.delegate
if obj.__class__.__name__.endswith(
(unwrap_c... | def asynchronize(
framework, sync_method, doc=None, wrap_class=None, unwrap_class=None) | Decorate `sync_method` so it returns a Future.
The method runs on a thread and resolves the Future when it completes.
:Parameters:
- `motor_class`: Motor class being created, e.g. MotorClient.
- `framework`: An asynchronous framework
- `sync_method`: Unbound method of pymong... | 3.011408 | 2.945572 | 1.022351 |
@functools.wraps(fn)
def _wrap_synchro(*args, **kwargs):
motor_obj = fn(*args, **kwargs)
# Not all Motor classes appear here, only those we need to return
# from methods like map_reduce() or create_collection()
if isinstance(motor_obj, motor.MotorCollection):
cl... | def wrap_synchro(fn) | If decorated Synchro function returns a Motor object, wrap in a Synchro
object. | 2.193241 | 2.136776 | 1.026425 |
@functools.wraps(fn)
def _unwrap_synchro(*args, **kwargs):
def _unwrap_obj(obj):
if isinstance(obj, Synchro):
return obj.delegate
else:
return obj
args = [_unwrap_obj(arg) for arg in args]
kwargs = dict([
(key, _un... | def unwrap_synchro(fn) | Unwrap Synchro objects passed to a method and pass Motor objects instead. | 1.972438 | 1.819186 | 1.084242 |
grid_out = super(self.__class__, self).next_object()
if grid_out:
grid_out_class = create_class_with_framework(
AgnosticGridOut, self._framework, self.__module__)
return grid_out_class(self.collection, delegate=grid_out)
else:
# Exhau... | def next_object(self) | Get next GridOut object from cursor. | 8.144464 | 5.614059 | 1.450726 |
return self._framework.chain_return_value(self._ensure_file(),
self.get_io_loop(),
self) | def open(self) | Retrieve this file's attributes from the server.
Returns a Future.
.. versionchanged:: 2.0
No longer accepts a callback argument.
.. versionchanged:: 0.2
:class:`~motor.MotorGridOut` now opens itself on demand, calling
``open`` explicitly is rarely needed. | 34.124569 | 24.143549 | 1.413403 |
written = 0
while written < self.length:
# Reading chunk_size at a time minimizes buffering.
f = self._framework.yieldable(self.read(self.chunk_size))
yield f
chunk = f.result()
# write() simply appends the output to a list; flush() s... | def stream_to_handler(self, request_handler) | Write the contents of this file to a
:class:`tornado.web.RequestHandler`. This method calls
:meth:`~tornado.web.RequestHandler.flush` on
the RequestHandler, so ensure all headers have already been set.
For a more complete example see the implementation of
:class:`~motor.web.GridF... | 7.18599 | 7.557344 | 0.950862 |
cursor = self.delegate.find(*args, **kwargs)
grid_out_cursor = create_class_with_framework(
AgnosticGridOutCursor, self._framework, self.__module__)
return grid_out_cursor(cursor, self.collection) | def find(self, *args, **kwargs) | Find and return the files collection documents that match ``filter``.
Returns a cursor that iterates across files matching
arbitrary queries on the files collection. Can be combined
with other modifiers for additional control.
For example::
cursor = bucket.find({"filename": ... | 10.357331 | 9.634122 | 1.075067 |
attr = safe_getattr(motor_class, name)
# Store some info for process_motor_nodes()
full_name = '%s.%s.%s' % (
motor_class.__module__, motor_class.__name__, name)
full_name_legacy = 'motor.%s.%s.%s' % (
motor_class.__module__, motor_class.__name__, name)
# These sub-attributes... | def get_motor_attr(motor_class, name, *defargs) | If any Motor attributes can't be accessed, grab the equivalent PyMongo
attribute. While we're at it, store some info about each attribute
in the global motor_info dict. | 3.972972 | 3.733552 | 1.064127 |
to_return: Dict[Mount, Dict[str, Optional[str]]] = {}
for mount in Mount:
found_model = self._smoothie_driver.read_pipette_model(
mount.name.lower())
found_id = self._smoothie_driver.read_pipette_id(
mount.name.lower())
expecte... | def get_attached_instruments(
self, expected: Dict[Mount, str])\
-> Dict[Mount, Dict[str, Optional[str]]] | Find the instruments attached to our mounts.
:param expected: A dict that may contain a mapping from mount to
strings that should prefix instrument model names.
When instruments are scanned, they are matched
against the expectation (if ... | 2.767544 | 2.92447 | 0.94634 |
self._smoothie_driver.set_active_current({axis.name: amp}) | def set_active_current(self, axis, amp) | This method sets only the 'active' current, i.e., the current for an
axis' movement. Smoothie driver automatically resets the current for
pipette axis to a low current (dwelling current) after each move | 11.303286 | 7.572345 | 1.492706 |
return {ax: (0, pos+.05) for ax, pos
in self._smoothie_driver.homed_position.items()
if ax not in 'BC'} | def axis_bounds(self) -> Dict[str, Tuple[float, float]] | The (minimum, maximum) bounds for each axis. | 16.415344 | 15.090204 | 1.087815 |
return self._smoothie_driver.probe_axis(axis, distance) | def probe(self, axis: str, distance: float) -> Dict[str, float] | Run a probe and return the new position dict | 15.821947 | 11.782192 | 1.34287 |
self.pause()
await asyncio.sleep(duration_s)
self.resume() | async def delay(self, duration_s: int) | Pause and sleep | 5.620403 | 3.532195 | 1.591193 |
global session
pipette_info = set_current_mount(session.adapter, session)
pipette = pipette_info['pipette']
res = {}
if pipette:
session.current_model = pipette_info['model']
if not feature_flags.use_protocol_api_v2():
mount = pipette.mount
session.curren... | def init_pipette() | Finds pipettes attached to the robot currently and chooses the correct one
to add to the session.
:return: The pipette type and mount chosen for deck calibration | 4.368323 | 4.190173 | 1.042516 |
pipette = None
right_channel = None
left_channel = None
right_pipette, left_pipette = get_pipettes(hardware)
if right_pipette:
if not feature_flags.use_protocol_api_v2():
right_channel = right_pipette.channels
else:
right_channel = right_pipette.get('cha... | def set_current_mount(hardware, session) | Choose the pipette in which to execute commands. If there is no pipette,
or it is uncommissioned, the pipette is not mounted.
:attached_pipettes attached_pipettes: Information obtained from the current
pipettes attached to the robot. This looks like the following:
:dict with keys 'left' and 'right' and... | 2.351658 | 2.331775 | 1.008527 |
global session
tip_length = data.get('tipLength')
if not tip_length:
message = 'Error: "tipLength" must be specified in request'
status = 400
else:
if not feature_flags.use_protocol_api_v2():
pipette = session.pipettes[session.current_mount]
if pipet... | async def attach_tip(data) | Attach a tip to the current pipette
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'attach tip'
'tipLength': a float representing how... | 4.665923 | 4.050205 | 1.152021 |
global session
if not feature_flags.use_protocol_api_v2():
pipette = session.pipettes[session.current_mount]
if not pipette.tip_attached:
log.warning('detach tip called with no tip')
pipette._remove_tip(session.tip_length)
else:
session.adapter.remove_tip(se... | async def detach_tip(data) | Detach the tip from the current pipette
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'detach tip'
} | 6.868446 | 6.037284 | 1.137672 |
axis = data.get('axis')
direction = data.get('direction')
step = data.get('step')
if axis not in ('x', 'y', 'z'):
message = '"axis" must be "x", "y", or "z"'
status = 400
elif direction not in (-1, 1):
message = '"direction" must be -1 or 1'
status = 400
eli... | async def run_jog(data) | Allow the user to jog the selected pipette around the deck map
:param data: Information obtained from a POST request.
The content type is application/json
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'jog'
'axis': The curren... | 2.457906 | 2.442751 | 1.006204 |
global session
point_name = data.get('point')
point = safe_points().get(point_name)
if point and len(point) == 3:
if not feature_flags.use_protocol_api_v2():
pipette = session.pipettes[session.current_mount]
channels = pipette.channels
# For multichannel pipe... | async def move(data) | Allow the user to move the selected pipette to a specific point
:param data: Information obtained from a POST request.
The content type is application/json
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'move'
'point': The nam... | 4.916636 | 4.424952 | 1.111116 |
global session
valid_points = list(session.points.keys())
point = data.get('point')
if point not in valid_points:
message = 'point must be one of {}'.format(valid_points)
status = 400
elif not session.current_mount:
message = "Mount must be set before calibrating"
... | async def save_xy(data) | Save the current XY values for the calibration data
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'save xy'
'point': a string ID ['1... | 4.284075 | 3.946561 | 1.085521 |
if not session.tip_length:
message = "Tip length must be set before calibrating"
status = 400
else:
if not feature_flags.use_protocol_api_v2():
mount = 'Z' if session.current_mount == 'left' else 'A'
actual_z = position(
mount, session.adapter... | async def save_z(data) | Save the current Z height value for the calibration data
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'save z'
} | 5.593558 | 5.354989 | 1.044551 |
if any([v is None for v in session.points.values()]):
message = "Not all points have been saved"
status = 400
else:
# expected values based on mechanical drawings of the robot
expected_pos = expected_points()
expected = [
expected_pos[p] for p in expected... | async def save_transform(data) | Calculate the transormation matrix that calibrates the gantry to the deck
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'save transform'
... | 6.93551 | 6.773252 | 1.023956 |
global session
if not feature_flags.use_protocol_api_v2():
session.adapter.remove_instrument('left')
session.adapter.remove_instrument('right')
else:
session.adapter.cache_instruments()
session = None
return web.json_response({"message": "calibration session released"}) | async def release(data) | Release a session
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'release'
} | 9.728697 | 9.04005 | 1.076177 |
global session
try:
body = await request.json()
except json.decoder.JSONDecodeError:
# Body will be null for requests without parameters (normal operation)
log.debug("No body in {}".format(request))
body = {}
if not session or body.get('force'):
hardware = ... | async def start(request) | Begins the session manager for factory calibration, if a session is not
already in progress, or if the "force" key is specified in the request. To
force, use the following body:
{
"force": true
}
:return: The current session ID token or an error message | 5.500445 | 4.948364 | 1.111568 |
if session:
message = ''
data = await request.json()
try:
log.info("Dispatching {}".format(data))
_id = data.get('token')
if not _id:
message = '"token" field required for calibration requests'
raise AssertionError
... | async def dispatch(request) | Routes commands to subhandlers based on the command field in the body. | 3.109286 | 3.010169 | 1.032927 |
while True:
_next = dict(self._poller.poll(POLLING_FREQUENCY_MS))
if self._halt_read_file.fileno() in _next:
log.debug("Poller [{}]: halt".format(hash(self)))
self._halt_read_file.read()
# Note: this is discarded because we send a ... | def _serial_poller(self) | Priority-sorted list of checks
Highest priority is the 'halt' channel, which is used to kill the
thread and the serial communication channel and allow everything to be
cleaned up.
Second is the lid-open interrupt, which should trigger a callback
(typically to halt the robot).
... | 5.359693 | 4.693727 | 1.141884 |
if self._driver and self._driver.is_connected():
self._driver.set_temperature(celsius) | def set_temperature(self, celsius) | Set temperature in degree Celsius
Range: 4 to 95 degree Celsius (QA tested).
The internal temp range is -9 to 99 C, which is limited by the 2-digit
temperature display. Any input outside of this range will be clipped
to the nearest limit | 3.534016 | 4.857463 | 0.727544 |
if self._driver and self._driver.is_connected():
self._driver.deactivate() | def deactivate(self) | Stop heating/cooling and turn off the fan | 6.023813 | 5.029148 | 1.19778 |
if self._port:
self._driver = TempDeckDriver()
self._driver.connect(self._port)
self._device_info = self._driver.get_device_info()
self._poll_stop_event = Event()
Thread(target=self._poll_temperature).start()
else:
# Sanit... | def connect(self) | Connect to the 'TempDeck' port
Planned change- will connect to the correct port in case of multiple
TempDecks | 6.404468 | 5.25401 | 1.218968 |
'''
Disconnect from the serial port
'''
if self._poll_stop_event:
self._poll_stop_event.set()
if self._driver:
if self.status != 'idle':
self.deactivate()
self._driver.disconnect() | def disconnect(self) | Disconnect from the serial port | 5.992919 | 5.056992 | 1.185076 |
old_hw = self._hw_manager.hardware
try:
self._hw_manager.set_hw(hardware)
yield self
finally:
self._hw_manager.set_hw(old_hw) | def temp_connect(self, hardware: hc.API) | Connect temporarily to the specified hardware controller.
This should be used as a context manager:
.. code-block :: python
with ctx.temp_connect(hw):
# do some tasks
ctx.home()
# after the with block, the context is connected to the same
... | 3.997072 | 3.338498 | 1.197267 |
self._hw_manager.set_hw(hardware)
self._hw_manager.hardware.cache_instruments() | def connect(self, hardware: hc.API) | Connect to a running hardware API.
This can be either a simulator or a full hardware controller.
Note that there is no true disconnected state for a
:py:class:`.ProtocolContext`; :py:meth:`disconnect` simply creates
a new simulator and replaces the current hardware with it. | 11.37944 | 12.501863 | 0.91022 |
self._deck_layout[location] = labware_obj
return labware_obj | def load_labware(
self, labware_obj: Labware,
location: types.DeckLocation) -> Labware | Specify the presence of a piece of labware on the OT2 deck.
This function loads the labware specified by `labware`
(previously loaded from a configuration file) to the location
specified by `location`.
:param Labware labware: The labware object to load
:param location: The slot... | 5.781597 | 9.84934 | 0.587003 |
labware = load(labware_name,
self._deck_layout.position_for(location),
label)
return self.load_labware(labware, location) | def load_labware_by_name(
self, labware_name: str,
location: types.DeckLocation, label: str = None) -> Labware | A convenience function to specify a piece of labware by name.
For labware already defined by Opentrons, this is a convient way
to collapse the two stages of labware initialization (creating
the labware and adding it to the protocol) into one.
This function returns the created and initi... | 6.182297 | 7.806459 | 0.791946 |
if isinstance(mount, str):
try:
checked_mount = types.Mount[mount.upper()]
except KeyError:
raise ValueError(
"If mount is specified as a string, it should be either"
"'left' or 'right' (ignoring capitalizat... | def load_instrument(
self,
instrument_name: str,
mount: Union[types.Mount, str],
tip_racks: List[Labware] = None,
replace: bool = False) -> 'InstrumentContext' | Load a specific instrument required by the protocol.
This value will actually be checked when the protocol runs, to
ensure that the correct instrument is attached in the specified
location.
:param str instrument_name: The name of the instrument model, or a
... | 3.174026 | 3.132933 | 1.013116 |
return {mount.name.lower(): instr for mount, instr
in self._instruments.items()} | def loaded_instruments(self) -> Dict[str, Optional['InstrumentContext']] | Get the instruments that have been loaded into the protocol.
:returns: A dict mapping mount names in lowercase to the instrument
in that mount, or `None` if no instrument is present. | 10.999487 | 6.68286 | 1.645925 |
delay_time = seconds + minutes * 60
self._hw_manager.hardware.delay(delay_time) | def delay(self, seconds=0, minutes=0, msg=None) | Delay protocol execution for a specific amount of time.
:param float seconds: A time to delay in seconds
:param float minutes: A time to delay in minutes
If both `seconds` and `minutes` are specified, they will be added. | 7.89862 | 7.555166 | 1.045459 |
self._log.debug("home")
self._location_cache = None
self._hw_manager.hardware.home() | def home(self) | Homes the robot. | 15.301397 | 11.391866 | 1.343186 |
self._log.debug("aspirate {} from {} at {}"
.format(volume,
location if location else 'current position',
rate))
if isinstance(location, Well):
point, well = location.bottom()
loc = ... | def aspirate(self,
volume: float = None,
location: Union[types.Location, Well] = None,
rate: float = 1.0) -> 'InstrumentContext' | Aspirate a volume of liquid (in microliters/uL) using this pipette
from the specified location
If only a volume is passed, the pipette will aspirate
from its current position. If only a location is passed,
:py:meth:`aspirate` will default to its :py:attr:`max_volume`.
:param vo... | 3.414633 | 3.352985 | 1.018386 |
self._log.debug(
'mixing {}uL with {} repetitions in {} at rate={}'.format(
volume, repetitions,
location if location else 'current position', rate))
if not self.hw_pipette['has_tip']:
raise hc.NoTipAttachedError('Pipette has no tip. Abort... | def mix(self,
repetitions: int = 1,
volume: float = None,
location: Union[types.Location, Well] = None,
rate: float = 1.0) -> 'InstrumentContext' | Mix a volume of liquid (uL) using this pipette.
If no location is specified, the pipette will mix from its current
position. If no Volume is passed, 'mix' will default to its max_volume.
:param repetitions: how many times the pipette should mix (default: 1)
:param volume: number of micr... | 3.648677 | 3.340459 | 1.092268 |
if location is None:
if not self._ctx.location_cache:
raise RuntimeError('No valid current location cache present')
else:
location = self._ctx.location_cache.labware # type: ignore
# type checked below
if isinstance(locat... | def blow_out(self,
location: Union[types.Location, Well] = None
) -> 'InstrumentContext' | Blow liquid out of the tip.
If :py:attr:`dispense` is used to completely empty a pipette,
usually a small amount of liquid will remain in the tip. This
method moves the plunger past its usual stops to fully remove
any remaining liquid from the tip. Regardless of how much liquid
... | 3.571151 | 3.59097 | 0.994481 |
if not self.hw_pipette['has_tip']:
raise hc.NoTipAttachedError('Pipette has no tip to touch_tip()')
if speed > 80.0:
self._log.warning('Touch tip speed above limit. Setting to 80mm/s')
speed = 80.0
elif speed < 20.0:
self._log.warning('To... | def touch_tip(self,
location: Well = None,
radius: float = 1.0,
v_offset: float = -1.0,
speed: float = 60.0) -> 'InstrumentContext' | Touch the pipette tip to the sides of a well, with the intent of
removing left-over droplets
:param location: If no location is passed, pipette will
touch tip at current well's edges
:type location: :py:class:`.Well` or None
:param radius: Describes the proporti... | 3.168108 | 3.023041 | 1.047987 |
if not self.hw_pipette['has_tip']:
raise hc.NoTipAttachedError('Pipette has no tip. Aborting air_gap')
if height is None:
height = 5
loc = self._ctx.location_cache
if not loc or not isinstance(loc.labware, Well):
raise RuntimeError('No previo... | def air_gap(self,
volume: float = None,
height: float = None) -> 'InstrumentContext' | Pull air into the pipette current tip at the current location
:param volume: The amount in uL to aspirate air into the tube.
(Default will use all remaining volume in tip)
:type volume: float
:param height: The number of millimiters to move above the current Well
... | 6.223508 | 4.564552 | 1.363443 |
if not self.hw_pipette['has_tip']:
self._log.warning('Pipette has no tip to return')
loc = self._last_tip_picked_up_from
if not isinstance(loc, Well):
raise TypeError('Last tip location should be a Well but it is: '
'{}'.format(loc))
... | def return_tip(self) -> 'InstrumentContext' | If a tip is currently attached to the pipette, then it will return the
tip to it's location in the tiprack.
It will not reset tip tracking so the well flag will remain False.
:returns: This instance | 4.311995 | 4.727766 | 0.912058 |
num_channels = self.channels
def _select_tiprack_from_list(tip_racks) -> Tuple[Labware, Well]:
try:
tr = tip_racks[0]
except IndexError:
raise OutOfTipsError
next_tip = tr.next_tip(num_channels)
if next_tip:
... | def pick_up_tip(self, location: Union[types.Location, Well] = None,
presses: int = 3,
increment: float = 1.0) -> 'InstrumentContext' | Pick up a tip for the pipette to run liquid-handling commands with
If no location is passed, the Pipette will pick up the next available
tip in its :py:attr:`InstrumentContext.tip_racks` list.
The tip to pick up can be manually specified with the `location`
argument. The `location` arg... | 3.098949 | 3.163641 | 0.979552 |
if location and isinstance(location, types.Location):
if isinstance(location.labware, Well):
target = location
else:
raise TypeError(
"If a location is specified as a types.Location (for "
"instance, as the ... | def drop_tip(
self,
location: Union[types.Location, Well] = None)\
-> 'InstrumentContext' | Drop the current tip.
If no location is passed, the Pipette will drop the tip into its
:py:attr:`trash_container`, which if not specified defaults to
the fixed trash in slot 12.
The location in which to drop the tip can be manually specified with
the `location` argument. The `l... | 3.670035 | 3.572231 | 1.027379 |
def home_dummy(mount): pass
cmds.do_publish(self.broker, cmds.home, home_dummy,
'before', None, None, self._mount.name.lower())
self._hw_manager.hardware.home_z(self._mount)
self._hw_manager.hardware.home_plunger(self._mount)
cmds.do_publish(self.... | def home(self) -> 'InstrumentContext' | Home the robot.
:returns: This instance. | 5.951276 | 6.156624 | 0.966646 |
self._log.debug("Distributing {} from {} to {}"
.format(volume, source, dest))
kwargs['mode'] = 'distribute'
kwargs['disposal_volume'] = kwargs.get('disposal_vol', self.min_volume)
return self.transfer(volume, source, dest, **kwargs) | def distribute(self,
volume: float,
source: Well,
dest: List[Well],
*args, **kwargs) -> 'InstrumentContext' | Move a volume of liquid from one source to multiple destinations.
:param volume: The amount of volume to distribute to each destination
well.
:param source: A single well from where liquid will be aspirated.
:param dest: List of Wells where liquid will be dispensed to.
... | 3.59952 | 3.918436 | 0.918611 |
self._log.debug("Consolidate {} from {} to {}"
.format(volume, source, dest))
kwargs['mode'] = 'consolidate'
return self.transfer(volume, source, dest, **kwargs) | def consolidate(self,
volume: float,
source: List[Well],
dest: Well,
*args, **kwargs) -> 'InstrumentContext' | Move liquid from multiple wells (sources) to a single well(destination)
:param volume: The amount of volume to consolidate from each source
well.
:param source: List of wells from where liquid will be aspirated.
:param dest: The single well into which liquid will be dispe... | 3.402245 | 3.585569 | 0.948872 |
if self._ctx.location_cache:
from_lw = self._ctx.location_cache.labware
else:
from_lw = None
from_center = 'centerMultichannelOnWells'\
in quirks_from_any_parent(from_lw)
cp_override = CriticalPoint.XY_CENTER if from_center else None
... | def move_to(self, location: types.Location, force_direct: bool = False,
minimum_z_height: float = None
) -> 'InstrumentContext' | Move the instrument.
:param location: The location to move to.
:type location: :py:class:`.types.Location`
:param force_direct: If set to true, move directly to destination
without arc motion.
:param minimum_z_height: When specified, this Z margin is able to rais... | 4.044298 | 4.291139 | 0.942477 |
self._hw_manager.hardware.set_flow_rate(self._mount, **new_flow_rate) | def flow_rate(self, new_flow_rate: Dict[str, float]) -> None | Update the speeds (in uL/s) for the pipette.
:param new_flow_rate: A dict containing at least one of 'aspirate'
and 'dispense', mapping to new speeds in uL/s. | 9.834119 | 5.351655 | 1.837585 |
model = self.name
if 'single' in model:
return 'single'
elif 'multi' in model:
return 'multi'
else:
raise RuntimeError("Bad pipette model name: {}".format(model)) | def type(self) -> str | One of `'single'` or `'multi'`. | 5.621521 | 4.229729 | 1.32905 |
pipette = self._hw_manager.hardware.attached_instruments[self._mount]
if pipette is None:
raise types.PipetteNotAttachedError
return pipette | def hw_pipette(self) -> Dict[str, Any] | View the information returned by the hardware API directly.
:raises: a :py:class:`.types.PipetteNotAttachedError` if the pipette is
no longer attached (should not happen). | 5.759094 | 4.39571 | 1.310162 |
mod_labware = self._geometry.add_labware(labware)
self._ctx.deck.recalculate_high_z()
return mod_labware | def load_labware(self, labware: Labware) -> Labware | Specify the presence of a piece of labware on the module.
:param labware: The labware object. This object should be already
initialized and its parent should be set to this
module's geometry. To initialize and load a labware
onto the modul... | 8.440895 | 10.371303 | 0.81387 |
lw = load(name, self._geometry.location)
return self.load_labware(lw) | def load_labware_by_name(self, name: str) -> Labware | Specify the presence of a piece of labware on the module.
:param name: The name of the labware object.
:returns: The initialized and loaded labware object. | 12.725004 | 21.013258 | 0.60557 |
if labware.magdeck_engage_height is None:
MODULE_LOG.warning(
"This labware ({}) is not explicitly compatible with the"
" Magnetic Module. You will have to specify a height when"
" calling engage().")
return super().load_labware(labwar... | def load_labware(self, labware: Labware) -> Labware | Load labware onto a Magnetic Module, checking if it is compatible | 8.035092 | 7.366435 | 1.090771 |
if height:
dist = height
elif self.labware and self.labware.magdeck_engage_height is not None:
dist = self.labware.magdeck_engage_height
if offset:
dist += offset
else:
raise ValueError(
"Currently loaded la... | def engage(self, height: float = None, offset: float = None) | Raise the Magnetic Module's magnets.
The destination of the magnets can be specified in several different
ways, based on internally stored default heights for labware:
- If neither `height` nor `offset` is specified, the magnets will
raise to a reasonable default height based o... | 4.869515 | 4.5445 | 1.071518 |
self._geometry.lid_status = self._module.open()
self._ctx.deck.recalculate_high_z()
return self._geometry.lid_status | def open(self) | Opens the lid | 21.15023 | 17.638018 | 1.199127 |
self._geometry.lid_status = self._module.close()
self._ctx.deck.recalculate_high_z()
return self._geometry.lid_status | def close(self) | Closes the lid | 21.098244 | 18.706778 | 1.12784 |
return self._module.set_temperature(
temp=temp, hold_time=hold_time, ramp_rate=ramp_rate) | def set_temperature(self,
temp: float,
hold_time: float = None,
ramp_rate: float = None) | Set the target temperature, in C.
Valid operational range yet to be determined.
:param temp: The target temperature, in degrees C.
:param hold_time: The time to hold after reaching temperature. If
``hold_time`` is not specified, the Thermocycler will
... | 3.442762 | 3.687761 | 0.933564 |
# Required for old bootloader
ports_before_dfu_mode = await _discover_ports()
driver.enter_programming_mode()
driver.disconnect()
new_port = ''
try:
new_port = await asyncio.wait_for(
_port_poll(_has_old_bootloader(model), ports_before_dfu_mode),
PORT_SEARCH... | async def enter_bootloader(driver, model) | Using the driver method, enter bootloader mode of the atmega32u4.
The bootloader mode opens a new port on the uC to upload the hex file.
After receiving a 'dfu' command, the firmware provides a 3-second window to
close the current port so as to do a clean switch to the bootloader port.
The new port show... | 6.89448 | 5.849636 | 1.178617 |
ports_before_update = await _discover_ports()
config_file_path = os.path.join(package_root,
'config', 'modules', 'avrdude.conf')
kwargs: Dict[str, Any] = {
'stdout': asyncio.subprocess.PIPE,
'stderr': asyncio.subprocess.PIPE
}
if loop:
... | async def update_firmware(port: str,
firmware_file_path: str,
loop: Optional[asyncio.AbstractEventLoop])\
-> Tuple[str, Tuple[bool, str]] | Run avrdude firmware upload command. Switch back to normal module port
Note: For modules with old bootloader, the kernel could assign the module
a new port after the update (since the board is automatically reset).
Scan for such a port change and use the appropriate port.
Returns a tuple of the new po... | 3.065889 | 3.03175 | 1.01126 |
new_port = ''
while not new_port:
if is_old_bootloader:
new_port = await _port_on_mode_switch(ports_before_switch)
else:
ports = await _discover_ports()
if ports:
discovered_ports = list(filter(
lambda x: x.endswith('bo... | async def _port_poll(is_old_bootloader, ports_before_switch=None) | Checks for the bootloader port | 3.228276 | 2.946946 | 1.095465 |
if not self.has_tip or cp_override == CriticalPoint.NOZZLE:
cp_type = CriticalPoint.NOZZLE
tip_length = 0.0
else:
cp_type = CriticalPoint.TIP
tip_length = self.current_tip_length
if cp_override == CriticalPoint.XY_CENTER:
mod_o... | def critical_point(self, cp_override: CriticalPoint = None) -> Point | The vector from the pipette's origin to its critical point. The
critical point for a pipette is the end of the nozzle if no tip is
attached, or the end of the tip if a tip is attached.
If `cp_override` is specified and valid - so is either
:py:attr:`CriticalPoint.NOZZLE` or :py:attr:`Cr... | 3.462268 | 3.120518 | 1.109517 |
assert tip_length > 0.0, "tip_length must be greater than 0"
assert not self.has_tip
self._has_tip = True
self._current_tip_length = tip_length | def add_tip(self, tip_length) -> None | Add a tip to the pipette for position tracking and validation
(effectively updates the pipette's critical point)
:param tip_length: a positive, non-zero float representing the distance
in Z from the end of the pipette nozzle to the end of the tip
:return: | 3.428856 | 3.403672 | 1.007399 |
'''
Connect over Serial to the Smoothieware motor driver
'''
print()
import optparse
from opentrons import robot
print('Connecting to robot...')
parser = optparse.OptionParser(usage='usage: %prog [options] ')
parser.add_option(
"-p", "--p", dest="port", default='',
ty... | def connect_to_robot() | Connect over Serial to the Smoothieware motor driver | 4.317179 | 3.172641 | 1.360753 |
'''
Send a bytearray to the specified mount, so that Smoothieware can
save the bytes to the pipette's memory
'''
robot._driver.write_pipette_id(mount, new_id)
read_id = robot._driver.read_pipette_id(mount)
_assert_the_same(new_id, read_id)
robot._driver.write_pipette_model(mount, new_mod... | def write_identifiers(robot, mount, new_id, new_model) | Send a bytearray to the specified mount, so that Smoothieware can
save the bytes to the pipette's memory | 3.471436 | 1.872872 | 1.853536 |
'''
User can enter a serial number as a string of HEX values
Length of byte array must equal `num`
'''
barcode = input('BUTTON + SCAN: ').strip()
if len(barcode) > max_length:
raise Exception(BAD_BARCODE_MESSAGE.format(barcode))
# remove all characters before the letter P
# for e... | def _user_submitted_barcode(max_length) | User can enter a serial number as a string of HEX values
Length of byte array must equal `num` | 11.316085 | 6.345637 | 1.783286 |
try:
if mounted:
LOG.info(f"Starting {unitname}")
interface().StartUnit(unitname, 'replace')
LOG.info(f"Started {unitname}")
else:
LOG.info(f"Stopping {unitname}")
interface().StopUnit(unitname, 'replace')
LOG.info(f"Stoppe... | def set_mounted(unitname: str, mounted: bool, swallow_exc: bool = False) | Mount or unmount a unit.
Worker for the contextlibs
:param unitname: The systemd unit for the mount to affect. This probably
should be one of :py:attr:`_SYSROOT_INACTIVE_UNIT` or
:py:attr:`_BOOT_UNIT` but it could be anything
:param mounted: ``True`` to start the ... | 2.795484 | 2.745826 | 1.018085 |
@functools.wraps(handler)
async def decorated(request: web.Request) -> web.Response:
request_session_token = request.match_info['session']
session = session_from_request(request)
if not session or request_session_token != session.token:
LOG.warning(f"request for invalid ... | def require_session(handler) | Decorator to ensure a session is properly in the request | 2.804289 | 2.748744 | 1.020207 |
if None is not session_from_request(request):
LOG.warning("begin: requested with active session")
return web.json_response(
data={'message':
'An update session is already active on this robot',
'error': 'session-already-active'},
statu... | async def begin(request: web.Request) -> web.Response | Begin a session | 6.108793 | 5.72573 | 1.066902 |
session.set_stage(Stages.VALIDATING)
validation_future \
= asyncio.ensure_future(loop.run_in_executor(
None, validate_update,
downloaded_update_path, session.set_progress))
def validation_done(fut):
exc = fut.exception()
if exc:
session.set_... | def _begin_validation(
session: UpdateSession,
loop: asyncio.AbstractEventLoop,
downloaded_update_path: str,
robot_name: str) -> asyncio.futures.Future | Start the validation process. | 4.028245 | 3.765315 | 1.06983 |
if session.stage != Stages.DONE:
return web.json_response(
data={'error': 'not-ready',
'message': f'System is not ready to commit the update '
f'(currently {session.stage.value.short})'},
status=409)
with dbus_actions.unmount_boot():
... | async def commit(
request: web.Request, session: UpdateSession) -> web.Response | Serves /update/:session/commit | 7.324965 | 6.985486 | 1.048598 |
session = session_from_request(request)
if session and session.stage != Stages.READY_FOR_RESTART:
return web.json_response(
data={'error': 'not-ready',
'message': 'System is not ready to restart '
f'(currently {session.stage.value.short})'},
... | async def restart(request: web.Request) -> web.Response | Serves /update/server/restart | 5.718405 | 5.4431 | 1.050579 |
if path and os.path.exists(path):
with open(path) as pkg:
package_dict = json.load(pkg)
version = package_dict.get('version')
else:
version = 'not available'
return version | def get_version(path) -> str | Reads the version field from a package file
:param path: the path to a valid package.json file
:return: the version string or "unknown" | 3.345582 | 3.291223 | 1.016516 |
# probe_dimensions is the external bounding box of the probe unit
size_x, size_y, size_z = tip_probe_settings.dimensions
rel_x_start = (size_x / 2) + tip_probe_settings.switch_clearance
rel_y_start = (size_y / 2) + tip_probe_settings.switch_clearance
# Ensure that the nozzle will clear the pr... | def calculate_tip_probe_hotspots(
tip_length: float,
tip_probe_settings: tip_probe_config)\
-> List[HotSpot] | Generate a list of tuples describing motions for doing the xy part of
tip probe based on the config's description of the tip probe box. | 3.305478 | 3.315714 | 0.996913 |
_write_value(pin, "{}/export".format(_path_prefix))
_write_value(direction, "{0}/gpio{1}/direction".format(_path_prefix, pin)) | def _enable_pin(pin, direction) | In order to enable a GPIO pin, the pin number must be written into
/sys/class/gpio/export, and then the direction ("in" or "out" must be
written to /sys/class/gpio/gpio<number>/direction
:param pin: An integer corresponding to the GPIO number of the pin in RPi
GPIO board numbering (not physical pin n... | 7.509767 | 7.073768 | 1.061636 |
base_command = "echo '{0}' > {1}"
# There is no common method for redirecting stderr to a null sink, so the
# command string is platform-dependent
if platform == 'win32':
command = "{0} > NUL".format(base_command)
else:
command = "exec 2> /dev/null; {0}".format(base_command)
... | def _write_value(value, path) | Writes specified value into path. Note that the value is wrapped in single
quotes in the command, to prevent injecting bash commands.
:param value: The value to write (usually a number or string)
:param path: A valid system path | 5.025943 | 5.072772 | 0.990769 |
read_value = 0
if not os.path.exists(path):
# Path will generally only exist on a Raspberry Pi
pass
else:
with open(path) as f:
read_value = int(f.read())
return read_value | def _read_value(path) | Reads value of specified path.
:param path: A valid system path | 4.764271 | 5.838871 | 0.815958 |
for pin in sorted(OUTPUT_PINS.values()):
_enable_pin(pin, OUT)
for pin in sorted(INPUT_PINS.values()):
_enable_pin(pin, IN) | def initialize() | All named pins in OUTPUT_PINS and INPUT_PINS are exported, and set the
HALT pin high (normal running state), since the default value after export
is low. | 4.305848 | 3.287889 | 1.309609 |
app = web.Application(loop=loop, middlewares=[error_middleware])
if hardware:
checked_hardware = hardware
else:
checked_hardware = opentrons.hardware
app['com.opentrons.hardware'] = checked_hardware
app['com.opentrons.rpc'] = RPCServer(app, MainRouter(checked_hardware))
app... | def init(loop=None, hardware: 'HardwareAPILike' = None) | Builds an application and sets up RPC and HTTP servers with it.
:param loop: A specific aiohttp event loop to use. If not specified, the
server will use the default event loop.
:param hardware: The hardware manager or hardware adapter to connect to.
If not specified, the s... | 4.666831 | 4.033568 | 1.156998 |
if path:
log.debug("Starting Opentrons server application on {}".format(
path))
hostname, port = None, None
else:
log.debug("Starting Opentrons server application on {}:{}".format(
hostname, port))
path = None
web.run_app(init(loop), host=hostnam... | def run(hostname=None, port=None, path=None, loop=None) | The arguments are not all optional. Either a path or hostname+port should
be specified; you have to specify one. | 3.823271 | 3.515239 | 1.087628 |
if IS_ROBOT and os.path.isdir('/dev/modules'):
devices = os.listdir('/dev/modules')
else:
devices = []
discovered_modules = []
module_port_regex = re.compile('|'.join(MODULE_TYPES.keys()), re.I)
for port in devices:
match = module_port_regex.search(port)
if mat... | def discover() -> List[Tuple[str, str]] | Scan for connected modules and instantiate handler classes | 3.305241 | 3.081205 | 1.07271 |
simulating = module.is_simulated
cls = type(module)
old_port = module.port
flash_port = await module.prep_for_update()
callback = module.interrupt_callback
del module
after_port, results = await update.update_firmware(flash_port,
fi... | async def update_firmware(
module: AbstractModule,
firmware_file: str,
loop: Optional[asyncio.AbstractEventLoop]) -> AbstractModule | Update a module.
If the update succeeds, an Module instance will be returned.
Otherwise, raises an UpdateError with the reason for the failure. | 5.294249 | 5.507369 | 0.961303 |
def defaults(_x, _y, _z):
_x = _x if x is not None else 0
_y = _y if y is not None else 0
_z = _z if z is not None else 0
return _x, _y, _z
dst_x, dst_y, dst_z = change_base(
pose_tree,
src=self._src,
dst=self.... | def move(self, pose_tree, x=None, y=None, z=None, home_flagged_axes=True) | Dispatch move command to the driver changing base of
x, y and z from source coordinate system to destination.
Value must be set for each axis that is mapped.
home_flagged_axes: (default=True)
This kwarg is passed to the driver. This ensures that any axes
within this Mov... | 2.981357 | 2.733396 | 1.090715 |
filenames = [ROOTFS_NAME, ROOTFS_HASH_NAME, BOOT_NAME, BOOT_HASH_NAME]
def zip_callback(progress):
progress_callback(progress/3.0)
files, sizes = unzip_update(filepath, zip_callback, filenames, filenames)
def rootfs_hash_callback(progress):
progress_callback(progress/3.0 + 0.33)
... | def validate_update(
filepath: str,
progress_callback: Callable[[float], None]) -> Tuple[str, str] | Like otupdate.buildroot.file_actions.validate_update but moreso
Checks for the rootfs, rootfs hash, bootfs, and bootfs hash.
Returns the path to the rootfs and the path to the bootfs | 2.100839 | 2.031687 | 1.034037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.