code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return [
Well(
self._well_definition[well],
Location(self._calibrated_offset, self),
"{} of {}".format(well, self._display_name),
self.is_tiprack)
for well in self._ordering] | def _build_wells(self) -> List[Well] | This function is used to create one instance of wells to be used by all
accessor functions. It is only called again if a new offset needs
to be applied. | 9.634653 | 8.232085 | 1.170378 |
dict_list = defaultdict(list)
for index, well_obj in zip(self._ordering, self._wells):
dict_list[self._pattern.match(index).group(group)].append(well_obj)
return dict_list | def _create_indexed_dictionary(self, group=0) | Creates a dict of lists of Wells. Which way the labware is segmented
determines whether this is a dict of rows or dict of columns. If group
is 1, then it will collect wells that have the same alphabetic prefix
and therefore are considered to be in the same row. If group is 2, it
will col... | 5.420643 | 4.062906 | 1.334179 |
self._calibrated_offset = Point(x=self._offset.x + delta.x,
y=self._offset.y + delta.y,
z=self._offset.z + delta.z)
self._wells = self._build_wells() | def set_calibration(self, delta: Point) | Called by save calibration in order to update the offset on the object. | 3.262391 | 2.768042 | 1.178592 |
if isinstance(idx, int):
res = self._wells[idx]
elif isinstance(idx, str):
res = self.wells_by_index()[idx]
else:
res = NotImplemented
return res | def well(self, idx) -> Well | Deprecated---use result of `wells` or `wells_by_index` | 3.113274 | 2.442976 | 1.274378 |
if not args:
res = self._wells
elif isinstance(args[0], int):
res = [self._wells[idx] for idx in args]
elif isinstance(args[0], str):
res = [self.wells_by_index()[idx] for idx in args]
else:
raise TypeError
return res | def wells(self, *args) -> List[Well] | Accessor function used to generate a list of wells in top -> down,
left -> right order. This is representative of moving down `rows` and
across `columns` (e.g. 'A1', 'B1', 'C1'...'A2', 'B2', 'C2')
With indexing one can treat it as a typical python
list. To access well A1, for example, s... | 2.254891 | 2.777354 | 0.811884 |
return {well: wellObj
for well, wellObj in zip(self._ordering, self._wells)} | def wells_by_index(self) -> Dict[str, Well] | Accessor function used to create a look-up table of Wells by name.
With indexing one can treat it as a typical python
dictionary whose keys are well names. To access well A1, for example,
simply write: labware.wells_by_index()['A1']
:return: Dictionary of well objects keyed by well nam... | 10.770281 | 11.576035 | 0.930395 |
row_dict = self._create_indexed_dictionary(group=1)
keys = sorted(row_dict)
if not args:
res = [row_dict[key] for key in keys]
elif isinstance(args[0], int):
res = [row_dict[keys[idx]] for idx in args]
elif isinstance(args[0], str):
r... | def rows(self, *args) -> List[List[Well]] | Accessor function used to navigate through a labware by row.
With indexing one can treat it as a typical python nested list.
To access row A for example, simply write: labware.rows()[0]. This
will output ['A1', 'A2', 'A3', 'A4'...]
Note that this method takes args for backward-compatib... | 2.756173 | 3.415695 | 0.806914 |
row_dict = self._create_indexed_dictionary(group=1)
return row_dict | def rows_by_index(self) -> Dict[str, List[Well]] | Accessor function used to navigate through a labware by row name.
With indexing one can treat it as a typical python dictionary.
To access row A for example, simply write: labware.rows_by_index()['A']
This will output ['A1', 'A2', 'A3', 'A4'...].
:return: Dictionary of Well lists keyed... | 14.834344 | 27.953472 | 0.53068 |
col_dict = self._create_indexed_dictionary(group=2)
keys = sorted(col_dict, key=lambda x: int(x))
if not args:
res = [col_dict[key] for key in keys]
elif isinstance(args[0], int):
res = [col_dict[keys[idx]] for idx in args]
elif isinstance(args[0... | def columns(self, *args) -> List[List[Well]] | Accessor function used to navigate through a labware by column.
With indexing one can treat it as a typical python nested list.
To access row A for example,
simply write: labware.columns()[0]
This will output ['A1', 'B1', 'C1', 'D1'...].
Note that this method takes args for bac... | 2.768221 | 3.30922 | 0.836518 |
col_dict = self._create_indexed_dictionary(group=2)
return col_dict | def columns_by_index(self) -> Dict[str, List[Well]] | Accessor function used to navigate through a labware by column name.
With indexing one can treat it as a typical python dictionary.
To access row A for example,
simply write: labware.columns_by_index()['1']
This will output ['A1', 'B1', 'C1', 'D1'...].
:return: Dictionary of We... | 17.670406 | 28.235235 | 0.625828 |
assert num_tips > 0
columns: List[List[Well]] = self.columns()
drop_leading_empties = [
list(dropwhile(lambda x: not x.has_tip, column))
for column in columns]
drop_at_first_gap = [
list(takewhile(lambda x: x.has_tip, column))
for... | def next_tip(self, num_tips: int = 1) -> Optional[Well] | Find the next valid well for pick-up.
Determines the next valid start tip from which to retrieve the
specified number of tips. There must be at least `num_tips` sequential
wells for which all wells have tips, in the same column.
:param num_tips: target number of sequential tips in the ... | 2.972055 | 3.229829 | 0.92019 |
assert num_channels > 0, 'Bad call to use_tips: num_channels==0'
# Select the column of the labware that contains the target well
target_column: List[Well] = [
col for col in self.columns() if start_well in col][0]
well_idx = target_column.index(start_well)
... | def use_tips(self, start_well: Well, num_channels: int = 1) | Removes tips from the tip tracker.
This method should be called when a tip is picked up. Generally, it
will be called with `num_channels=1` or `num_channels=8` for single-
and multi-channel respectively. If picking up with more than one
channel, this method will automatically determine ... | 4.05491 | 3.916296 | 1.035394 |
log.debug('Update Firmware request received')
data = await request.post()
module_serial = request.match_info['serial']
res = await _update_module_firmware(request.app['com.opentrons.hardware'],
module_serial,
data['mod... | async def update_module_firmware(request) | This handler accepts a POST request with Content-Type: multipart/form-data
and a file field in the body named "module_firmware". The file should
be a valid HEX image to be flashed to the atmega32u4. The received file is
sent via USB to the board and flashed by the avr109 bootloader. The file
is then... | 3.520219 | 3.334411 | 1.055724 |
# ensure there is a reference to the port
if not hw.is_connected():
hw.connect()
hw.discover_modules()
hw_mods = hw.attached_modules.values()
res = {}
for module in hw_mods:
if module.device_info.get('serial') == serialnum:
log.info("Module with serial {} foun... | async def _upload_to_module(hw, serialnum, fw_filename, loop) | This method remains in the API currently because of its use of the robot
singleton's copy of the api object & driver. This should move to the server
lib project eventually and use its own driver object (preferably involving
moving the drivers themselves to the serverlib) | 4.888573 | 4.742706 | 1.030756 |
@functools.wraps(handler)
async def decorated(request: web.Request) -> web.Response:
ipaddr_str = request.headers.get('x-host-ip')
invalid_req_data = {
'error': 'bad-interface',
'message': f'The endpoint {request.url} can only be used from '
'local connec... | def require_linklocal(handler) | Ensure the decorated is only called if the request is linklocal.
The host ip address should be in the X-Host-IP header (provided by nginx) | 2.860966 | 2.756748 | 1.037805 |
path = '/var/home/.ssh/authorized_keys'
if not os.path.exists(path):
os.makedirs(os.path.dirname(path))
open(path, 'w').close()
with open(path, mode) as ak:
yield ak | def authorized_keys(mode='r') | Open the authorized_keys file. Separate function for mocking.
:param mode: As :py:meth:`open` | 3.053229 | 3.583788 | 0.851956 |
with authorized_keys() as ak:
return [(hashlib.new('md5', line.encode()).hexdigest(),
line)
for line in ak.read().split('\n')
if line.strip()] | def get_keys() -> List[Tuple[str, str]] | Return a list of tuples of [md5(pubkey), pubkey] | 5.480144 | 4.896074 | 1.119294 |
key_details = get_keys()
with authorized_keys('w') as ak:
for keyhash, key in key_details:
if keyhash != hashval:
ak.write(f'{key}\n')
break
else:
raise KeyError(hashval) | def remove_by_hash(hashval: str) | Remove the key whose md5 sum matches hashval.
:raises: KeyError if the hashval wasn't found | 7.332989 | 6.742921 | 1.087509 |
return web.json_response(
{'public_keys': [{'key_md5': details[0], 'key': details[1]}
for details in get_keys()]},
status=200) | async def list_keys(request: web.Request) -> web.Response | List keys in the authorized_keys file.
GET /server/ssh_keys
-> 200 OK {"public_keys": [{"key_md5": md5 hex digest, "key": key string}]}
(or 403 if not from the link-local connection) | 6.293835 | 3.48009 | 1.808526 |
body = await request.json()
if 'key' not in body or not isinstance(body['key'], str):
return web.json_response(
data={'error': 'no-key', 'message': 'No "key" element in body'},
status=400)
pubkey = body['key']
# Do some fairly minor sanitization; dropbear will ignore... | async def add(request: web.Request) -> web.Response | Add a public key to the authorized_keys file.
POST /server/ssh_keys {"key": key string}
-> 201 Created
If the key string doesn't look like an openssh public key, rejects with 400 | 5.0001 | 4.516578 | 1.107055 |
requested_hash = request.match_info['key_md5']
new_keys: List[str] = []
found = False
for keyhash, key in get_keys():
if keyhash == requested_hash:
found = True
else:
new_keys.append(key)
if not found:
return web.json_response(
data={... | async def remove(request: web.Request) -> web.Response | Remove a public key from authorized_keys
DELETE /server/ssh_keys/:key_md5_hexdigest
-> 200 OK if the key was found
-> 404 Not Found otherwise | 3.794435 | 3.313629 | 1.145099 |
fallback_log_level = 'INFO'
ot_log_level = hardware.config.log_level
if ot_log_level not in logging._nameToLevel:
log.info("OT Log Level {} not found. Defaulting to {}".format(
ot_log_level, fallback_log_level))
ot_log_level = fallback_log_level
level_value = logging._n... | def log_init() | Function that sets log levels and format strings. Checks for the
OT_API_LOG_LEVEL environment variable otherwise defaults to DEBUG. | 1.732814 | 1.716841 | 1.009304 |
log_init()
loop = asyncio.get_event_loop()
log.info("API server version: {}".format(__version__))
if not os.environ.get("ENABLE_VIRTUAL_SMOOTHIE"):
initialize_robot(loop)
if ff.use_protocol_api_v2():
loop.run_until_complete(hardware.cache_instruments())
if not f... | def run(**kwargs) | This function was necessary to separate from main() to accommodate for
server startup path on system 3.0, which is server.main. In the case where
the api is on system 3.0, server.main will redirect to this function with
an additional argument of 'patch_old_init'. kwargs are hence used to allow
the use o... | 6.628871 | 6.624019 | 1.000732 |
arg_parser = ArgumentParser(
description="Opentrons robot software",
parents=[build_arg_parser()])
args = arg_parser.parse_args()
run(**vars(args))
arg_parser.exit(message="Stopped\n") | def main() | The main entrypoint for the Opentrons robot API server stack.
This function
- creates and starts the server for both the RPC routes
handled by :py:mod:`opentrons.server.rpc` and the HTTP routes handled
by :py:mod:`opentrons.server.http`
- initializes the hardware interaction handled by either
... | 6.162992 | 5.572075 | 1.10605 |
import shutil
import subprocess
rules_file = os.path.join(
os.path.abspath(os.path.dirname(__file__)), '..',
'config', 'modules', '95-opentrons-modules.rules')
shutil.copy2(
rules_file,
'/data/user_storage/opentrons_data/95-opentrons-modules.rules')
res0 = sub... | def setup_rules_file() | Copy the udev rules file for Opentrons Modules to opentrons_data directory
and trigger the new rules.
This rules file in opentrons_data is symlinked into udev rules directory
TODO: Move this file to resources and move the symlink to point to
/data/system/ | 3.076126 | 2.691089 | 1.143078 |
async with request.app[RESTART_LOCK_NAME]:
asyncio.get_event_loop().call_later(1, _do_restart)
return web.json_response({'message': 'Restarting in 1s'},
status=200) | async def restart(request: web.Request) -> web.Response | Restart the robot.
Blocks while the restart lock is held. | 4.742178 | 4.317592 | 1.098339 |
async def health(request: web.Request) -> web.Response:
return web.json_response(
{
'name': request.app[DEVICE_NAME_VARNAME],
'updateServerVersion': version_dict.get(
'update_server_version', 'unknown'),
'serialNumber': get... | def build_health_endpoint(
version_dict: Mapping[str, str])\
-> Callable[[web.Request],
Coroutine[None, None, web.Response]] | Build a coroutine to serve /health that captures version info | 4.450909 | 4.321624 | 1.029916 |
tmp_dir = tempfile.mkdtemp()
venv_dir = os.path.join(tmp_dir, VENV_NAME)
proc1 = await asyncio.create_subprocess_shell(
'virtualenv {}'.format(venv_dir), loop=loop)
await proc1.communicate()
if sys.platform == 'win32':
python = os.path.join(venv_dir, 'Scripts', 'python.exe')
... | async def create_virtual_environment(loop=None) | Create a virtual environment, and return the path to the virtual env
directory, which should contain a "bin" directory with the `python` and
`pip` binaries that can be used to a test install of a software package.
:return: the path to the virtual environment, its python, and its site pkgs | 2.34036 | 2.251876 | 1.039294 |
# Import all of the packages that need to be available in the virtualenv
# for the update server to boot, so we can locate them using their __file__
# attribute
import aiohttp
import virtualenv_support
import async_timeout
import chardet
import multidict
import yarl
import i... | def install_dependencies(python) -> str | Copy aiohttp and virtualenv install locations (and their transitive
dependencies in new virtualenv so that the update server can install
without access to full system site-packages or connection to the internet.
Full access to system site-packages causes the install inside the
virtualenv to fail quietly... | 3.148785 | 2.951947 | 1.066681 |
log.info("Starting sandboxed update server on port {}".format(port))
if venv_site_pkgs:
python = 'PYTHONPATH={} {}'.format(venv_site_pkgs, python)
cmd = [python, '-m', 'otupdate', '--debug', '--test', '--port', str(port)]
log.debug('cmd: {}'.format(' '.join(cmd)))
proc = sp.Popen(' '.jo... | async def _start_server(python, port,
venv_site_pkgs=None, cwd=None) -> sp.Popen | Starts an update server sandboxed in the virtual env, and attempts to read
the health endpoint with retries to determine when the server is available.
If the number of retries is exceeded, the returned server process will
already be terminated.
:return: the server process | 3.657757 | 3.453361 | 1.059188 |
log.debug("Creating virtual environment")
venv_dir, python, venv_site_pkgs\
= await create_virtual_environment(loop=loop)
log.debug("Installing update server into virtual environment")
out, err, returncode = await _install(python, filename, loop)
if err or returncode != 0:
log.e... | async def install_sandboxed_update(filename, loop) | Create a virtual environment and activate it, and then install an
update candidate (leaves virtual environment activated)
:return: a result dict and the path to python in the virtual environment | 3.977254 | 3.622319 | 1.097986 |
log.info("Installing update server into system environment")
log.debug('File {} exists? {}'.format(filename, os.path.exists(filename)))
out, err, returncode = await _install(sys.executable, filename, loop)
if returncode == 0:
msg = out
else:
msg = err
res = {'message': msg, ... | async def install_update(filename, loop) | Install the update into the system environment. | 4.953872 | 4.364278 | 1.135095 |
# Note: input list shape validation is handled by the type checker
# Turn expected and actual matricies into numpy ndarrays with the last row
# of [1 1 1] appended, and then take the dot product of the resulting
# actual matrix with the inverse of the resulting expected matrix.
# Shape of `ex... | def solve(expected: List[Tuple[float, float]],
actual: List[Tuple[float, float]]) -> np.ndarray | Takes two lists of 3 x-y points each, and calculates the matrix
representing the transformation from one space to the other.
The 3x3 matrix returned by this method represents the 2-D transformation
matrix from the actual point to the expected point.
Example:
If the expected points are:
... | 5.368338 | 5.292339 | 1.01436 |
# First, insert a column of zeros as into the input matrix
interm = insert(xy, 2, [0, 0, 0], axis=1)
# Result:
# [ 1 0 0 x ]
# [ 0 1 0 y ]
# [ 0 0 0 1 ]
# Then, insert the z row to create a properly formed 3-D transform matrix:
xyz = insert(
interm,
2,
... | def add_z(xy: np.ndarray, z: float) -> np.ndarray | Turn a 2-D transform matrix into a 3-D transform matrix (scale/shift only,
no rotation).
:param xy: A two-dimensional transform matrix (a 3x3 numpy ndarray) in the
following form:
[ 1 0 x ]
[ 0 1 y ]
[ 0 0 1 ]
:param z: a float for the z component
:retu... | 3.658446 | 2.959712 | 1.236082 |
extended = 1 if with_offsets else 0
return tuple(dot(t, list(pos) + [extended])[:3]) | def apply_transform(
t: Union[List[List[float]], np.ndarray],
pos: Tuple[float, float, float],
with_offsets=True) -> Tuple[float, float, float] | Change of base using a transform matrix. Primarily used to render a point
in space in a way that is more readable for the user.
:param t: A transformation matrix from one 3D space [A] to another [B]
:param pos: XYZ point in space A
:param with_offsets: Whether to apply the transform as an affine transf... | 7.420773 | 11.095067 | 0.668835 |
return apply_transform(inv(t), pos) | def apply_reverse(
t: Union[List[List[float]], np.ndarray],
pos: Tuple[float, float, float],
with_offsets=True) -> Tuple[float, float, float] | Like apply_transform but inverts the transform first | 17.340731 | 10.627815 | 1.631636 |
if os.path.exists(database_path):
os.remove(database_path)
# Not an os.path.join because it is a suffix to the full filename
journal_path = database_path + '-journal'
if os.path.exists(journal_path):
os.remove(journal_path) | def reset() | Unmount and remove the sqlite database (used in robot reset) | 4.622793 | 4.280404 | 1.07999 |
log.info('Restarting server')
sleep(1)
# We can use the default event loop here because this
# is actually running in a thread. We use aiohttp here because urllib is
# painful and we don’t have `requests`.
loop = asyncio.new_event_loop()
loop.run_until_complete(_resin_supervisor_restart... | def __wait_and_restart() | Delay and then execute the restart. Do not call directly. Instead, call
`do_restart()`. | 11.086991 | 11.22365 | 0.987824 |
supervisor = os.environ.get('RESIN_SUPERVISOR_ADDRESS',
'http://127.0.0.1:48484')
restart_url = supervisor + '/v1/restart'
api = os.environ.get('RESIN_SUPERVISOR_API_KEY', 'unknown')
app_id = os.environ.get('RESIN_APP_ID', 'unknown')
async with aiohttp.ClientSess... | async def _resin_supervisor_restart() | Execute a container restart by requesting it from the supervisor.
Note that failures here are returned but most likely will not be
sent back to the caller, since this is run in a separate workthread.
If the system is not responding, look for these log messages. | 2.666636 | 2.674227 | 0.997161 |
self._hardware.connect(port) | def connect(self, port: str = None,
options: Any = None) | Connect to the robot hardware.
This function is provided for backwards compatibility. In most cases
it need not be called.
Calls to this method should be replaced with calls to
:py:meth:`.ProtocolContext.connect` (notice the difference in
arguments) if necessary; however, since... | 65.594803 | 38.570408 | 1.700651 |
def initializer(
self,
mount: str,
trash_container: Labware = None,
tip_racks: List[Labware] = None,
aspirate_flow_rate: float = None,
dispense_flow_rate: float = None,
min_volume: float = No... | def _build_initializer(model, proper_name) | Build an initializer function for a given pipette.
This is a separate function so that the `proper_name` is correctly
caught in the closure that it returns. | 4.91187 | 4.217913 | 1.164526 |
return ctx.load_instrument(name, Mount[mount.upper()]) | def _load_instr(ctx,
name: str,
mount: str,
*args, **kwargs) -> InstrumentContext | Build an instrument in a backwards-compatible way.
You should almost certainly not be calling this function from a
protocol; if you want to create a pipette on a lower level, use
:py:meth:`.ProtocolContext.load_instrument` directly, and if you
want to create an instrument easily use one... | 11.204335 | 13.348964 | 0.839341 |
if share:
raise NotImplementedError("Sharing not supported")
try:
name = self.LW_TRANSLATION[container_name]
except KeyError:
if container_name in self.LW_NO_EQUIVALENT:
raise NotImplementedError("Labware {} is not supported"
... | def load(self, container_name, slot, label=None, share=False) | Load a piece of labware by specifying its name and position.
This method calls :py:meth:`.ProtocolContext.load_labware_by_name`;
see that documentation for more information on arguments and return
values. Calls to this function should be replaced with calls to
:py:meth:`.Protocolcontext... | 4.635514 | 4.352559 | 1.065009 |
normalized = get_version(project)
sha = subprocess.check_output(
['git', 'rev-parse', 'HEAD'], cwd=HERE).strip()
branch = subprocess.check_output(
['git', 'rev-parse', '--abbrev-ref', 'HEAD'], cwd=HERE).strip()
pref = br_version_prefixes[project]
return json.dumps({pref+'_versio... | def dump_br_version(project) | Dump an enhanced version json including
- The version from package.json
- The current branch (if it can be found)
- The current sha | 3.375163 | 3.190247 | 1.057963 |
default_aspirate = default_values.get(
'aspirate-flow-rate', {}).get(pipette_name)
default_dispense = default_values.get(
'dispense-flow-rate', {}).get(pipette_name)
flow_rate_param = params.get('flow-rate')
if flow_rate_param is not None:
if command_type == 'aspirate':
... | def _set_flow_rate(
pipette_name, pipette, command_type, params, default_values) | Set flow rate in uL/mm, to value obtained from command's params,
or if unspecified in command params, then from protocol's "default-values". | 1.72284 | 1.708244 | 1.008545 |
loop = asyncio.new_event_loop()
kwargs['loop'] = loop
args = [arg for arg in args
if not isinstance(arg, asyncio.AbstractEventLoop)]
if asyncio.iscoroutinefunction(builder):
checked_loop = build_loop or asyncio.get_event_loop()
api = check... | def build(cls, builder, *args, build_loop=None, **kwargs) | Build a hardware control API and initialize the adapter in one call
:param builder: the builder method to use (e.g.
:py:meth:`hardware_control.API.build_hardware_simulator`)
:param args: Args to forward to the builder method
:param kwargs: Kwargs to forward to the builde... | 2.837952 | 3.028268 | 0.937154 |
old_api = object.__getattribute__(self, '_api')
loop = old_api._loop
new_api = loop.run_until_complete(API.build_hardware_controller(
loop=loop,
port=port,
config=copy.copy(old_api.config),
force=force))
old_api._loop.run_until_com... | def connect(self, port: str = None, force: bool = False) | Connect to hardware.
:param port: The port to connect to. May be `None`, in which case the
hardware will connect to the first serial port it sees
with the device name `FT232R`; or port name compatible
with `serial.Serial<https://pythonhosted.org/py... | 4.671553 | 4.568412 | 1.022577 |
old_api = object.__getattribute__(self, '_api')
new_api = API.build_hardware_simulator(
loop=old_api._loop,
config=copy.copy(old_api.config))
setattr(self, '_api', new_api) | def disconnect(self) | Disconnect from connected hardware. | 6.743532 | 6.210732 | 1.085787 |
api = object.__getattribute__(self, '_api')
instrs = {}
for mount, data in api.attached_instruments.items():
instrs[mount.name.lower()] = {
'model': data.get('name', None),
'id': data.get('pipette_id', None),
'mount_axis': Axis... | def get_attached_pipettes(self) | Mimic the behavior of robot.get_attached_pipettes | 3.173629 | 3.015917 | 1.052293 |
assert chunk_size
total_size = 0
written_size = 0
to_unzip: List[zipfile.ZipInfo] = []
file_paths: Dict[str, Optional[str]] = {fn: None
for fn in acceptable_files}
file_sizes: Dict[str, int] = {fn: 0 for fn in acceptable_files}
LOG.info(f"Unzi... | def unzip_update(filepath: str,
progress_callback: Callable[[float], None],
acceptable_files: Sequence[str],
mandatory_files: Sequence[str],
chunk_size: int = 1024) -> Tuple[Mapping[str, Optional[str]],
... | Unzip an update file
The update file must contain
- a file called rootfs.ext4
- a file called rootfs.ext4.hash
It may contain
- a file called rootfs.ext4.hash.sig
These will all be unzipped (discarding their leading directories) to
the same file as the zipfile.
This function is blo... | 1.978459 | 2.019176 | 0.979835 |
hasher = hashlib.new(algo)
have_read = 0
if not chunk_size:
chunk_size = 1024
with open(path, 'rb') as to_hash:
if not file_size:
file_size = to_hash.seek(0, 2)
to_hash.seek(0)
while True:
chunk = to_hash.read(chunk_size)
hashe... | def hash_file(path: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None,
algo: str = 'sha256') -> bytes | Hash a file and return the hash, providing progress callbacks
:param path: The file to hash
:param progress_callback: The callback to call with progress between 0 and
1. May not ever be precisely 1.0.
:param chunk_size: If specified, the size of the chunks to hash in one call
... | 1.882229 | 1.963041 | 0.958833 |
with tempfile.TemporaryDirectory() as pubkey_dir:
pubkey_contents = subprocess.check_output(
['openssl', 'x509', '-in', cert_path,
'-pubkey', '-noout'])
pubkey_file = os.path.join(pubkey_dir, 'pubkey')
open(pubkey_file, 'wb').write(pubkey_contents)
try:
... | def verify_signature(message_path: str,
sigfile_path: str,
cert_path: str) -> None | Verify the signature (assumed, of the hash file)
It is assumed that the public key for the signature is in the keyring
:param message_path: The path to the message file to check
:param sigfile_path: The path to the signature to check
:param cert_path: The path to the certificate to check the signature... | 2.414537 | 2.529092 | 0.954705 |
def zip_callback(progress):
progress_callback(progress/2.0)
required = [ROOTFS_NAME, ROOTFS_HASH_NAME]
if cert_path:
required.append(ROOTFS_SIG_NAME)
files, sizes = unzip_update(filepath, zip_callback,
UPDATE_FILES,
r... | def validate_update(filepath: str,
progress_callback: Callable[[float], None],
cert_path: Optional[str]) | Worker for validation. Call in an executor (so it can return things)
- Unzips filepath to its directory
- Hashes the rootfs inside
- If requested, checks the signature of the hash
:param filepath: The path to the update zip file
:param progress_callback: The function to call with progress between 0... | 3.329878 | 2.982724 | 1.116388 |
which = subprocess.check_output(['ot-unused-partition']).strip()
return {b'2': RootPartitions.TWO,
b'3': RootPartitions.THREE}[which] | def _find_unused_partition() -> RootPartitions | Find the currently-unused root partition to write to | 8.55232 | 8.025799 | 1.065604 |
total_written = 0
with open(infile, 'rb') as img, open(outfile, 'wb') as part:
if None is file_size:
file_size = img.seek(0, 2)
img.seek(0)
LOG.info(f'write_file: file size calculated as {file_size}B')
LOG.info(f'write_file: writing {infile} ({file_size}B... | def write_file(infile: str,
outfile: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None) | Write a file to another file with progress callbacks.
:param infile: The input filepath
:param outfile: The output filepath
:param progress_callback: The callback to call for progress
:param chunk_size: The size of file chunks to copy in between progress
notifications
:param ... | 2.397634 | 2.571637 | 0.932338 |
unused = _find_unused_partition()
part_path = unused.value.path
write_file(rootfs_filepath, part_path, progress_callback,
chunk_size, file_size)
return unused | def write_update(rootfs_filepath: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None) -> RootPartitions | Write the new rootfs to the next root partition
- Figure out, from the system, the correct root partition to write to
- Write the rootfs at ``rootfs_filepath`` there, with progress
:param rootfs_filepath: The path to a checked rootfs.ext4
:param progress_callback: A callback to call periodically with ... | 5.979685 | 6.950851 | 0.860281 |
res = subprocess.check_output(['ot-switch-partitions'])
for line in res.split(b'\n'):
matches = re.match(
b'Current boot partition: ([23]), setting to ([23])',
line)
if matches:
return {b'2': RootPartitions.TWO,
b'3': RootPartitions.TH... | def _switch_partition() -> RootPartitions | Switch the active boot partition using the switch script | 4.469862 | 4.114993 | 1.086238 |
unused = _find_unused_partition()
new = _switch_partition()
if new != unused:
msg = f"Bad switch: switched to {new} when {unused} was unused"
LOG.error(msg)
raise RuntimeError(msg)
else:
LOG.info(f'commit_update: committed to booting {new}') | def commit_update() | Switch the target boot partition. | 8.164763 | 6.181557 | 1.320826 |
coordinates = None
placeable = None
if isinstance(location, Placeable):
placeable, coordinates = location.top()
elif isinstance(location, tuple):
placeable, coordinates = location
else:
raise ValueError(
'Location should be (Placeable, (x, y, z)) or Placeab... | def unpack_location(location) | Returns (:Placeable:, :Vector:) tuple
If :location: is :Placeable: it will get converted to
(:Placeable:, :Vector: corresponding to the top) | 4.346716 | 3.196082 | 1.360014 |
return list(reversed([item.get_name()
for item in self.get_trace(reference)
if item.get_name() is not None])) | def get_path(self, reference=None) | Returns list of names from :reference: to :self:
If :reference: is *None* root is assumed | 7.013985 | 5.25486 | 1.334761 |
item = self
while item:
yield item
if item == reference:
return
item = item.parent
if reference is not None:
raise Exception(
'Reference {} is not in Ancestry'.format(reference)) | def get_trace(self, reference=None) | Returns a generator of parents up to :reference:, including reference
If :reference: is *None* root is assumed
Closest ancestor goes first | 5.326379 | 4.252035 | 1.252666 |
coordinates = [i._coordinates for i in self.get_trace(reference)]
return functools.reduce(lambda a, b: a + b, coordinates) | def coordinates(self, reference=None) | Returns the coordinates of a :Placeable: relative to :reference: | 6.350924 | 6.305735 | 1.007166 |
if not name:
name = str(child)
if name in self.children_by_name:
raise RuntimeWarning(
'Child with name {} already in slot, use custom name'.format(
name))
if coordinates:
child._coordinates = Vector(coordinates)
... | def add(self, child, name=None, coordinates=None) | Adds child to the :Placeable:, storing it's :name: and :coordinates:
This method is used to add :Well:s to the :Container:,
add :Slot:s to :Deck:, etc | 3.777264 | 3.915782 | 0.964626 |
trace = self.get_trace()
# Find decks in trace, prepend with [None] in case nothing was found
res = [None] + [item for item in trace if isinstance(item, Deck)]
# Pop last (and hopefully only Deck) or None if there is no deck
return res.pop() | def get_deck(self) | Returns parent :Deck: of a :Placeable: | 10.594398 | 9.456057 | 1.120382 |
for md in SUPPORTED_MODULES:
maybe_module = self.get_child_by_name(md)
if maybe_module:
# No probability of a placeable having more than one module
return maybe_module
return None | def get_module(self) | Returns the module placeable if present | 9.302585 | 7.345454 | 1.266441 |
if isinstance(s.start, str):
s = slice(
self.get_index_from_name(s.start), s.stop, s.step)
if isinstance(s.stop, str):
s = slice(
s.start, self.get_index_from_name(s.stop), s.step)
return WellSeries(self.get_children_list()[s]) | def get_children_from_slice(self, s) | Retrieves list of children within slice | 2.912755 | 2.845611 | 1.023596 |
my_children = self.get_children_list()
children = []
children.extend(my_children)
for child in my_children:
children.extend(child.get_all_children())
return children | def get_all_children(self) | Returns all children recursively | 2.658085 | 2.450283 | 1.084807 |
center = self.size() / 2.0
r = r * center['x']
return center + Vector(r * math.cos(theta),
r * math.sin(theta),
center['z'] * h) | def from_polar(self, r, theta, h) | Converts polar coordiantes within a placeable into a :Vector:
The origin is assumed to be in the center of a Placeable
:r: is between -1.0 and 1.0, relative to max X
:h: is between -1.0 and 1.0, relative to max Z | 5.394063 | 5.1825 | 1.040822 |
center = self.size() / 2.0
return center + center * Vector(x, y, z) | def from_cartesian(self, x, y, z) | Converts cartesian coordinates within a placeable into a :Vector:
The origin is assumed to be in the center of a Placeable
:x:, :y:, :z: is between -1.0 and 1.0, relative to max X, Y, Z | 8.484793 | 8.32702 | 1.018947 |
return self.from_center(x=0.0, y=0.0, z=0.0, reference=reference) | def center(self, reference=None) | Returns :Vector: of the center for a :Placeable: relative
to the :reference: :Placeable:
Uses self as a :reference: if *None* is given | 4.388938 | 4.914287 | 0.893098 |
coordinates = self.from_center(
r=radius,
theta=(degrees / 180) * math.pi,
h=-1,
reference=reference)
return (self, coordinates + (0, 0, z)) | def bottom(self, z=0, radius=0, degrees=0, reference=None) | Returns (:Placeable, :Vector:) tuple where :Vector:
corresponds to the bottom of a :Placeable:
If :reference: :Placeable: is provided, returns
the :Vector: within :reference: coordinate system | 6.411291 | 7.115271 | 0.901061 |
coords_to_endpoint = None
if all([isinstance(i, numbers.Number) for i in (x, y, z)]):
coords_to_endpoint = self.from_cartesian(x, y, z)
if all([isinstance(i, numbers.Number) for i in (r, theta, h)]):
coords_to_endpoint = self.from_polar(r, theta, h)
coo... | def from_center(self, x=None, y=None, z=None, r=None,
theta=None, h=None, reference=None) | Accepts a set of (:x:, :y:, :z:) ratios for Cartesian or
(:r:, :theta:, :h:) rations/angle for Polar and returns
:Vector: using :reference: as origin | 2.237608 | 2.266427 | 0.987284 |
all_containers: List = list()
for slot in self:
all_containers += slot.get_children_list()
for container in all_containers:
if getattr(container, 'stackable', False):
all_containers += container.get_children_list()
return all_containers | def containers(self) -> list | Returns all containers on a deck as a list | 4.765173 | 3.932829 | 1.21164 |
if self.grid is None:
self.grid = self.get_wellseries(self.get_grid())
if self.grid_transposed is None:
self.grid_transposed = self.get_wellseries(
self.transpose(
self.get_grid())) | def calculate_grid(self) | Calculates and stores grid structure | 4.773037 | 4.378736 | 1.090049 |
columns = OrderedDict()
index_pattern = r'^([A-Za-z]+)([0-9]+)$'
for name in self.children_by_name:
match = re.match(index_pattern, name)
if match:
row, col = match.groups(0)
if col not in columns:
columns[col]... | def get_grid(self) | Calculates the grid inferring row/column structure
from indexes. Currently only Letter+Number names are supported | 3.541975 | 2.964496 | 1.194798 |
res = OrderedDict()
for row, cols in rows.items():
for col, cell in cols.items():
if col not in res:
res[col] = OrderedDict()
res[col][row] = cell
return res | def transpose(self, rows) | Transposes the grid to allow for cols | 2.695106 | 2.663871 | 1.011726 |
res = OrderedDict()
for col, cells in matrix.items():
if col not in res:
res[col] = OrderedDict()
for row, cell in cells.items():
res[col][row] = self.children_by_name[
''.join(cell)
]
res[co... | def get_wellseries(self, matrix) | Returns the grid as a WellSeries of WellSeries | 3.700952 | 3.488896 | 1.06078 |
if len(args) and isinstance(args[0], list):
args = args[0]
new_wells = None
if not args and not kwargs:
new_wells = WellSeries(self.get_children_list())
elif len(args) > 1:
new_wells = WellSeries([self.well(n) for n in args])
elif 'x... | def wells(self, *args, **kwargs) | Returns child Well or list of child Wells | 2.765097 | 2.667537 | 1.036573 |
'''
Returns the ascii value in the expected string "N:aa11bb22", where "N" is
the key, and "aa11bb22" is string value to be returned
'''
try:
value = substring.split(':')[1]
return str(value)
except (ValueError, IndexError, TypeError, AttributeError):
log.exception('Unexp... | def parse_string_value_from_substring(substring) -> str | Returns the ascii value in the expected string "N:aa11bb22", where "N" is
the key, and "aa11bb22" is string value to be returned | 5.64809 | 2.447828 | 2.307389 |
'''
Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", where "none" should return a None value
'''
try:
value = substr... | def parse_number_from_substring(substring) -> Optional[float] | Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", where "none" should return a None value | 5.830596 | 2.226311 | 2.61895 |
'''
Example input: "T:none C:25"
'''
err_msg = 'Unexpected argument to parse_temperature_response: {}'.format(
temperature_string)
if not temperature_string or \
not isinstance(temperature_string, str):
raise ParseError(err_msg)
parsed_values = temperature_string.stri... | def parse_temperature_response(
temperature_string: str) -> Mapping[str, Optional[float]] | Example input: "T:none C:25" | 2.913692 | 2.495095 | 1.167768 |
'''
Parse the modules's device information response.
Example response from temp-deck: "serial:aa11 model:bb22 version:cc33"
'''
error_msg = 'Unexpected argument to parse_device_information: {}'.format(
device_info_string)
if not device_info_string or \
not isinstance... | def parse_device_information(
device_info_string: str) -> Mapping[str, str] | Parse the modules's device information response.
Example response from temp-deck: "serial:aa11 model:bb22 version:cc33" | 3.557039 | 2.25217 | 1.579383 |
stack_logger = logging.getLogger('opentrons')
stack_logger.propagate = propagate_logs
contents = protocol_file.read()
if opentrons.config.feature_flags.use_protocol_api_v2():
try:
execute_args = {'protocol_json': json.loads(contents)}
except json.JSONDecodeError:
... | def simulate(protocol_file,
propagate_logs=False,
log_level='warning') -> List[Mapping[str, Any]] | Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other
internal server infrastructure) sources.
To simulate an opentrons protocol from other places, pass in a file like
object as... | 3.626932 | 3.536313 | 1.025625 |
to_ret = []
for command in runlog:
to_ret.append(
'\t' * command['level']
+ command['payload'].get('text', '').format(**command['payload']))
if command['logs']:
to_ret.append('\t' * command['level'] + 'Logs from this command:')
to_ret.extend(
... | def format_runlog(runlog: List[Mapping[str, Any]]) -> str | Format a run log (return value of :py:meth:`simulate``) into a
human-readable string
:param runlog: The output of a call to :py:func:`simulate` | 3.766951 | 3.875408 | 0.972014 |
parser = argparse.ArgumentParser(prog='opentrons_simulate',
description=__doc__)
parser.add_argument(
'protocol', metavar='PROTOCOL_FILE',
type=argparse.FileType('r'),
help='The protocol file to simulate (specify - to read from stdin).')
pars... | def main() | Run the simulation | 2.741326 | 2.692802 | 1.01802 |
return self._commands | def commands(self) -> List[Mapping[str, Mapping[str, Any]]] | The list of commands. See :py:meth:`simulate` | 35.987457 | 40.294735 | 0.893106 |
payload = message['payload']
if message['$'] == 'before':
self._commands.append({'level': self._depth,
'payload': payload,
'logs': []})
self._depth += 1
else:
while not self._queue.... | def _command_callback(self, message) | The callback subscribed to the broker | 4.10461 | 4.280817 | 0.958838 |
if version_a[0] > version_b[0]:
return False
elif version_a[0] < version_b[0]:
return True
else:
if version_a[1] > version_b[1]:
return False
elif version_a[1] < version_b[1]:
return True
else:
return version_a[2] < version_b[2... | def _version_less(version_a, version_b) | Takes two version as (major, minor, patch) tuples and returns a <= b. | 1.437841 | 1.335859 | 1.076342 |
try:
from opentrons import robot
except ModuleNotFoundError:
res = "Unable to find module `opentrons`--not updating firmware"
rc = 1
log.error(res)
else:
# ensure there is a reference to the port
if not robot.is_connected():
robot.connect()
... | async def _update_firmware(filename, loop) | Currently uses the robot singleton from the API server to connect to
Smoothie. Those calls should be separated out from the singleton so it can
be used directly without requiring a full initialization of the API robot. | 5.214454 | 5.065503 | 1.029405 |
log.debug('Update request received')
data = await request.post()
try:
res0, rc0 = await install_py(
sys.executable, data['whl'], request.loop)
reslist = [res0]
filename = os.path.basename(res0['filename'])
version_re_res = re.search(WHEEL_VERSION_RE, filename... | async def update_api(request: web.Request) -> web.Response | This handler accepts a POST request with Content-Type: multipart/form-data
and file fields in the body named "whl", "serverlib", and "fw". The "whl"
and "serverlib" files should be valid Python wheels to be installed ("whl"
is expected generally to be the API server wheel, and "serverlib" is
expected to... | 3.614975 | 3.183291 | 1.13561 |
hw = hw_from_req(request)
if request.url.query.get('refresh') == 'true':
if ff.use_protocol_api_v2():
await hw.cache_instruments()
else:
hw.cache_instrument_models()
response = {}
for mount, data in hw.get_attached_pipettes().items():
response[mount] ... | async def get_attached_pipettes(request) | Query robot for model strings on 'left' and 'right' mounts, and return a
dict with the results keyed by mount. By default, this endpoint provides
cached values, which will not interrupt a running session. WARNING: if the
caller supplies the "refresh=true" query parameter, this method will
interrupt a se... | 3.09022 | 2.702512 | 1.143462 |
hw = hw_from_req(request)
if ff.use_protocol_api_v2():
hw_mods = await hw.discover_modules()
module_data = [
{
'name': mod.name(),
'displayName': mod.display_name(),
'port': mod.port,
'serial': mod.device_info.get('... | async def get_attached_modules(request) | On success (including an empty "modules" list if no modules are detected):
// status: 200
{
"modules": [
{
/** name of module */
"name": "string",
/** model identifier (i.e. part number) */
"model": "string",
/**... | 2.467518 | 2.458656 | 1.003604 |
hw = hw_from_req(request)
requested_serial = request.match_info['serial']
res = None
if ff.use_protocol_api_v2():
hw_mods = await hw.discover_modules()
else:
hw_mods = hw.attached_modules.values()
for module in hw_mods:
is_serial_match = module.device_info.get('ser... | async def get_module_data(request) | Query a module (by its serial number) for its live data | 3.767689 | 3.384988 | 1.113058 |
hw = hw_from_req(request)
requested_serial = request.match_info['serial']
data = await request.json()
command_type = data.get('command_type')
args = data.get('args')
if ff.use_protocol_api_v2():
hw_mods = await hw.discover_modules()
else:
hw_mods = hw.attached_modules.v... | async def execute_module_command(request) | Execute a command on a given module by its serial number | 2.751787 | 2.642024 | 1.041545 |
hw = hw_from_req(request)
return web.json_response(
{str(k).lower(): {'enabled': v}
for k, v in hw.engaged_axes.items()}) | async def get_engaged_axes(request) | Query driver for engaged state by axis. Response keys will be axes XYZABC
and keys will be True for engaged and False for disengaged. Axes must be
manually disengaged, and are automatically re-engaged whenever a "move" or
"home" command is called on that axis.
Response shape example:
{"x": {"en... | 6.246276 | 6.247305 | 0.999835 |
hw = hw_from_req(request)
data = await request.text()
axes = json.loads(data).get('axes')
invalid_axes = [ax for ax in axes if ax.lower() not in 'xyzabc']
if invalid_axes:
message = "Invalid axes: {}".format(', '.join(invalid_axes))
status = 400
else:
await hw.diseng... | async def disengage_axes(request) | Disengage axes (turn off power) primarily in order to reduce heat
consumption.
:param request: Must contain an "axes" field with a list of axes
to disengage (["x", "y", "z", "a", "b", "c"])
:return: message and status code | 2.501402 | 2.498112 | 1.001317 |
hw = hw_from_req(request)
req = await request.text()
data = json.loads(req)
target, point, mount, model, message, error = _validate_move_data(data)
if error:
status = 400
else:
status = 200
if ff.use_protocol_api_v2():
await hw.cache_instruments()
... | async def move(request) | Moves the robot to the specified position as provided by the `control.info`
endpoint response
Post body must include the following keys:
- 'target': either 'mount' or 'pipette'
- 'point': a tuple of 3 floats for x, y, z
- 'mount': must be 'left' or 'right'
If 'target' is 'pipette', body must a... | 4.076495 | 3.363891 | 1.211839 |
carriage = robot._actuators[mount]['carriage']
# Home both carriages, to prevent collisions and to ensure that the other
# mount doesn't block the one being moved (mount moves are primarily for
# changing pipettes, so we don't want the other pipette blocking access)
robot.poses = carriage.home... | def _move_mount(robot, mount, point) | The carriage moves the mount in the Z axis, and the gantry moves in X and Y
Mount movements do not have the same protections calculated in to an
existing `move` command like Pipette does, so the safest thing is to home
the Z axis, then move in X and Y, then move down to the specified Z height | 5.787914 | 5.441772 | 1.063608 |
hw = hw_from_req(request)
req = await request.text()
data = json.loads(req)
target = data.get('target')
if target == 'robot':
if ff.use_protocol_api_v2():
await hw.home()
else:
hw.home()
status = 200
message = "Homing robot."
elif targ... | async def home(request) | This initializes a call to pipette.home() which, as a side effect will:
1. Check the pipette is actually connected (will throw an error if you
try to home a non-connected pipette)
2. Re-engages the motor
:param request: Information obtained from a POST request.
The content type is ap... | 3.518223 | 3.091122 | 1.13817 |
try:
networks = await nmcli.available_ssids()
except RuntimeError as e:
return web.json_response({'message': ' '.join(e.args)}, status=500)
else:
return web.json_response({'list': networks}, status=200) | async def list_networks(request: web.Request) -> web.Response | Get request will return a list of discovered ssids:
GET /wifi/list
200 OK
{ "list": [
{
ssid: string // e.g. "linksys", name to connect to
signal: int // e.g. 100; arbitrary signal strength, more is better
active: boolean // e.g. true; whether there is a connection... | 3.955525 | 3.108341 | 1.272552 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.