repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Opentrons/opentrons
update-server/otupdate/migration/file_actions.py
validate_update
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 """ 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) rootfs = files.get(ROOTFS_NAME) assert rootfs rootfs_calc_hash = hash_file(rootfs, rootfs_hash_callback, file_size=sizes[ROOTFS_NAME]) rootfs_hashfile = files.get(ROOTFS_HASH_NAME) assert rootfs_hashfile rootfs_packaged_hash = open(rootfs_hashfile, 'rb').read().strip() if rootfs_calc_hash != rootfs_packaged_hash: msg = f"Hash mismatch (rootfs): calculated {rootfs_calc_hash} != "\ f"packaged {rootfs_packaged_hash}" LOG.error(msg) raise HashMismatch(msg) def bootfs_hash_callback(progress): progress_callback(progress/3.0 + 0.66) bootfs = files.get(BOOT_NAME) assert bootfs bootfs_calc_hash = hash_file(bootfs, bootfs_hash_callback, file_size=sizes[BOOT_NAME]) bootfs_hashfile = files.get(BOOT_HASH_NAME) assert bootfs_hashfile bootfs_packaged_hash = open(bootfs_hashfile, 'rb').read().strip() if bootfs_calc_hash != bootfs_packaged_hash: msg = f"Hash mismatch (bootfs): calculated {bootfs_calc_hash} != "\ f"packged {bootfs_packaged_hash}" LOG.error(msg) raise HashMismatch(msg) return rootfs, bootfs
python
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 """ 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) rootfs = files.get(ROOTFS_NAME) assert rootfs rootfs_calc_hash = hash_file(rootfs, rootfs_hash_callback, file_size=sizes[ROOTFS_NAME]) rootfs_hashfile = files.get(ROOTFS_HASH_NAME) assert rootfs_hashfile rootfs_packaged_hash = open(rootfs_hashfile, 'rb').read().strip() if rootfs_calc_hash != rootfs_packaged_hash: msg = f"Hash mismatch (rootfs): calculated {rootfs_calc_hash} != "\ f"packaged {rootfs_packaged_hash}" LOG.error(msg) raise HashMismatch(msg) def bootfs_hash_callback(progress): progress_callback(progress/3.0 + 0.66) bootfs = files.get(BOOT_NAME) assert bootfs bootfs_calc_hash = hash_file(bootfs, bootfs_hash_callback, file_size=sizes[BOOT_NAME]) bootfs_hashfile = files.get(BOOT_HASH_NAME) assert bootfs_hashfile bootfs_packaged_hash = open(bootfs_hashfile, 'rb').read().strip() if bootfs_calc_hash != bootfs_packaged_hash: msg = f"Hash mismatch (bootfs): calculated {bootfs_calc_hash} != "\ f"packged {bootfs_packaged_hash}" LOG.error(msg) raise HashMismatch(msg) return rootfs, bootfs
[ "def", "validate_update", "(", "filepath", ":", "str", ",", "progress_callback", ":", "Callable", "[", "[", "float", "]", ",", "None", "]", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "filenames", "=", "[", "ROOTFS_NAME", ",", "ROOTFS_HASH_NAME...
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
[ "Like", "otupdate", ".", "buildroot", ".", "file_actions", ".", "validate_update", "but", "moreso" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/migration/file_actions.py#L25-L73
train
198,000
Opentrons/opentrons
update-server/otupdate/migration/file_actions.py
patch_connection_file_paths
def patch_connection_file_paths(connection: str) -> str: """ Patch any paths in a connection to remove the balena host paths Undoes the changes applied by :py:meth:`opentrons.system.nmcli._rewrite_key_path_to_host_path` :param connection: The contents of a NetworkManager connection file :return: The patches contents, suitable for writing somewher """ new_conn_lines = [] for line in connection.split('\n'): if '=' in line: parts = line.split('=') path_matches = re.search( '/mnt/data/resin-data/[0-9]+/(.*)', parts[1]) if path_matches: new_path = f'/data/{path_matches.group(1)}' new_conn_lines.append( '='.join([parts[0], new_path])) LOG.info( f"migrate_connection_file: {parts[0]}: " f"{parts[1]}->{new_path}") continue new_conn_lines.append(line) return '\n'.join(new_conn_lines)
python
def patch_connection_file_paths(connection: str) -> str: """ Patch any paths in a connection to remove the balena host paths Undoes the changes applied by :py:meth:`opentrons.system.nmcli._rewrite_key_path_to_host_path` :param connection: The contents of a NetworkManager connection file :return: The patches contents, suitable for writing somewher """ new_conn_lines = [] for line in connection.split('\n'): if '=' in line: parts = line.split('=') path_matches = re.search( '/mnt/data/resin-data/[0-9]+/(.*)', parts[1]) if path_matches: new_path = f'/data/{path_matches.group(1)}' new_conn_lines.append( '='.join([parts[0], new_path])) LOG.info( f"migrate_connection_file: {parts[0]}: " f"{parts[1]}->{new_path}") continue new_conn_lines.append(line) return '\n'.join(new_conn_lines)
[ "def", "patch_connection_file_paths", "(", "connection", ":", "str", ")", "->", "str", ":", "new_conn_lines", "=", "[", "]", "for", "line", "in", "connection", ".", "split", "(", "'\\n'", ")", ":", "if", "'='", "in", "line", ":", "parts", "=", "line", ...
Patch any paths in a connection to remove the balena host paths Undoes the changes applied by :py:meth:`opentrons.system.nmcli._rewrite_key_path_to_host_path` :param connection: The contents of a NetworkManager connection file :return: The patches contents, suitable for writing somewher
[ "Patch", "any", "paths", "in", "a", "connection", "to", "remove", "the", "balena", "host", "paths" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/migration/file_actions.py#L97-L122
train
198,001
Opentrons/opentrons
update-server/otupdate/migration/file_actions.py
migrate
def migrate(ignore: Sequence[str], name: str): """ Copy everything in the app data to the root of the new partition :param ignore: Files to ignore in the root. This should be populated with the names (with no directory elements) of the migration update zipfile and everything unzipped from it. :param str: The name of the robot """ try: with mount_data_partition() as datamount: migrate_data(ignore, datamount, DATA_DIR_NAME) migrate_connections(datamount) migrate_hostname(datamount, name) except Exception: LOG.exception("Exception during data migration") raise
python
def migrate(ignore: Sequence[str], name: str): """ Copy everything in the app data to the root of the new partition :param ignore: Files to ignore in the root. This should be populated with the names (with no directory elements) of the migration update zipfile and everything unzipped from it. :param str: The name of the robot """ try: with mount_data_partition() as datamount: migrate_data(ignore, datamount, DATA_DIR_NAME) migrate_connections(datamount) migrate_hostname(datamount, name) except Exception: LOG.exception("Exception during data migration") raise
[ "def", "migrate", "(", "ignore", ":", "Sequence", "[", "str", "]", ",", "name", ":", "str", ")", ":", "try", ":", "with", "mount_data_partition", "(", ")", "as", "datamount", ":", "migrate_data", "(", "ignore", ",", "datamount", ",", "DATA_DIR_NAME", ")"...
Copy everything in the app data to the root of the new partition :param ignore: Files to ignore in the root. This should be populated with the names (with no directory elements) of the migration update zipfile and everything unzipped from it. :param str: The name of the robot
[ "Copy", "everything", "in", "the", "app", "data", "to", "the", "root", "of", "the", "new", "partition" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/migration/file_actions.py#L156-L171
train
198,002
Opentrons/opentrons
update-server/otupdate/migration/file_actions.py
migrate_data
def migrate_data(ignore: Sequence[str], new_data_path: str, old_data_path: str): """ Copy everything in the app data to the root of the main data part :param ignore: A list of files that should be ignored in the root of /data :param new_data_path: Where the new data partition is mounted :param old_data_path: Where the old date files are """ # the new ’data’ path is actually /var and /data is in /var/data dest_data = os.path.join(new_data_path, 'data') LOG.info(f"migrate_data: copying {old_data_path} to {dest_data}") os.makedirs(dest_data, exist_ok=True) with os.scandir(old_data_path) as scanner: for entry in scanner: if entry.name in ignore: LOG.info(f"migrate_data: ignoring {entry.name}") continue src = os.path.join(old_data_path, entry.name) dest = os.path.join(dest_data, entry.name) if os.path.exists(dest): LOG.info(f"migrate_data: removing dest tree {dest}") shutil.rmtree(dest, ignore_errors=True) if entry.is_dir(): LOG.info(f"migrate_data: copying tree {src}->{dest}") shutil.copytree(src, dest, symlinks=True, ignore=migrate_files_to_ignore) else: LOG.info(f"migrate_data: copying file {src}->{dest}") shutil.copy2(src, dest)
python
def migrate_data(ignore: Sequence[str], new_data_path: str, old_data_path: str): """ Copy everything in the app data to the root of the main data part :param ignore: A list of files that should be ignored in the root of /data :param new_data_path: Where the new data partition is mounted :param old_data_path: Where the old date files are """ # the new ’data’ path is actually /var and /data is in /var/data dest_data = os.path.join(new_data_path, 'data') LOG.info(f"migrate_data: copying {old_data_path} to {dest_data}") os.makedirs(dest_data, exist_ok=True) with os.scandir(old_data_path) as scanner: for entry in scanner: if entry.name in ignore: LOG.info(f"migrate_data: ignoring {entry.name}") continue src = os.path.join(old_data_path, entry.name) dest = os.path.join(dest_data, entry.name) if os.path.exists(dest): LOG.info(f"migrate_data: removing dest tree {dest}") shutil.rmtree(dest, ignore_errors=True) if entry.is_dir(): LOG.info(f"migrate_data: copying tree {src}->{dest}") shutil.copytree(src, dest, symlinks=True, ignore=migrate_files_to_ignore) else: LOG.info(f"migrate_data: copying file {src}->{dest}") shutil.copy2(src, dest)
[ "def", "migrate_data", "(", "ignore", ":", "Sequence", "[", "str", "]", ",", "new_data_path", ":", "str", ",", "old_data_path", ":", "str", ")", ":", "# the new ’data’ path is actually /var and /data is in /var/data", "dest_data", "=", "os", ".", "path", ".", "joi...
Copy everything in the app data to the root of the main data part :param ignore: A list of files that should be ignored in the root of /data :param new_data_path: Where the new data partition is mounted :param old_data_path: Where the old date files are
[ "Copy", "everything", "in", "the", "app", "data", "to", "the", "root", "of", "the", "main", "data", "part" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/migration/file_actions.py#L181-L210
train
198,003
Opentrons/opentrons
update-server/otupdate/migration/file_actions.py
migrate_system_connections
def migrate_system_connections(src_sc: str, dest_sc: str) -> bool: """ Migrate the contents of a system-connections dir :param dest_sc: The system-connections to copy to. Will be created if it does not exist :param src_sc: The system-connections to copy from :return: True if anything was moved """ found = False LOG.info(f"migrate_system_connections: checking {dest_sc}") os.makedirs(dest_sc, exist_ok=True) with os.scandir(src_sc) as scanner: for entry in scanner: # ignore readme and sample if entry.name.endswith('.ignore'): continue # ignore the hardwired connection added by api server if entry.name == 'static-eth0': continue # ignore weird remnants of boot partition connections if entry.name.startswith('._'): continue patched = patch_connection_file_paths( open(os.path.join(src_sc, entry.name), 'r').read()) open(os.path.join(dest_sc, entry.name), 'w').write(patched) LOG.info(f"migrate_connections: migrated {entry.name}") found = True return found
python
def migrate_system_connections(src_sc: str, dest_sc: str) -> bool: """ Migrate the contents of a system-connections dir :param dest_sc: The system-connections to copy to. Will be created if it does not exist :param src_sc: The system-connections to copy from :return: True if anything was moved """ found = False LOG.info(f"migrate_system_connections: checking {dest_sc}") os.makedirs(dest_sc, exist_ok=True) with os.scandir(src_sc) as scanner: for entry in scanner: # ignore readme and sample if entry.name.endswith('.ignore'): continue # ignore the hardwired connection added by api server if entry.name == 'static-eth0': continue # ignore weird remnants of boot partition connections if entry.name.startswith('._'): continue patched = patch_connection_file_paths( open(os.path.join(src_sc, entry.name), 'r').read()) open(os.path.join(dest_sc, entry.name), 'w').write(patched) LOG.info(f"migrate_connections: migrated {entry.name}") found = True return found
[ "def", "migrate_system_connections", "(", "src_sc", ":", "str", ",", "dest_sc", ":", "str", ")", "->", "bool", ":", "found", "=", "False", "LOG", ".", "info", "(", "f\"migrate_system_connections: checking {dest_sc}\"", ")", "os", ".", "makedirs", "(", "dest_sc",...
Migrate the contents of a system-connections dir :param dest_sc: The system-connections to copy to. Will be created if it does not exist :param src_sc: The system-connections to copy from :return: True if anything was moved
[ "Migrate", "the", "contents", "of", "a", "system", "-", "connections", "dir" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/migration/file_actions.py#L213-L240
train
198,004
Opentrons/opentrons
update-server/otupdate/migration/file_actions.py
migrate_connections
def migrate_connections(new_data_path: str): """ Migrate wifi connection files to new locations and patch them :param new_data_path: The path to where the new data partition is mounted """ dest_connections = os.path.join( new_data_path, 'lib', 'NetworkManager', 'system-connections') os.makedirs(dest_connections, exist_ok=True) with mount_state_partition() as state_path: src_connections = os.path.join( state_path, 'root-overlay', 'etc', 'NetworkManager', 'system-connections') LOG.info(f"migrate_connections: moving nmcli connections from" f" {src_connections} to {dest_connections}") found = migrate_system_connections(src_connections, dest_connections) if found: return LOG.info( "migrate_connections: No connections found in state, checking boot") with mount_boot_partition() as boot_path: src_connections = os.path.join( boot_path, 'system-connections') LOG.info(f"migrate_connections: moving nmcli connections from" f" {src_connections} to {dest_connections}") found = migrate_system_connections(src_connections, dest_connections) if not found: LOG.info("migrate_connections: No connections found in boot")
python
def migrate_connections(new_data_path: str): """ Migrate wifi connection files to new locations and patch them :param new_data_path: The path to where the new data partition is mounted """ dest_connections = os.path.join( new_data_path, 'lib', 'NetworkManager', 'system-connections') os.makedirs(dest_connections, exist_ok=True) with mount_state_partition() as state_path: src_connections = os.path.join( state_path, 'root-overlay', 'etc', 'NetworkManager', 'system-connections') LOG.info(f"migrate_connections: moving nmcli connections from" f" {src_connections} to {dest_connections}") found = migrate_system_connections(src_connections, dest_connections) if found: return LOG.info( "migrate_connections: No connections found in state, checking boot") with mount_boot_partition() as boot_path: src_connections = os.path.join( boot_path, 'system-connections') LOG.info(f"migrate_connections: moving nmcli connections from" f" {src_connections} to {dest_connections}") found = migrate_system_connections(src_connections, dest_connections) if not found: LOG.info("migrate_connections: No connections found in boot")
[ "def", "migrate_connections", "(", "new_data_path", ":", "str", ")", ":", "dest_connections", "=", "os", ".", "path", ".", "join", "(", "new_data_path", ",", "'lib'", ",", "'NetworkManager'", ",", "'system-connections'", ")", "os", ".", "makedirs", "(", "dest_...
Migrate wifi connection files to new locations and patch them :param new_data_path: The path to where the new data partition is mounted
[ "Migrate", "wifi", "connection", "files", "to", "new", "locations", "and", "patch", "them" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/migration/file_actions.py#L243-L273
train
198,005
Opentrons/opentrons
update-server/otupdate/migration/file_actions.py
migrate_hostname
def migrate_hostname(dest_data: str, name: str): """ Write the machine name to a couple different places :param dest_data: The path to the root of ``/var`` in buildroot :param name: The name The hostname gets written to: - dest_path/hostname (bind mounted to /etc/hostname) (https://www.freedesktop.org/software/systemd/man/hostname.html#) - dest_path/machine-info as the PRETTY_HOSTNAME (bind mounted to /etc/machine-info) (https://www.freedesktop.org/software/systemd/man/machine-info.html#) - dest_path/serial since we assume the resin name is the serial number We also create some basic defaults for the machine-info. """ if name.startswith('opentrons-'): name = name[len('opentrons-'):] LOG.info( f"migrate_hostname: writing name {name} to {dest_data}/hostname," f" {dest_data}/machine-info, {dest_data}/serial") with open(os.path.join(dest_data, 'hostname'), 'w') as hn: hn.write(name + "\n") with open(os.path.join(dest_data, 'machine-info'), 'w') as mi: mi.write(f'PRETTY_HOSTNAME={name}\nDEPLOYMENT=production\n') with open(os.path.join(dest_data, 'serial'), 'w') as ser: ser.write(name)
python
def migrate_hostname(dest_data: str, name: str): """ Write the machine name to a couple different places :param dest_data: The path to the root of ``/var`` in buildroot :param name: The name The hostname gets written to: - dest_path/hostname (bind mounted to /etc/hostname) (https://www.freedesktop.org/software/systemd/man/hostname.html#) - dest_path/machine-info as the PRETTY_HOSTNAME (bind mounted to /etc/machine-info) (https://www.freedesktop.org/software/systemd/man/machine-info.html#) - dest_path/serial since we assume the resin name is the serial number We also create some basic defaults for the machine-info. """ if name.startswith('opentrons-'): name = name[len('opentrons-'):] LOG.info( f"migrate_hostname: writing name {name} to {dest_data}/hostname," f" {dest_data}/machine-info, {dest_data}/serial") with open(os.path.join(dest_data, 'hostname'), 'w') as hn: hn.write(name + "\n") with open(os.path.join(dest_data, 'machine-info'), 'w') as mi: mi.write(f'PRETTY_HOSTNAME={name}\nDEPLOYMENT=production\n') with open(os.path.join(dest_data, 'serial'), 'w') as ser: ser.write(name)
[ "def", "migrate_hostname", "(", "dest_data", ":", "str", ",", "name", ":", "str", ")", ":", "if", "name", ".", "startswith", "(", "'opentrons-'", ")", ":", "name", "=", "name", "[", "len", "(", "'opentrons-'", ")", ":", "]", "LOG", ".", "info", "(", ...
Write the machine name to a couple different places :param dest_data: The path to the root of ``/var`` in buildroot :param name: The name The hostname gets written to: - dest_path/hostname (bind mounted to /etc/hostname) (https://www.freedesktop.org/software/systemd/man/hostname.html#) - dest_path/machine-info as the PRETTY_HOSTNAME (bind mounted to /etc/machine-info) (https://www.freedesktop.org/software/systemd/man/machine-info.html#) - dest_path/serial since we assume the resin name is the serial number We also create some basic defaults for the machine-info.
[ "Write", "the", "machine", "name", "to", "a", "couple", "different", "places" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/migration/file_actions.py#L276-L302
train
198,006
Opentrons/opentrons
api/src/opentrons/config/__init__.py
infer_config_base_dir
def infer_config_base_dir() -> Path: """ Return the directory to store data in. Defaults are ~/.opentrons if not on a pi; OT_API_CONFIG_DIR is respected here. When this module is imported, this function is called automatically and the result stored in :py:attr:`APP_DATA_DIR`. This directory may not exist when the module is imported. Even if it does exist, it may not contain data, or may require data to be moved to it. :return pathlib.Path: The path to the desired root settings dir. """ if 'OT_API_CONFIG_DIR' in os.environ: return Path(os.environ['OT_API_CONFIG_DIR']) elif IS_ROBOT: return Path('/data') else: search = (Path.cwd(), Path.home()/'.opentrons') for path in search: if (path/_CONFIG_FILENAME).exists(): return path else: return search[-1]
python
def infer_config_base_dir() -> Path: """ Return the directory to store data in. Defaults are ~/.opentrons if not on a pi; OT_API_CONFIG_DIR is respected here. When this module is imported, this function is called automatically and the result stored in :py:attr:`APP_DATA_DIR`. This directory may not exist when the module is imported. Even if it does exist, it may not contain data, or may require data to be moved to it. :return pathlib.Path: The path to the desired root settings dir. """ if 'OT_API_CONFIG_DIR' in os.environ: return Path(os.environ['OT_API_CONFIG_DIR']) elif IS_ROBOT: return Path('/data') else: search = (Path.cwd(), Path.home()/'.opentrons') for path in search: if (path/_CONFIG_FILENAME).exists(): return path else: return search[-1]
[ "def", "infer_config_base_dir", "(", ")", "->", "Path", ":", "if", "'OT_API_CONFIG_DIR'", "in", "os", ".", "environ", ":", "return", "Path", "(", "os", ".", "environ", "[", "'OT_API_CONFIG_DIR'", "]", ")", "elif", "IS_ROBOT", ":", "return", "Path", "(", "'...
Return the directory to store data in. Defaults are ~/.opentrons if not on a pi; OT_API_CONFIG_DIR is respected here. When this module is imported, this function is called automatically and the result stored in :py:attr:`APP_DATA_DIR`. This directory may not exist when the module is imported. Even if it does exist, it may not contain data, or may require data to be moved to it. :return pathlib.Path: The path to the desired root settings dir.
[ "Return", "the", "directory", "to", "store", "data", "in", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L147-L173
train
198,007
Opentrons/opentrons
api/src/opentrons/config/__init__.py
load_and_migrate
def load_and_migrate() -> Dict[str, Path]: """ Ensure the settings directory tree is properly configured. This function does most of its work on the actual robot. It will move all settings files from wherever they happen to be to the proper place. On non-robots, this mostly just loads. In addition, it writes a default config and makes sure all directories required exist (though the files in them may not). """ if IS_ROBOT: _migrate_robot() base = infer_config_base_dir() base.mkdir(parents=True, exist_ok=True) index = _load_with_overrides(base) return _ensure_paths_and_types(index)
python
def load_and_migrate() -> Dict[str, Path]: """ Ensure the settings directory tree is properly configured. This function does most of its work on the actual robot. It will move all settings files from wherever they happen to be to the proper place. On non-robots, this mostly just loads. In addition, it writes a default config and makes sure all directories required exist (though the files in them may not). """ if IS_ROBOT: _migrate_robot() base = infer_config_base_dir() base.mkdir(parents=True, exist_ok=True) index = _load_with_overrides(base) return _ensure_paths_and_types(index)
[ "def", "load_and_migrate", "(", ")", "->", "Dict", "[", "str", ",", "Path", "]", ":", "if", "IS_ROBOT", ":", "_migrate_robot", "(", ")", "base", "=", "infer_config_base_dir", "(", ")", "base", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", ...
Ensure the settings directory tree is properly configured. This function does most of its work on the actual robot. It will move all settings files from wherever they happen to be to the proper place. On non-robots, this mostly just loads. In addition, it writes a default config and makes sure all directories required exist (though the files in them may not).
[ "Ensure", "the", "settings", "directory", "tree", "is", "properly", "configured", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L176-L190
train
198,008
Opentrons/opentrons
api/src/opentrons/config/__init__.py
_load_with_overrides
def _load_with_overrides(base) -> Dict[str, str]: """ Load an config or write its defaults """ should_write = False overrides = _get_environ_overrides() try: index = json.load((base/_CONFIG_FILENAME).open()) except (OSError, json.JSONDecodeError) as e: sys.stderr.write("Error loading config from {}: {}\nRewriting...\n" .format(str(base), e)) should_write = True index = generate_config_index(overrides) for key in CONFIG_ELEMENTS: if key.name not in index: sys.stderr.write( f"New config index key {key.name}={key.default}" "\nRewriting...\n") if key.kind in (ConfigElementType.DIR, ConfigElementType.FILE): index[key.name] = base/key.default else: index[key.name] = key.default should_write = True if should_write: try: write_config(index, path=base) except Exception as e: sys.stderr.write( "Error writing config to {}: {}\nProceeding memory-only\n" .format(str(base), e)) index.update(overrides) return index
python
def _load_with_overrides(base) -> Dict[str, str]: """ Load an config or write its defaults """ should_write = False overrides = _get_environ_overrides() try: index = json.load((base/_CONFIG_FILENAME).open()) except (OSError, json.JSONDecodeError) as e: sys.stderr.write("Error loading config from {}: {}\nRewriting...\n" .format(str(base), e)) should_write = True index = generate_config_index(overrides) for key in CONFIG_ELEMENTS: if key.name not in index: sys.stderr.write( f"New config index key {key.name}={key.default}" "\nRewriting...\n") if key.kind in (ConfigElementType.DIR, ConfigElementType.FILE): index[key.name] = base/key.default else: index[key.name] = key.default should_write = True if should_write: try: write_config(index, path=base) except Exception as e: sys.stderr.write( "Error writing config to {}: {}\nProceeding memory-only\n" .format(str(base), e)) index.update(overrides) return index
[ "def", "_load_with_overrides", "(", "base", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "should_write", "=", "False", "overrides", "=", "_get_environ_overrides", "(", ")", "try", ":", "index", "=", "json", ".", "load", "(", "(", "base", "/", "...
Load an config or write its defaults
[ "Load", "an", "config", "or", "write", "its", "defaults" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L193-L224
train
198,009
Opentrons/opentrons
api/src/opentrons/config/__init__.py
_ensure_paths_and_types
def _ensure_paths_and_types(index: Dict[str, str]) -> Dict[str, Path]: """ Take the direct results of loading the config and make sure the filesystem reflects them. """ configs_by_name = {ce.name: ce for ce in CONFIG_ELEMENTS} correct_types: Dict[str, Path] = {} for key, item in index.items(): if key not in configs_by_name: # old config, ignore continue if configs_by_name[key].kind == ConfigElementType.FILE: it = Path(item) it.parent.mkdir(parents=True, exist_ok=True) correct_types[key] = it elif configs_by_name[key].kind == ConfigElementType.DIR: it = Path(item) it.mkdir(parents=True, exist_ok=True) correct_types[key] = it else: raise RuntimeError( f"unhandled kind in ConfigElements: {key}: " f"{configs_by_name[key].kind}") return correct_types
python
def _ensure_paths_and_types(index: Dict[str, str]) -> Dict[str, Path]: """ Take the direct results of loading the config and make sure the filesystem reflects them. """ configs_by_name = {ce.name: ce for ce in CONFIG_ELEMENTS} correct_types: Dict[str, Path] = {} for key, item in index.items(): if key not in configs_by_name: # old config, ignore continue if configs_by_name[key].kind == ConfigElementType.FILE: it = Path(item) it.parent.mkdir(parents=True, exist_ok=True) correct_types[key] = it elif configs_by_name[key].kind == ConfigElementType.DIR: it = Path(item) it.mkdir(parents=True, exist_ok=True) correct_types[key] = it else: raise RuntimeError( f"unhandled kind in ConfigElements: {key}: " f"{configs_by_name[key].kind}") return correct_types
[ "def", "_ensure_paths_and_types", "(", "index", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Dict", "[", "str", ",", "Path", "]", ":", "configs_by_name", "=", "{", "ce", ".", "name", ":", "ce", "for", "ce", "in", "CONFIG_ELEMENTS", "}", "cor...
Take the direct results of loading the config and make sure the filesystem reflects them.
[ "Take", "the", "direct", "results", "of", "loading", "the", "config", "and", "make", "sure", "the", "filesystem", "reflects", "them", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L227-L248
train
198,010
Opentrons/opentrons
api/src/opentrons/config/__init__.py
_legacy_index
def _legacy_index() -> Union[None, Dict[str, str]]: """ Try and load an index file from the various places it might exist. If the legacy file cannot be found or cannot be parsed, return None. This method should only be called on a robot. """ for index in _LEGACY_INDICES: if index.exists(): try: return json.load(open(index)) except (OSError, json.JSONDecodeError): return None return None
python
def _legacy_index() -> Union[None, Dict[str, str]]: """ Try and load an index file from the various places it might exist. If the legacy file cannot be found or cannot be parsed, return None. This method should only be called on a robot. """ for index in _LEGACY_INDICES: if index.exists(): try: return json.load(open(index)) except (OSError, json.JSONDecodeError): return None return None
[ "def", "_legacy_index", "(", ")", "->", "Union", "[", "None", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "for", "index", "in", "_LEGACY_INDICES", ":", "if", "index", ".", "exists", "(", ")", ":", "try", ":", "return", "json", ".", "load", ...
Try and load an index file from the various places it might exist. If the legacy file cannot be found or cannot be parsed, return None. This method should only be called on a robot.
[ "Try", "and", "load", "an", "index", "file", "from", "the", "various", "places", "it", "might", "exist", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L262-L275
train
198,011
Opentrons/opentrons
api/src/opentrons/config/__init__.py
_find_most_recent_backup
def _find_most_recent_backup(normal_path: Optional[str]) -> Optional[str]: """ Find the most recent old settings to migrate. The input is the path to an unqualified settings file - e.g. /mnt/usbdrive/config/robotSettings.json This will return - None if the input is None (to support chaining from dict.get()) - The input if it exists, or - The file named normal_path-TIMESTAMP.json with the highest timestamp if one can be found, or - None """ if normal_path is None: return None if os.path.exists(normal_path): return normal_path dirname, basename = os.path.split(normal_path) root, ext = os.path.splitext(basename) backups = [fi for fi in os.listdir(dirname) if fi.startswith(root) and fi.endswith(ext)] ts_re = re.compile(r'.*-([0-9]+)' + ext + '$') def ts_compare(filename): match = ts_re.match(filename) if not match: return -1 else: return int(match.group(1)) backups_sorted = sorted(backups, key=ts_compare) if not backups_sorted: return None return os.path.join(dirname, backups_sorted[-1])
python
def _find_most_recent_backup(normal_path: Optional[str]) -> Optional[str]: """ Find the most recent old settings to migrate. The input is the path to an unqualified settings file - e.g. /mnt/usbdrive/config/robotSettings.json This will return - None if the input is None (to support chaining from dict.get()) - The input if it exists, or - The file named normal_path-TIMESTAMP.json with the highest timestamp if one can be found, or - None """ if normal_path is None: return None if os.path.exists(normal_path): return normal_path dirname, basename = os.path.split(normal_path) root, ext = os.path.splitext(basename) backups = [fi for fi in os.listdir(dirname) if fi.startswith(root) and fi.endswith(ext)] ts_re = re.compile(r'.*-([0-9]+)' + ext + '$') def ts_compare(filename): match = ts_re.match(filename) if not match: return -1 else: return int(match.group(1)) backups_sorted = sorted(backups, key=ts_compare) if not backups_sorted: return None return os.path.join(dirname, backups_sorted[-1])
[ "def", "_find_most_recent_backup", "(", "normal_path", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "str", "]", ":", "if", "normal_path", "is", "None", ":", "return", "None", "if", "os", ".", "path", ".", "exists", "(", "normal_path", ")...
Find the most recent old settings to migrate. The input is the path to an unqualified settings file - e.g. /mnt/usbdrive/config/robotSettings.json This will return - None if the input is None (to support chaining from dict.get()) - The input if it exists, or - The file named normal_path-TIMESTAMP.json with the highest timestamp if one can be found, or - None
[ "Find", "the", "most", "recent", "old", "settings", "to", "migrate", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L288-L323
train
198,012
Opentrons/opentrons
api/src/opentrons/config/__init__.py
generate_config_index
def generate_config_index(defaults: Dict[str, str], base_dir=None) -> Dict[str, Path]: """ Determines where existing info can be found in the system, and creates a corresponding data dict that can be written to index.json in the baseDataDir. The information in the files defined by the config index is information required by the API itself and nothing else - labware definitions, feature flags, robot configurations. It does not include configuration files that relate to the rest of the system, such as network description file definitions. :param defaults: A dict of defaults to write, useful for specifying part (but not all) of the index succinctly. This is used both when loading a configuration file from disk and when generating a new one. :param base_dir: If specified, a base path used if this function has to generate defaults. If not specified, falls back to :py:attr:`CONFIG_BASE_DIR` :returns: The config object """ base = Path(base_dir) if base_dir else infer_config_base_dir() def parse_or_default( ce: ConfigElement, val: Optional[str]) -> Path: if not val: return base / Path(ce.default) else: return Path(val) return { ce.name: parse_or_default(ce, defaults.get(ce.name)) for ce in CONFIG_ELEMENTS }
python
def generate_config_index(defaults: Dict[str, str], base_dir=None) -> Dict[str, Path]: """ Determines where existing info can be found in the system, and creates a corresponding data dict that can be written to index.json in the baseDataDir. The information in the files defined by the config index is information required by the API itself and nothing else - labware definitions, feature flags, robot configurations. It does not include configuration files that relate to the rest of the system, such as network description file definitions. :param defaults: A dict of defaults to write, useful for specifying part (but not all) of the index succinctly. This is used both when loading a configuration file from disk and when generating a new one. :param base_dir: If specified, a base path used if this function has to generate defaults. If not specified, falls back to :py:attr:`CONFIG_BASE_DIR` :returns: The config object """ base = Path(base_dir) if base_dir else infer_config_base_dir() def parse_or_default( ce: ConfigElement, val: Optional[str]) -> Path: if not val: return base / Path(ce.default) else: return Path(val) return { ce.name: parse_or_default(ce, defaults.get(ce.name)) for ce in CONFIG_ELEMENTS }
[ "def", "generate_config_index", "(", "defaults", ":", "Dict", "[", "str", ",", "str", "]", ",", "base_dir", "=", "None", ")", "->", "Dict", "[", "str", ",", "Path", "]", ":", "base", "=", "Path", "(", "base_dir", ")", "if", "base_dir", "else", "infer...
Determines where existing info can be found in the system, and creates a corresponding data dict that can be written to index.json in the baseDataDir. The information in the files defined by the config index is information required by the API itself and nothing else - labware definitions, feature flags, robot configurations. It does not include configuration files that relate to the rest of the system, such as network description file definitions. :param defaults: A dict of defaults to write, useful for specifying part (but not all) of the index succinctly. This is used both when loading a configuration file from disk and when generating a new one. :param base_dir: If specified, a base path used if this function has to generate defaults. If not specified, falls back to :py:attr:`CONFIG_BASE_DIR` :returns: The config object
[ "Determines", "where", "existing", "info", "can", "be", "found", "in", "the", "system", "and", "creates", "a", "corresponding", "data", "dict", "that", "can", "be", "written", "to", "index", ".", "json", "in", "the", "baseDataDir", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L363-L398
train
198,013
Opentrons/opentrons
api/src/opentrons/config/__init__.py
write_config
def write_config(config_data: Dict[str, Path], path: Path = None): """ Save the config file. :param config_data: The index to save :param base_dir: The place to save the file. If ``None``, :py:meth:`infer_config_base_dir()` will be used Only keys that are in the config elements will be saved. """ path = Path(path) if path else infer_config_base_dir() valid_names = [ce.name for ce in CONFIG_ELEMENTS] try: os.makedirs(path, exist_ok=True) with (path/_CONFIG_FILENAME).open('w') as base_f: json.dump({k: str(v) for k, v in config_data.items() if k in valid_names}, base_f, indent=2) except OSError as e: sys.stderr.write("Config index write to {} failed: {}\n" .format(path/_CONFIG_FILENAME, e))
python
def write_config(config_data: Dict[str, Path], path: Path = None): """ Save the config file. :param config_data: The index to save :param base_dir: The place to save the file. If ``None``, :py:meth:`infer_config_base_dir()` will be used Only keys that are in the config elements will be saved. """ path = Path(path) if path else infer_config_base_dir() valid_names = [ce.name for ce in CONFIG_ELEMENTS] try: os.makedirs(path, exist_ok=True) with (path/_CONFIG_FILENAME).open('w') as base_f: json.dump({k: str(v) for k, v in config_data.items() if k in valid_names}, base_f, indent=2) except OSError as e: sys.stderr.write("Config index write to {} failed: {}\n" .format(path/_CONFIG_FILENAME, e))
[ "def", "write_config", "(", "config_data", ":", "Dict", "[", "str", ",", "Path", "]", ",", "path", ":", "Path", "=", "None", ")", ":", "path", "=", "Path", "(", "path", ")", "if", "path", "else", "infer_config_base_dir", "(", ")", "valid_names", "=", ...
Save the config file. :param config_data: The index to save :param base_dir: The place to save the file. If ``None``, :py:meth:`infer_config_base_dir()` will be used Only keys that are in the config elements will be saved.
[ "Save", "the", "config", "file", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L401-L421
train
198,014
Opentrons/opentrons
api/src/opentrons/deck_calibration/dc_main.py
main
def main(): """ A CLI application for performing factory calibration of an Opentrons robot Instructions: - Robot must be set up with two 300ul or 50ul single-channel pipettes installed on the right-hand and left-hand mount. - Put a GEB 300ul tip onto the pipette. - Use the arrow keys to jog the robot over slot 5 in an open space that is not an engraving or a hole. - Use the 'q' and 'a' keys to jog the pipette up and down respectively until the tip is just touching the deck surface, then press 'z'. This will save the 'Z' height. - Press '1' to automatically go to the expected location of the first calibration point. Jog the robot until the tip is actually at the point, then press 'enter'. - Repeat with '2' and '3'. - After calibrating all three points, press the space bar to save the configuration. - Optionally, press 4,5,6 or 7 to validate the new configuration. - Press 'p' to perform tip probe. Press the space bar to save again. - Press 'm' to perform mount calibration. Press enter and then space bar to save again. - Press 'esc' to exit the program. """ prompt = input( ">>> Warning! Running this tool backup and clear any previous " "calibration data. Proceed (y/[n])? ") if prompt not in ['y', 'Y', 'yes']: print('Exiting--prior configuration data not changed') sys.exit() # Notes: # - 200ul tip is 51.7mm long when attached to a pipette # - For xyz coordinates, (0, 0, 0) is the lower-left corner of the robot cli = CLITool( point_set=get_calibration_points(), tip_length=51.7) hardware = cli.hardware backup_configuration_and_reload(hardware) if not feature_flags.use_protocol_api_v2(): hardware.connect() hardware.turn_on_rail_lights() atexit.register(hardware.turn_off_rail_lights) else: hardware.set_lights(rails=True) cli.home() # lights help the script user to see the points on the deck cli.ui_loop.run() if feature_flags.use_protocol_api_v2(): hardware.set_lights(rails=False) print('Robot config: \n', cli._config)
python
def main(): """ A CLI application for performing factory calibration of an Opentrons robot Instructions: - Robot must be set up with two 300ul or 50ul single-channel pipettes installed on the right-hand and left-hand mount. - Put a GEB 300ul tip onto the pipette. - Use the arrow keys to jog the robot over slot 5 in an open space that is not an engraving or a hole. - Use the 'q' and 'a' keys to jog the pipette up and down respectively until the tip is just touching the deck surface, then press 'z'. This will save the 'Z' height. - Press '1' to automatically go to the expected location of the first calibration point. Jog the robot until the tip is actually at the point, then press 'enter'. - Repeat with '2' and '3'. - After calibrating all three points, press the space bar to save the configuration. - Optionally, press 4,5,6 or 7 to validate the new configuration. - Press 'p' to perform tip probe. Press the space bar to save again. - Press 'm' to perform mount calibration. Press enter and then space bar to save again. - Press 'esc' to exit the program. """ prompt = input( ">>> Warning! Running this tool backup and clear any previous " "calibration data. Proceed (y/[n])? ") if prompt not in ['y', 'Y', 'yes']: print('Exiting--prior configuration data not changed') sys.exit() # Notes: # - 200ul tip is 51.7mm long when attached to a pipette # - For xyz coordinates, (0, 0, 0) is the lower-left corner of the robot cli = CLITool( point_set=get_calibration_points(), tip_length=51.7) hardware = cli.hardware backup_configuration_and_reload(hardware) if not feature_flags.use_protocol_api_v2(): hardware.connect() hardware.turn_on_rail_lights() atexit.register(hardware.turn_off_rail_lights) else: hardware.set_lights(rails=True) cli.home() # lights help the script user to see the points on the deck cli.ui_loop.run() if feature_flags.use_protocol_api_v2(): hardware.set_lights(rails=False) print('Robot config: \n', cli._config)
[ "def", "main", "(", ")", ":", "prompt", "=", "input", "(", "\">>> Warning! Running this tool backup and clear any previous \"", "\"calibration data. Proceed (y/[n])? \"", ")", "if", "prompt", "not", "in", "[", "'y'", ",", "'Y'", ",", "'yes'", "]", ":", "print", "(",...
A CLI application for performing factory calibration of an Opentrons robot Instructions: - Robot must be set up with two 300ul or 50ul single-channel pipettes installed on the right-hand and left-hand mount. - Put a GEB 300ul tip onto the pipette. - Use the arrow keys to jog the robot over slot 5 in an open space that is not an engraving or a hole. - Use the 'q' and 'a' keys to jog the pipette up and down respectively until the tip is just touching the deck surface, then press 'z'. This will save the 'Z' height. - Press '1' to automatically go to the expected location of the first calibration point. Jog the robot until the tip is actually at the point, then press 'enter'. - Repeat with '2' and '3'. - After calibrating all three points, press the space bar to save the configuration. - Optionally, press 4,5,6 or 7 to validate the new configuration. - Press 'p' to perform tip probe. Press the space bar to save again. - Press 'm' to perform mount calibration. Press enter and then space bar to save again. - Press 'esc' to exit the program.
[ "A", "CLI", "application", "for", "performing", "factory", "calibration", "of", "an", "Opentrons", "robot" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/dc_main.py#L492-L542
train
198,015
Opentrons/opentrons
api/src/opentrons/deck_calibration/dc_main.py
CLITool.increase_step
def increase_step(self) -> str: """ Increase the jog resolution without overrunning the list of values """ if self._steps_index < len(self._steps) - 1: self._steps_index = self._steps_index + 1 return 'step: {}'.format(self.current_step())
python
def increase_step(self) -> str: """ Increase the jog resolution without overrunning the list of values """ if self._steps_index < len(self._steps) - 1: self._steps_index = self._steps_index + 1 return 'step: {}'.format(self.current_step())
[ "def", "increase_step", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_steps_index", "<", "len", "(", "self", ".", "_steps", ")", "-", "1", ":", "self", ".", "_steps_index", "=", "self", ".", "_steps_index", "+", "1", "return", "'step: {}'", ...
Increase the jog resolution without overrunning the list of values
[ "Increase", "the", "jog", "resolution", "without", "overrunning", "the", "list", "of", "values" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/dc_main.py#L209-L215
train
198,016
Opentrons/opentrons
api/src/opentrons/deck_calibration/dc_main.py
CLITool.decrease_step
def decrease_step(self) -> str: """ Decrease the jog resolution without overrunning the list of values """ if self._steps_index > 0: self._steps_index = self._steps_index - 1 return 'step: {}'.format(self.current_step())
python
def decrease_step(self) -> str: """ Decrease the jog resolution without overrunning the list of values """ if self._steps_index > 0: self._steps_index = self._steps_index - 1 return 'step: {}'.format(self.current_step())
[ "def", "decrease_step", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_steps_index", ">", "0", ":", "self", ".", "_steps_index", "=", "self", ".", "_steps_index", "-", "1", "return", "'step: {}'", ".", "format", "(", "self", ".", "current_step"...
Decrease the jog resolution without overrunning the list of values
[ "Decrease", "the", "jog", "resolution", "without", "overrunning", "the", "list", "of", "values" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/dc_main.py#L217-L223
train
198,017
Opentrons/opentrons
api/src/opentrons/deck_calibration/dc_main.py
CLITool._jog
def _jog(self, axis, direction, step): """ Move the pipette on `axis` in `direction` by `step` and update the position tracker """ jog(axis, direction, step, self.hardware, self._current_mount) self.current_position = self._position() return 'Jog: {}'.format([axis, str(direction), str(step)])
python
def _jog(self, axis, direction, step): """ Move the pipette on `axis` in `direction` by `step` and update the position tracker """ jog(axis, direction, step, self.hardware, self._current_mount) self.current_position = self._position() return 'Jog: {}'.format([axis, str(direction), str(step)])
[ "def", "_jog", "(", "self", ",", "axis", ",", "direction", ",", "step", ")", ":", "jog", "(", "axis", ",", "direction", ",", "step", ",", "self", ".", "hardware", ",", "self", ".", "_current_mount", ")", "self", ".", "current_position", "=", "self", ...
Move the pipette on `axis` in `direction` by `step` and update the position tracker
[ "Move", "the", "pipette", "on", "axis", "in", "direction", "by", "step", "and", "update", "the", "position", "tracker" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/dc_main.py#L249-L257
train
198,018
Opentrons/opentrons
api/src/opentrons/deck_calibration/dc_main.py
CLITool.home
def home(self) -> str: """ Return the robot to the home position and update the position tracker """ self.hardware.home() self.current_position = self._position() return 'Homed'
python
def home(self) -> str: """ Return the robot to the home position and update the position tracker """ self.hardware.home() self.current_position = self._position() return 'Homed'
[ "def", "home", "(", "self", ")", "->", "str", ":", "self", ".", "hardware", ".", "home", "(", ")", "self", ".", "current_position", "=", "self", ".", "_position", "(", ")", "return", "'Homed'" ]
Return the robot to the home position and update the position tracker
[ "Return", "the", "robot", "to", "the", "home", "position", "and", "update", "the", "position", "tracker" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/dc_main.py#L259-L265
train
198,019
Opentrons/opentrons
api/src/opentrons/deck_calibration/dc_main.py
CLITool.save_point
def save_point(self) -> str: """ Indexes the measured data with the current point as a key and saves the current position once the 'Enter' key is pressed to the 'actual points' vector. """ if self._current_mount is left: msg = self.save_mount_offset() self._current_mount = right elif self._current_mount is types.Mount.LEFT: msg = self.save_mount_offset() self._current_mount = types.Mount.RIGHT else: pos = self._position()[:-1] self.actual_points[self._current_point] = pos log.debug("Saving {} for point {}".format( pos, self._current_point)) msg = 'saved #{}: {}'.format( self._current_point, self.actual_points[self._current_point]) return msg
python
def save_point(self) -> str: """ Indexes the measured data with the current point as a key and saves the current position once the 'Enter' key is pressed to the 'actual points' vector. """ if self._current_mount is left: msg = self.save_mount_offset() self._current_mount = right elif self._current_mount is types.Mount.LEFT: msg = self.save_mount_offset() self._current_mount = types.Mount.RIGHT else: pos = self._position()[:-1] self.actual_points[self._current_point] = pos log.debug("Saving {} for point {}".format( pos, self._current_point)) msg = 'saved #{}: {}'.format( self._current_point, self.actual_points[self._current_point]) return msg
[ "def", "save_point", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_current_mount", "is", "left", ":", "msg", "=", "self", ".", "save_mount_offset", "(", ")", "self", ".", "_current_mount", "=", "right", "elif", "self", ".", "_current_mount", "...
Indexes the measured data with the current point as a key and saves the current position once the 'Enter' key is pressed to the 'actual points' vector.
[ "Indexes", "the", "measured", "data", "with", "the", "current", "point", "as", "a", "key", "and", "saves", "the", "current", "position", "once", "the", "Enter", "key", "is", "pressed", "to", "the", "actual", "points", "vector", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/dc_main.py#L267-L286
train
198,020
Opentrons/opentrons
api/src/opentrons/deck_calibration/dc_main.py
CLITool.save_transform
def save_transform(self) -> str: """ Actual is measured data Expected is based on mechanical drawings of the robot This method computes the transformation matrix from actual -> expected. Saves this transform to disc. """ expected = [self._expected_points[p][:2] for p in [1, 2, 3]] log.debug("save_transform expected: {}".format(expected)) actual = [self.actual_points[p][:2] for p in [1, 2, 3]] log.debug("save_transform actual: {}".format(actual)) # Generate a 2 dimensional transform matrix from the two matricies flat_matrix = solve(expected, actual) log.debug("save_transform flat_matrix: {}".format(flat_matrix)) current_z = self.calibration_matrix[2][3] # Add the z component to form the 3 dimensional transform self.calibration_matrix = add_z(flat_matrix, current_z) gantry_calibration = list( map(lambda i: list(i), self.calibration_matrix)) log.debug("save_transform calibration_matrix: {}".format( gantry_calibration)) self.hardware.update_config(gantry_calibration=gantry_calibration) res = str(self.hardware.config) return '{}\n{}'.format(res, save_config(self.hardware.config))
python
def save_transform(self) -> str: """ Actual is measured data Expected is based on mechanical drawings of the robot This method computes the transformation matrix from actual -> expected. Saves this transform to disc. """ expected = [self._expected_points[p][:2] for p in [1, 2, 3]] log.debug("save_transform expected: {}".format(expected)) actual = [self.actual_points[p][:2] for p in [1, 2, 3]] log.debug("save_transform actual: {}".format(actual)) # Generate a 2 dimensional transform matrix from the two matricies flat_matrix = solve(expected, actual) log.debug("save_transform flat_matrix: {}".format(flat_matrix)) current_z = self.calibration_matrix[2][3] # Add the z component to form the 3 dimensional transform self.calibration_matrix = add_z(flat_matrix, current_z) gantry_calibration = list( map(lambda i: list(i), self.calibration_matrix)) log.debug("save_transform calibration_matrix: {}".format( gantry_calibration)) self.hardware.update_config(gantry_calibration=gantry_calibration) res = str(self.hardware.config) return '{}\n{}'.format(res, save_config(self.hardware.config))
[ "def", "save_transform", "(", "self", ")", "->", "str", ":", "expected", "=", "[", "self", ".", "_expected_points", "[", "p", "]", "[", ":", "2", "]", "for", "p", "in", "[", "1", ",", "2", ",", "3", "]", "]", "log", ".", "debug", "(", "\"save_t...
Actual is measured data Expected is based on mechanical drawings of the robot This method computes the transformation matrix from actual -> expected. Saves this transform to disc.
[ "Actual", "is", "measured", "data", "Expected", "is", "based", "on", "mechanical", "drawings", "of", "the", "robot" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/dc_main.py#L307-L334
train
198,021
Opentrons/opentrons
api/src/opentrons/hardware_control/simulator.py
find_config
def find_config(prefix: str) -> str: """ Find the most recent config matching `prefix` """ matches = [conf for conf in config_models if conf.startswith(prefix)] if not matches: raise KeyError('No match found for prefix {}'.format(prefix)) if prefix in matches: return prefix else: return sorted(matches)[0]
python
def find_config(prefix: str) -> str: """ Find the most recent config matching `prefix` """ matches = [conf for conf in config_models if conf.startswith(prefix)] if not matches: raise KeyError('No match found for prefix {}'.format(prefix)) if prefix in matches: return prefix else: return sorted(matches)[0]
[ "def", "find_config", "(", "prefix", ":", "str", ")", "->", "str", ":", "matches", "=", "[", "conf", "for", "conf", "in", "config_models", "if", "conf", ".", "startswith", "(", "prefix", ")", "]", "if", "not", "matches", ":", "raise", "KeyError", "(", ...
Find the most recent config matching `prefix`
[ "Find", "the", "most", "recent", "config", "matching", "prefix" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/simulator.py#L15-L23
train
198,022
Opentrons/opentrons
api/src/opentrons/hardware_control/simulator.py
Simulator.get_attached_instruments
def get_attached_instruments( self, expected: Dict[types.Mount, str])\ -> Dict[types.Mount, Dict[str, Optional[str]]]: """ Update the internal cache of attached instruments. This method allows after-init-time specification of attached simulated instruments. The method will return - the instruments specified at init-time, or if those do not exists, - the instruments specified in expected, or if that is not passed, - nothing :param expected: A mapping of mount to instrument model prefixes. When loading instruments from a prefix, we return the lexically-first model that matches the prefix. If the models specified in expected do not match the models specified in the `attached_instruments` argument of :py:meth:`__init__`, :py:attr:`RuntimeError` is raised. :raises RuntimeError: If an instrument is expected but not found. :returns: A dict of mount to either instrument model names or `None`. """ to_return: Dict[types.Mount, Dict[str, Optional[str]]] = {} for mount in types.Mount: expected_instr = expected.get(mount, None) init_instr = self._attached_instruments.get(mount, {}) found_model = init_instr.get('model', '') if expected_instr and found_model\ and not found_model.startswith(expected_instr): if self._strict_attached: raise RuntimeError( 'mount {}: expected instrument {} but got {}' .format(mount.name, expected_instr, init_instr)) else: to_return[mount] = { 'model': find_config(expected_instr), 'id': None} elif found_model and expected_instr: # Instrument detected matches instrument expected (note: # "instrument detected" means passed as an argument to the # constructor of this class) to_return[mount] = init_instr elif found_model: # Instrument detected and no expected instrument specified to_return[mount] = init_instr elif expected_instr: # Expected instrument specified and no instrument detected to_return[mount] = { 'model': find_config(expected_instr), 'id': None} else: # No instrument detected or expected to_return[mount] = { 'model': None, 'id': None} return to_return
python
def get_attached_instruments( self, expected: Dict[types.Mount, str])\ -> Dict[types.Mount, Dict[str, Optional[str]]]: """ Update the internal cache of attached instruments. This method allows after-init-time specification of attached simulated instruments. The method will return - the instruments specified at init-time, or if those do not exists, - the instruments specified in expected, or if that is not passed, - nothing :param expected: A mapping of mount to instrument model prefixes. When loading instruments from a prefix, we return the lexically-first model that matches the prefix. If the models specified in expected do not match the models specified in the `attached_instruments` argument of :py:meth:`__init__`, :py:attr:`RuntimeError` is raised. :raises RuntimeError: If an instrument is expected but not found. :returns: A dict of mount to either instrument model names or `None`. """ to_return: Dict[types.Mount, Dict[str, Optional[str]]] = {} for mount in types.Mount: expected_instr = expected.get(mount, None) init_instr = self._attached_instruments.get(mount, {}) found_model = init_instr.get('model', '') if expected_instr and found_model\ and not found_model.startswith(expected_instr): if self._strict_attached: raise RuntimeError( 'mount {}: expected instrument {} but got {}' .format(mount.name, expected_instr, init_instr)) else: to_return[mount] = { 'model': find_config(expected_instr), 'id': None} elif found_model and expected_instr: # Instrument detected matches instrument expected (note: # "instrument detected" means passed as an argument to the # constructor of this class) to_return[mount] = init_instr elif found_model: # Instrument detected and no expected instrument specified to_return[mount] = init_instr elif expected_instr: # Expected instrument specified and no instrument detected to_return[mount] = { 'model': find_config(expected_instr), 'id': None} else: # No instrument detected or expected to_return[mount] = { 'model': None, 'id': None} return to_return
[ "def", "get_attached_instruments", "(", "self", ",", "expected", ":", "Dict", "[", "types", ".", "Mount", ",", "str", "]", ")", "->", "Dict", "[", "types", ".", "Mount", ",", "Dict", "[", "str", ",", "Optional", "[", "str", "]", "]", "]", ":", "to_...
Update the internal cache of attached instruments. This method allows after-init-time specification of attached simulated instruments. The method will return - the instruments specified at init-time, or if those do not exists, - the instruments specified in expected, or if that is not passed, - nothing :param expected: A mapping of mount to instrument model prefixes. When loading instruments from a prefix, we return the lexically-first model that matches the prefix. If the models specified in expected do not match the models specified in the `attached_instruments` argument of :py:meth:`__init__`, :py:attr:`RuntimeError` is raised. :raises RuntimeError: If an instrument is expected but not found. :returns: A dict of mount to either instrument model names or `None`.
[ "Update", "the", "internal", "cache", "of", "attached", "instruments", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/simulator.py#L115-L169
train
198,023
Opentrons/opentrons
api/src/opentrons/system/smoothie_update.py
_ensure_programmer_executable
def _ensure_programmer_executable(): """ Find the lpc21isp executable and ensure it is executable """ # Find the lpc21isp executable, explicitly allowing the case where it # is not executable (since that’s exactly what we’re trying to fix) updater_executable = shutil.which('lpc21isp', mode=os.F_OK) # updater_executable might be None; we’re passing it here unchecked # because if it is None, we’re about to fail when we try to program # the smoothie, and we want the exception to bubble up. os.chmod(updater_executable, 0o777)
python
def _ensure_programmer_executable(): """ Find the lpc21isp executable and ensure it is executable """ # Find the lpc21isp executable, explicitly allowing the case where it # is not executable (since that’s exactly what we’re trying to fix) updater_executable = shutil.which('lpc21isp', mode=os.F_OK) # updater_executable might be None; we’re passing it here unchecked # because if it is None, we’re about to fail when we try to program # the smoothie, and we want the exception to bubble up. os.chmod(updater_executable, 0o777)
[ "def", "_ensure_programmer_executable", "(", ")", ":", "# Find the lpc21isp executable, explicitly allowing the case where it", "# is not executable (since that’s exactly what we’re trying to fix)", "updater_executable", "=", "shutil", ".", "which", "(", "'lpc21isp'", ",", "mode", "=...
Find the lpc21isp executable and ensure it is executable
[ "Find", "the", "lpc21isp", "executable", "and", "ensure", "it", "is", "executable" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/smoothie_update.py#L6-L16
train
198,024
Opentrons/opentrons
api/src/opentrons/server/endpoints/serverlib_fallback.py
restart
async def restart(request): """ Returns OK, then waits approximately 1 second and restarts container """ def wait_and_restart(): log.info('Restarting server') sleep(1) os.system('kill 1') Thread(target=wait_and_restart).start() return web.json_response({"message": "restarting"})
python
async def restart(request): """ Returns OK, then waits approximately 1 second and restarts container """ def wait_and_restart(): log.info('Restarting server') sleep(1) os.system('kill 1') Thread(target=wait_and_restart).start() return web.json_response({"message": "restarting"})
[ "async", "def", "restart", "(", "request", ")", ":", "def", "wait_and_restart", "(", ")", ":", "log", ".", "info", "(", "'Restarting server'", ")", "sleep", "(", "1", ")", "os", ".", "system", "(", "'kill 1'", ")", "Thread", "(", "target", "=", "wait_a...
Returns OK, then waits approximately 1 second and restarts container
[ "Returns", "OK", "then", "waits", "approximately", "1", "second", "and", "restarts", "container" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/serverlib_fallback.py#L197-L206
train
198,025
Opentrons/opentrons
update-server/otupdate/buildroot/__init__.py
get_app
def get_app(system_version_file: str = None, config_file_override: str = None, name_override: str = None, loop: asyncio.AbstractEventLoop = None) -> web.Application: """ Build and return the aiohttp.web.Application that runs the server The params can be overloaded for testing. """ if not system_version_file: system_version_file = BR_BUILTIN_VERSION_FILE version = get_version(system_version_file) name = name_override or name_management.get_name() config_obj = config.load(config_file_override) LOG.info("Setup: " + '\n\t'.join([ f'Device name: {name}', f'Buildroot version: ' f'{version.get("buildroot_version", "unknown")}', f'\t(from git sha ' f'{version.get("buildroot_sha", "unknown")}', f'API version: ' f'{version.get("opentrons_api_version", "unknown")}', f'\t(from git sha ' f'{version.get("opentrons_api_sha", "unknown")}', f'Update server version: ' f'{version.get("update_server_version", "unknown")}', f'\t(from git sha ' f'{version.get("update_server_sha", "unknown")}', f'Smoothie firmware version: TODO' ])) if not loop: loop = asyncio.get_event_loop() app = web.Application(loop=loop, middlewares=[log_error_middleware]) app[config.CONFIG_VARNAME] = config_obj app[constants.RESTART_LOCK_NAME] = asyncio.Lock() app[constants.DEVICE_NAME_VARNAME] = name app.router.add_routes([ web.get('/server/update/health', control.build_health_endpoint(version)), web.post('/server/update/begin', update.begin), web.post('/server/update/cancel', update.cancel), web.get('/server/update/{session}/status', update.status), web.post('/server/update/{session}/file', update.file_upload), web.post('/server/update/{session}/commit', update.commit), web.post('/server/restart', control.restart), web.get('/server/ssh_keys', ssh_key_management.list_keys), web.post('/server/ssh_keys', ssh_key_management.add), web.delete('/server/ssh_keys/{key_md5}', ssh_key_management.remove), web.post('/server/name', name_management.set_name_endpoint), web.get('/server/name', name_management.get_name_endpoint), ]) return app
python
def get_app(system_version_file: str = None, config_file_override: str = None, name_override: str = None, loop: asyncio.AbstractEventLoop = None) -> web.Application: """ Build and return the aiohttp.web.Application that runs the server The params can be overloaded for testing. """ if not system_version_file: system_version_file = BR_BUILTIN_VERSION_FILE version = get_version(system_version_file) name = name_override or name_management.get_name() config_obj = config.load(config_file_override) LOG.info("Setup: " + '\n\t'.join([ f'Device name: {name}', f'Buildroot version: ' f'{version.get("buildroot_version", "unknown")}', f'\t(from git sha ' f'{version.get("buildroot_sha", "unknown")}', f'API version: ' f'{version.get("opentrons_api_version", "unknown")}', f'\t(from git sha ' f'{version.get("opentrons_api_sha", "unknown")}', f'Update server version: ' f'{version.get("update_server_version", "unknown")}', f'\t(from git sha ' f'{version.get("update_server_sha", "unknown")}', f'Smoothie firmware version: TODO' ])) if not loop: loop = asyncio.get_event_loop() app = web.Application(loop=loop, middlewares=[log_error_middleware]) app[config.CONFIG_VARNAME] = config_obj app[constants.RESTART_LOCK_NAME] = asyncio.Lock() app[constants.DEVICE_NAME_VARNAME] = name app.router.add_routes([ web.get('/server/update/health', control.build_health_endpoint(version)), web.post('/server/update/begin', update.begin), web.post('/server/update/cancel', update.cancel), web.get('/server/update/{session}/status', update.status), web.post('/server/update/{session}/file', update.file_upload), web.post('/server/update/{session}/commit', update.commit), web.post('/server/restart', control.restart), web.get('/server/ssh_keys', ssh_key_management.list_keys), web.post('/server/ssh_keys', ssh_key_management.add), web.delete('/server/ssh_keys/{key_md5}', ssh_key_management.remove), web.post('/server/name', name_management.set_name_endpoint), web.get('/server/name', name_management.get_name_endpoint), ]) return app
[ "def", "get_app", "(", "system_version_file", ":", "str", "=", "None", ",", "config_file_override", ":", "str", "=", "None", ",", "name_override", ":", "str", "=", "None", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ")", "->", "web"...
Build and return the aiohttp.web.Application that runs the server The params can be overloaded for testing.
[ "Build", "and", "return", "the", "aiohttp", ".", "web", ".", "Application", "that", "runs", "the", "server" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/__init__.py#L34-L88
train
198,026
Opentrons/opentrons
api/src/opentrons/server/rpc.py
RPCServer.on_shutdown
async def on_shutdown(self, app): """ Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown """ for ws in self.clients.copy(): await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown') self.shutdown()
python
async def on_shutdown(self, app): """ Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown """ for ws in self.clients.copy(): await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown') self.shutdown()
[ "async", "def", "on_shutdown", "(", "self", ",", "app", ")", ":", "for", "ws", "in", "self", ".", "clients", ".", "copy", "(", ")", ":", "await", "ws", ".", "close", "(", "code", "=", "WSCloseCode", ".", "GOING_AWAY", ",", "message", "=", "'Server sh...
Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown
[ "Graceful", "shutdown", "handler" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/rpc.py#L71-L80
train
198,027
Opentrons/opentrons
api/src/opentrons/server/rpc.py
RPCServer.handler
async def handler(self, request): """ Receives HTTP request and negotiates up to a Websocket session """ def task_done(future): self.tasks.remove(future) exception = future.exception() if exception: log.warning( 'While processing message: {0}\nDetails: {1}'.format( exception, traceback.format_exc()) ) client = web.WebSocketResponse() client_id = id(client) # upgrade to Websockets await client.prepare(request) log.info('Opening Websocket {0}'.format(id(client))) log.debug('Tasks: {0}'.format(self.tasks)) log.debug('Clients: {0}'.format(self.clients)) try: log.debug('Sending root info to {0}'.format(client_id)) await client.send_json({ '$': {'type': CONTROL_MESSAGE, 'monitor': True}, 'root': self.call_and_serialize(lambda: self.root), 'type': self.call_and_serialize(lambda: type(self.root)) }) log.debug('Root info sent to {0}'.format(client_id)) except Exception: log.exception('While sending root info to {0}'.format(client_id)) try: self.clients[client] = self.send_worker(client) # Async receive client data until websocket is closed async for msg in client: task = self.loop.create_task(self.process(msg)) task.add_done_callback(task_done) self.tasks += [task] except Exception: log.exception('While reading from socket:') finally: log.info('Closing WebSocket {0}'.format(id(client))) await client.close() del self.clients[client] return client
python
async def handler(self, request): """ Receives HTTP request and negotiates up to a Websocket session """ def task_done(future): self.tasks.remove(future) exception = future.exception() if exception: log.warning( 'While processing message: {0}\nDetails: {1}'.format( exception, traceback.format_exc()) ) client = web.WebSocketResponse() client_id = id(client) # upgrade to Websockets await client.prepare(request) log.info('Opening Websocket {0}'.format(id(client))) log.debug('Tasks: {0}'.format(self.tasks)) log.debug('Clients: {0}'.format(self.clients)) try: log.debug('Sending root info to {0}'.format(client_id)) await client.send_json({ '$': {'type': CONTROL_MESSAGE, 'monitor': True}, 'root': self.call_and_serialize(lambda: self.root), 'type': self.call_and_serialize(lambda: type(self.root)) }) log.debug('Root info sent to {0}'.format(client_id)) except Exception: log.exception('While sending root info to {0}'.format(client_id)) try: self.clients[client] = self.send_worker(client) # Async receive client data until websocket is closed async for msg in client: task = self.loop.create_task(self.process(msg)) task.add_done_callback(task_done) self.tasks += [task] except Exception: log.exception('While reading from socket:') finally: log.info('Closing WebSocket {0}'.format(id(client))) await client.close() del self.clients[client] return client
[ "async", "def", "handler", "(", "self", ",", "request", ")", ":", "def", "task_done", "(", "future", ")", ":", "self", ".", "tasks", ".", "remove", "(", "future", ")", "exception", "=", "future", ".", "exception", "(", ")", "if", "exception", ":", "l...
Receives HTTP request and negotiates up to a Websocket session
[ "Receives", "HTTP", "request", "and", "negotiates", "up", "to", "a", "Websocket", "session" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/rpc.py#L128-L178
train
198,028
Opentrons/opentrons
api/src/opentrons/server/rpc.py
RPCServer.resolve_args
def resolve_args(self, args): """ Resolve function call arguments that have object ids into instances of these objects """ def resolve(a): if isinstance(a, dict): _id = a.get('i', None) # If it's a compound type (including dict) # Check if it has id (i) to determine that it has # a reference in object storage. If it's None, then it's # a dict originated at the remote return self.objects[_id] if _id else a['v'] # if array, resolve it's elements if isinstance(a, (list, tuple)): return [resolve(i) for i in a] return a return [resolve(a) for a in args]
python
def resolve_args(self, args): """ Resolve function call arguments that have object ids into instances of these objects """ def resolve(a): if isinstance(a, dict): _id = a.get('i', None) # If it's a compound type (including dict) # Check if it has id (i) to determine that it has # a reference in object storage. If it's None, then it's # a dict originated at the remote return self.objects[_id] if _id else a['v'] # if array, resolve it's elements if isinstance(a, (list, tuple)): return [resolve(i) for i in a] return a return [resolve(a) for a in args]
[ "def", "resolve_args", "(", "self", ",", "args", ")", ":", "def", "resolve", "(", "a", ")", ":", "if", "isinstance", "(", "a", ",", "dict", ")", ":", "_id", "=", "a", ".", "get", "(", "'i'", ",", "None", ")", "# If it's a compound type (including dict)...
Resolve function call arguments that have object ids into instances of these objects
[ "Resolve", "function", "call", "arguments", "that", "have", "object", "ids", "into", "instances", "of", "these", "objects" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/rpc.py#L207-L225
train
198,029
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.build_hardware_controller
async def build_hardware_controller( cls, config: robot_configs.robot_config = None, port: str = None, loop: asyncio.AbstractEventLoop = None, force: bool = False) -> 'API': """ Build a hardware controller that will actually talk to hardware. This method should not be used outside of a real robot, and on a real robot only one true hardware controller may be active at one time. :param config: A config to preload. If not specified, load the default. :param port: A port to connect to. If not specified, the default port (found by scanning for connected FT232Rs). :param loop: An event loop to use. If not specified, use the result of :py:meth:`asyncio.get_event_loop`. :param force: If `True`, connect even if a lockfile is present. See :py:meth:`Controller.__init__`. """ if None is Controller: raise RuntimeError( 'The hardware controller may only be instantiated on a robot') checked_loop = loop or asyncio.get_event_loop() backend = Controller(config, checked_loop, force=force) await backend.connect(port) return cls(backend, config=config, loop=checked_loop)
python
async def build_hardware_controller( cls, config: robot_configs.robot_config = None, port: str = None, loop: asyncio.AbstractEventLoop = None, force: bool = False) -> 'API': """ Build a hardware controller that will actually talk to hardware. This method should not be used outside of a real robot, and on a real robot only one true hardware controller may be active at one time. :param config: A config to preload. If not specified, load the default. :param port: A port to connect to. If not specified, the default port (found by scanning for connected FT232Rs). :param loop: An event loop to use. If not specified, use the result of :py:meth:`asyncio.get_event_loop`. :param force: If `True`, connect even if a lockfile is present. See :py:meth:`Controller.__init__`. """ if None is Controller: raise RuntimeError( 'The hardware controller may only be instantiated on a robot') checked_loop = loop or asyncio.get_event_loop() backend = Controller(config, checked_loop, force=force) await backend.connect(port) return cls(backend, config=config, loop=checked_loop)
[ "async", "def", "build_hardware_controller", "(", "cls", ",", "config", ":", "robot_configs", ".", "robot_config", "=", "None", ",", "port", ":", "str", "=", "None", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ",", "force", ":", "bo...
Build a hardware controller that will actually talk to hardware. This method should not be used outside of a real robot, and on a real robot only one true hardware controller may be active at one time. :param config: A config to preload. If not specified, load the default. :param port: A port to connect to. If not specified, the default port (found by scanning for connected FT232Rs). :param loop: An event loop to use. If not specified, use the result of :py:meth:`asyncio.get_event_loop`. :param force: If `True`, connect even if a lockfile is present. See :py:meth:`Controller.__init__`.
[ "Build", "a", "hardware", "controller", "that", "will", "actually", "talk", "to", "hardware", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L107-L132
train
198,030
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.build_hardware_simulator
def build_hardware_simulator( cls, attached_instruments: Dict[top_types.Mount, Dict[str, Optional[str]]] = None, # noqa E501 attached_modules: List[str] = None, config: robot_configs.robot_config = None, loop: asyncio.AbstractEventLoop = None, strict_attached_instruments: bool = True) -> 'API': """ Build a simulating hardware controller. This method may be used both on a real robot and on dev machines. Multiple simulating hardware controllers may be active at one time. """ if None is attached_instruments: attached_instruments = {} if None is attached_modules: attached_modules = [] return cls(Simulator(attached_instruments, attached_modules, config, loop, strict_attached_instruments), config=config, loop=loop)
python
def build_hardware_simulator( cls, attached_instruments: Dict[top_types.Mount, Dict[str, Optional[str]]] = None, # noqa E501 attached_modules: List[str] = None, config: robot_configs.robot_config = None, loop: asyncio.AbstractEventLoop = None, strict_attached_instruments: bool = True) -> 'API': """ Build a simulating hardware controller. This method may be used both on a real robot and on dev machines. Multiple simulating hardware controllers may be active at one time. """ if None is attached_instruments: attached_instruments = {} if None is attached_modules: attached_modules = [] return cls(Simulator(attached_instruments, attached_modules, config, loop, strict_attached_instruments), config=config, loop=loop)
[ "def", "build_hardware_simulator", "(", "cls", ",", "attached_instruments", ":", "Dict", "[", "top_types", ".", "Mount", ",", "Dict", "[", "str", ",", "Optional", "[", "str", "]", "]", "]", "=", "None", ",", "# noqa E501", "attached_modules", ":", "List", ...
Build a simulating hardware controller. This method may be used both on a real robot and on dev machines. Multiple simulating hardware controllers may be active at one time.
[ "Build", "a", "simulating", "hardware", "controller", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L135-L157
train
198,031
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.register_callback
async def register_callback(self, cb): """ Allows the caller to register a callback, and returns a closure that can be used to unregister the provided callback """ self._callbacks.add(cb) def unregister(): self._callbacks.remove(cb) return unregister
python
async def register_callback(self, cb): """ Allows the caller to register a callback, and returns a closure that can be used to unregister the provided callback """ self._callbacks.add(cb) def unregister(): self._callbacks.remove(cb) return unregister
[ "async", "def", "register_callback", "(", "self", ",", "cb", ")", ":", "self", ".", "_callbacks", ".", "add", "(", "cb", ")", "def", "unregister", "(", ")", ":", "self", ".", "_callbacks", ".", "remove", "(", "cb", ")", "return", "unregister" ]
Allows the caller to register a callback, and returns a closure that can be used to unregister the provided callback
[ "Allows", "the", "caller", "to", "register", "a", "callback", "and", "returns", "a", "closure", "that", "can", "be", "used", "to", "unregister", "the", "provided", "callback" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L178-L187
train
198,032
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.set_lights
def set_lights(self, button: bool = None, rails: bool = None): """ Control the robot lights. :param button: If specified, turn the button light on (`True`) or off (`False`). If not specified, do not change the button light. :param rails: If specified, turn the rail lights on (`True`) or off (`False`). If not specified, do not change the rail lights. """ self._backend.set_lights(button, rails)
python
def set_lights(self, button: bool = None, rails: bool = None): """ Control the robot lights. :param button: If specified, turn the button light on (`True`) or off (`False`). If not specified, do not change the button light. :param rails: If specified, turn the rail lights on (`True`) or off (`False`). If not specified, do not change the rail lights. """ self._backend.set_lights(button, rails)
[ "def", "set_lights", "(", "self", ",", "button", ":", "bool", "=", "None", ",", "rails", ":", "bool", "=", "None", ")", ":", "self", ".", "_backend", ".", "set_lights", "(", "button", ",", "rails", ")" ]
Control the robot lights. :param button: If specified, turn the button light on (`True`) or off (`False`). If not specified, do not change the button light. :param rails: If specified, turn the rail lights on (`True`) or off (`False`). If not specified, do not change the rail lights.
[ "Control", "the", "robot", "lights", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L205-L215
train
198,033
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.identify
async def identify(self, duration_s: int = 5): """ Blink the button light to identify the robot. :param int duration_s: The duration to blink for, in seconds. """ count = duration_s * 4 on = False for sec in range(count): then = self._loop.time() self.set_lights(button=on) on = not on now = self._loop.time() await asyncio.sleep(max(0, 0.25-(now-then))) self.set_lights(button=True)
python
async def identify(self, duration_s: int = 5): """ Blink the button light to identify the robot. :param int duration_s: The duration to blink for, in seconds. """ count = duration_s * 4 on = False for sec in range(count): then = self._loop.time() self.set_lights(button=on) on = not on now = self._loop.time() await asyncio.sleep(max(0, 0.25-(now-then))) self.set_lights(button=True)
[ "async", "def", "identify", "(", "self", ",", "duration_s", ":", "int", "=", "5", ")", ":", "count", "=", "duration_s", "*", "4", "on", "=", "False", "for", "sec", "in", "range", "(", "count", ")", ":", "then", "=", "self", ".", "_loop", ".", "ti...
Blink the button light to identify the robot. :param int duration_s: The duration to blink for, in seconds.
[ "Blink", "the", "button", "light", "to", "identify", "the", "robot", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L226-L239
train
198,034
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.cache_instruments
async def cache_instruments(self, require: Dict[top_types.Mount, str] = None): """ - Get the attached instrument on each mount and - Cache their pipette configs from pipette-config.json If specified, the require element should be a dict of mounts to instrument models describing the instruments expected to be present. This can save a subsequent of :py:attr:`attached_instruments` and also serves as the hook for the hardware simulator to decide what is attached. """ checked_require = require or {} self._log.info("Updating instrument model cache") found = self._backend.get_attached_instruments(checked_require) for mount, instrument_data in found.items(): model = instrument_data.get('model') if model is not None: p = Pipette(model, self._config.instrument_offset[mount.name.lower()], instrument_data['id']) self._attached_instruments[mount] = p else: self._attached_instruments[mount] = None mod_log.info("Instruments found: {}".format( self._attached_instruments))
python
async def cache_instruments(self, require: Dict[top_types.Mount, str] = None): """ - Get the attached instrument on each mount and - Cache their pipette configs from pipette-config.json If specified, the require element should be a dict of mounts to instrument models describing the instruments expected to be present. This can save a subsequent of :py:attr:`attached_instruments` and also serves as the hook for the hardware simulator to decide what is attached. """ checked_require = require or {} self._log.info("Updating instrument model cache") found = self._backend.get_attached_instruments(checked_require) for mount, instrument_data in found.items(): model = instrument_data.get('model') if model is not None: p = Pipette(model, self._config.instrument_offset[mount.name.lower()], instrument_data['id']) self._attached_instruments[mount] = p else: self._attached_instruments[mount] = None mod_log.info("Instruments found: {}".format( self._attached_instruments))
[ "async", "def", "cache_instruments", "(", "self", ",", "require", ":", "Dict", "[", "top_types", ".", "Mount", ",", "str", "]", "=", "None", ")", ":", "checked_require", "=", "require", "or", "{", "}", "self", ".", "_log", ".", "info", "(", "\"Updating...
- Get the attached instrument on each mount and - Cache their pipette configs from pipette-config.json If specified, the require element should be a dict of mounts to instrument models describing the instruments expected to be present. This can save a subsequent of :py:attr:`attached_instruments` and also serves as the hook for the hardware simulator to decide what is attached.
[ "-", "Get", "the", "attached", "instrument", "on", "each", "mount", "and", "-", "Cache", "their", "pipette", "configs", "from", "pipette", "-", "config", ".", "json" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L248-L273
train
198,035
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.update_firmware
async def update_firmware( self, firmware_file: str, loop: asyncio.AbstractEventLoop = None, explicit_modeset: bool = True) -> str: """ Update the firmware on the Smoothie board. :param firmware_file: The path to the firmware file. :param explicit_modeset: `True` to force the smoothie into programming mode; `False` to assume it is already in programming mode. :param loop: An asyncio event loop to use; if not specified, the one associated with this instance will be used. :returns: The stdout of the tool used to update the smoothie """ if None is loop: checked_loop = self._loop else: checked_loop = loop return await self._backend.update_firmware(firmware_file, checked_loop, explicit_modeset)
python
async def update_firmware( self, firmware_file: str, loop: asyncio.AbstractEventLoop = None, explicit_modeset: bool = True) -> str: """ Update the firmware on the Smoothie board. :param firmware_file: The path to the firmware file. :param explicit_modeset: `True` to force the smoothie into programming mode; `False` to assume it is already in programming mode. :param loop: An asyncio event loop to use; if not specified, the one associated with this instance will be used. :returns: The stdout of the tool used to update the smoothie """ if None is loop: checked_loop = self._loop else: checked_loop = loop return await self._backend.update_firmware(firmware_file, checked_loop, explicit_modeset)
[ "async", "def", "update_firmware", "(", "self", ",", "firmware_file", ":", "str", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ",", "explicit_modeset", ":", "bool", "=", "True", ")", "->", "str", ":", "if", "None", "is", "loop", ":...
Update the firmware on the Smoothie board. :param firmware_file: The path to the firmware file. :param explicit_modeset: `True` to force the smoothie into programming mode; `False` to assume it is already in programming mode. :param loop: An asyncio event loop to use; if not specified, the one associated with this instance will be used. :returns: The stdout of the tool used to update the smoothie
[ "Update", "the", "firmware", "on", "the", "Smoothie", "board", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L298-L319
train
198,036
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.home_z
async def home_z(self, mount: top_types.Mount = None): """ Home the two z-axes """ if not mount: axes = [Axis.Z, Axis.A] else: axes = [Axis.by_mount(mount)] await self.home(axes)
python
async def home_z(self, mount: top_types.Mount = None): """ Home the two z-axes """ if not mount: axes = [Axis.Z, Axis.A] else: axes = [Axis.by_mount(mount)] await self.home(axes)
[ "async", "def", "home_z", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", "=", "None", ")", ":", "if", "not", "mount", ":", "axes", "=", "[", "Axis", ".", "Z", ",", "Axis", ".", "A", "]", "else", ":", "axes", "=", "[", "Axis", ".", ...
Home the two z-axes
[ "Home", "the", "two", "z", "-", "axes" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L374-L380
train
198,037
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.home_plunger
async def home_plunger(self, mount: top_types.Mount): """ Home the plunger motor for a mount, and then return it to the 'bottom' position. :param mount: the mount associated with the target plunger :type mount: :py:class:`.top_types.Mount` """ instr = self._attached_instruments[mount] if instr: await self.home([Axis.of_plunger(mount)]) await self._move_plunger(mount, instr.config.bottom)
python
async def home_plunger(self, mount: top_types.Mount): """ Home the plunger motor for a mount, and then return it to the 'bottom' position. :param mount: the mount associated with the target plunger :type mount: :py:class:`.top_types.Mount` """ instr = self._attached_instruments[mount] if instr: await self.home([Axis.of_plunger(mount)]) await self._move_plunger(mount, instr.config.bottom)
[ "async", "def", "home_plunger", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ")", ":", "instr", "=", "self", ".", "_attached_instruments", "[", "mount", "]", "if", "instr", ":", "await", "self", ".", "home", "(", "[", "Axis", ".", "of_plu...
Home the plunger motor for a mount, and then return it to the 'bottom' position. :param mount: the mount associated with the target plunger :type mount: :py:class:`.top_types.Mount`
[ "Home", "the", "plunger", "motor", "for", "a", "mount", "and", "then", "return", "it", "to", "the", "bottom", "position", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L383-L395
train
198,038
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API._deck_from_smoothie
def _deck_from_smoothie( self, smoothie_pos: Dict[str, float]) -> Dict[Axis, float]: """ Build a deck-abs position store from the smoothie's position This should take the smoothie style position {'X': float, etc} and turn it into the position dict used here {Axis.X: float} in deck-absolute coordinates. It runs the reverse deck transformation for the axes that require it. One piece of complexity is that if the gantry transformation includes a transition between non parallel planes, the z position of the left mount would depend on its actual position in deck frame, so we have to apply the mount offset. TODO: Figure out which frame the mount offset is measured in, because if it's measured in the deck frame (e.g. by touching off points on the deck) it has to go through the reverse transform to be added to the smoothie coordinates here. """ with_enum = {Axis[k]: v for k, v in smoothie_pos.items()} plunger_axes = {k: v for k, v in with_enum.items() if k not in Axis.gantry_axes()} right = (with_enum[Axis.X], with_enum[Axis.Y], with_enum[Axis.by_mount(top_types.Mount.RIGHT)]) # Tell apply_transform to just do the change of base part of the # transform rather than the full affine transform, because this is # an offset left = (with_enum[Axis.X], with_enum[Axis.Y], with_enum[Axis.by_mount(top_types.Mount.LEFT)]) right_deck = linal.apply_reverse(self.config.gantry_calibration, right) left_deck = linal.apply_reverse(self.config.gantry_calibration, left) deck_pos = {Axis.X: right_deck[0], Axis.Y: right_deck[1], Axis.by_mount(top_types.Mount.RIGHT): right_deck[2], Axis.by_mount(top_types.Mount.LEFT): left_deck[2]} deck_pos.update(plunger_axes) return deck_pos
python
def _deck_from_smoothie( self, smoothie_pos: Dict[str, float]) -> Dict[Axis, float]: """ Build a deck-abs position store from the smoothie's position This should take the smoothie style position {'X': float, etc} and turn it into the position dict used here {Axis.X: float} in deck-absolute coordinates. It runs the reverse deck transformation for the axes that require it. One piece of complexity is that if the gantry transformation includes a transition between non parallel planes, the z position of the left mount would depend on its actual position in deck frame, so we have to apply the mount offset. TODO: Figure out which frame the mount offset is measured in, because if it's measured in the deck frame (e.g. by touching off points on the deck) it has to go through the reverse transform to be added to the smoothie coordinates here. """ with_enum = {Axis[k]: v for k, v in smoothie_pos.items()} plunger_axes = {k: v for k, v in with_enum.items() if k not in Axis.gantry_axes()} right = (with_enum[Axis.X], with_enum[Axis.Y], with_enum[Axis.by_mount(top_types.Mount.RIGHT)]) # Tell apply_transform to just do the change of base part of the # transform rather than the full affine transform, because this is # an offset left = (with_enum[Axis.X], with_enum[Axis.Y], with_enum[Axis.by_mount(top_types.Mount.LEFT)]) right_deck = linal.apply_reverse(self.config.gantry_calibration, right) left_deck = linal.apply_reverse(self.config.gantry_calibration, left) deck_pos = {Axis.X: right_deck[0], Axis.Y: right_deck[1], Axis.by_mount(top_types.Mount.RIGHT): right_deck[2], Axis.by_mount(top_types.Mount.LEFT): left_deck[2]} deck_pos.update(plunger_axes) return deck_pos
[ "def", "_deck_from_smoothie", "(", "self", ",", "smoothie_pos", ":", "Dict", "[", "str", ",", "float", "]", ")", "->", "Dict", "[", "Axis", ",", "float", "]", ":", "with_enum", "=", "{", "Axis", "[", "k", "]", ":", "v", "for", "k", ",", "v", "in"...
Build a deck-abs position store from the smoothie's position This should take the smoothie style position {'X': float, etc} and turn it into the position dict used here {Axis.X: float} in deck-absolute coordinates. It runs the reverse deck transformation for the axes that require it. One piece of complexity is that if the gantry transformation includes a transition between non parallel planes, the z position of the left mount would depend on its actual position in deck frame, so we have to apply the mount offset. TODO: Figure out which frame the mount offset is measured in, because if it's measured in the deck frame (e.g. by touching off points on the deck) it has to go through the reverse transform to be added to the smoothie coordinates here.
[ "Build", "a", "deck", "-", "abs", "position", "store", "from", "the", "smoothie", "s", "position" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L441-L480
train
198,039
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.gantry_position
async def gantry_position( self, mount: top_types.Mount, critical_point: CriticalPoint = None) -> top_types.Point: """ Return the position of the critical point as pertains to the gantry This ignores the plunger position and gives the Z-axis a predictable name (as :py:attr:`.Point.z`). `critical_point` specifies an override to the current critical point to use (see :py:meth:`current_position`). """ cur_pos = await self.current_position(mount, critical_point) return top_types.Point(x=cur_pos[Axis.X], y=cur_pos[Axis.Y], z=cur_pos[Axis.by_mount(mount)])
python
async def gantry_position( self, mount: top_types.Mount, critical_point: CriticalPoint = None) -> top_types.Point: """ Return the position of the critical point as pertains to the gantry This ignores the plunger position and gives the Z-axis a predictable name (as :py:attr:`.Point.z`). `critical_point` specifies an override to the current critical point to use (see :py:meth:`current_position`). """ cur_pos = await self.current_position(mount, critical_point) return top_types.Point(x=cur_pos[Axis.X], y=cur_pos[Axis.Y], z=cur_pos[Axis.by_mount(mount)])
[ "async", "def", "gantry_position", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ",", "critical_point", ":", "CriticalPoint", "=", "None", ")", "->", "top_types", ".", "Point", ":", "cur_pos", "=", "await", "self", ".", "current_position", "(", ...
Return the position of the critical point as pertains to the gantry This ignores the plunger position and gives the Z-axis a predictable name (as :py:attr:`.Point.z`). `critical_point` specifies an override to the current critical point to use (see :py:meth:`current_position`).
[ "Return", "the", "position", "of", "the", "critical", "point", "as", "pertains", "to", "the", "gantry" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L517-L532
train
198,040
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.move_to
async def move_to( self, mount: top_types.Mount, abs_position: top_types.Point, speed: float = None, critical_point: CriticalPoint = None): """ Move the critical point of the specified mount to a location relative to the deck, at the specified speed. 'speed' sets the speed of all robot axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed The critical point of the mount depends on the current status of the mount: - If the mount does not have anything attached, its critical point is the bottom of the mount attach bracket. - If the mount has a pipette attached and it is not known to have a pipette tip, the critical point is the end of the nozzle of a single pipette or the end of the backmost nozzle of a multipipette - If the mount has a pipette attached and it is known to have a pipette tip, the critical point is the end of the pipette tip for a single pipette or the end of the tip of the backmost nozzle of a multipipette :param mount: The mount to move :param abs_position: The target absolute position in :ref:`protocol-api-deck-coords` to move the critical point to :param speed: An overall head speed to use during the move :param critical_point: The critical point to move. In most situations this is not needed. If not specified, the current critical point will be moved. If specified, the critical point must be one that actually exists - that is, specifying :py:attr:`.CriticalPoint.NOZZLE` when no pipette is attached or :py:attr:`.CriticalPoint.TIP` when no tip is applied will result in an error. """ if not self._current_position: raise MustHomeError await self._cache_and_maybe_retract_mount(mount) z_axis = Axis.by_mount(mount) if mount == top_types.Mount.LEFT: offset = top_types.Point(*self.config.mount_offset) else: offset = top_types.Point(0, 0, 0) cp = self._critical_point_for(mount, critical_point) target_position = OrderedDict( ((Axis.X, abs_position.x - offset.x - cp.x), (Axis.Y, abs_position.y - offset.y - cp.y), (z_axis, abs_position.z - offset.z - cp.z)) ) await self._move(target_position, speed=speed)
python
async def move_to( self, mount: top_types.Mount, abs_position: top_types.Point, speed: float = None, critical_point: CriticalPoint = None): """ Move the critical point of the specified mount to a location relative to the deck, at the specified speed. 'speed' sets the speed of all robot axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed The critical point of the mount depends on the current status of the mount: - If the mount does not have anything attached, its critical point is the bottom of the mount attach bracket. - If the mount has a pipette attached and it is not known to have a pipette tip, the critical point is the end of the nozzle of a single pipette or the end of the backmost nozzle of a multipipette - If the mount has a pipette attached and it is known to have a pipette tip, the critical point is the end of the pipette tip for a single pipette or the end of the tip of the backmost nozzle of a multipipette :param mount: The mount to move :param abs_position: The target absolute position in :ref:`protocol-api-deck-coords` to move the critical point to :param speed: An overall head speed to use during the move :param critical_point: The critical point to move. In most situations this is not needed. If not specified, the current critical point will be moved. If specified, the critical point must be one that actually exists - that is, specifying :py:attr:`.CriticalPoint.NOZZLE` when no pipette is attached or :py:attr:`.CriticalPoint.TIP` when no tip is applied will result in an error. """ if not self._current_position: raise MustHomeError await self._cache_and_maybe_retract_mount(mount) z_axis = Axis.by_mount(mount) if mount == top_types.Mount.LEFT: offset = top_types.Point(*self.config.mount_offset) else: offset = top_types.Point(0, 0, 0) cp = self._critical_point_for(mount, critical_point) target_position = OrderedDict( ((Axis.X, abs_position.x - offset.x - cp.x), (Axis.Y, abs_position.y - offset.y - cp.y), (z_axis, abs_position.z - offset.z - cp.z)) ) await self._move(target_position, speed=speed)
[ "async", "def", "move_to", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ",", "abs_position", ":", "top_types", ".", "Point", ",", "speed", ":", "float", "=", "None", ",", "critical_point", ":", "CriticalPoint", "=", "None", ")", ":", "if", ...
Move the critical point of the specified mount to a location relative to the deck, at the specified speed. 'speed' sets the speed of all robot axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed The critical point of the mount depends on the current status of the mount: - If the mount does not have anything attached, its critical point is the bottom of the mount attach bracket. - If the mount has a pipette attached and it is not known to have a pipette tip, the critical point is the end of the nozzle of a single pipette or the end of the backmost nozzle of a multipipette - If the mount has a pipette attached and it is known to have a pipette tip, the critical point is the end of the pipette tip for a single pipette or the end of the tip of the backmost nozzle of a multipipette :param mount: The mount to move :param abs_position: The target absolute position in :ref:`protocol-api-deck-coords` to move the critical point to :param speed: An overall head speed to use during the move :param critical_point: The critical point to move. In most situations this is not needed. If not specified, the current critical point will be moved. If specified, the critical point must be one that actually exists - that is, specifying :py:attr:`.CriticalPoint.NOZZLE` when no pipette is attached or :py:attr:`.CriticalPoint.TIP` when no tip is applied will result in an error.
[ "Move", "the", "critical", "point", "of", "the", "specified", "mount", "to", "a", "location", "relative", "to", "the", "deck", "at", "the", "specified", "speed", ".", "speed", "sets", "the", "speed", "of", "all", "robot", "axes", "to", "the", "given", "v...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L535-L586
train
198,041
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.move_rel
async def move_rel(self, mount: top_types.Mount, delta: top_types.Point, speed: float = None): """ Move the critical point of the specified mount by a specified displacement in a specified direction, at the specified speed. 'speed' sets the speed of all axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed """ if not self._current_position: raise MustHomeError await self._cache_and_maybe_retract_mount(mount) z_axis = Axis.by_mount(mount) try: target_position = OrderedDict( ((Axis.X, self._current_position[Axis.X] + delta.x), (Axis.Y, self._current_position[Axis.Y] + delta.y), (z_axis, self._current_position[z_axis] + delta.z)) ) except KeyError: raise MustHomeError await self._move(target_position, speed=speed)
python
async def move_rel(self, mount: top_types.Mount, delta: top_types.Point, speed: float = None): """ Move the critical point of the specified mount by a specified displacement in a specified direction, at the specified speed. 'speed' sets the speed of all axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed """ if not self._current_position: raise MustHomeError await self._cache_and_maybe_retract_mount(mount) z_axis = Axis.by_mount(mount) try: target_position = OrderedDict( ((Axis.X, self._current_position[Axis.X] + delta.x), (Axis.Y, self._current_position[Axis.Y] + delta.y), (z_axis, self._current_position[z_axis] + delta.z)) ) except KeyError: raise MustHomeError await self._move(target_position, speed=speed)
[ "async", "def", "move_rel", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ",", "delta", ":", "top_types", ".", "Point", ",", "speed", ":", "float", "=", "None", ")", ":", "if", "not", "self", ".", "_current_position", ":", "raise", "MustHo...
Move the critical point of the specified mount by a specified displacement in a specified direction, at the specified speed. 'speed' sets the speed of all axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed
[ "Move", "the", "critical", "point", "of", "the", "specified", "mount", "by", "a", "specified", "displacement", "in", "a", "specified", "direction", "at", "the", "specified", "speed", ".", "speed", "sets", "the", "speed", "of", "all", "axes", "to", "the", "...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L589-L613
train
198,042
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API._cache_and_maybe_retract_mount
async def _cache_and_maybe_retract_mount(self, mount: top_types.Mount): """ Retract the 'other' mount if necessary If `mount` does not match the value in :py:attr:`_last_moved_mount` (and :py:attr:`_last_moved_mount` exists) then retract the mount in :py:attr:`_last_moved_mount`. Also unconditionally update :py:attr:`_last_moved_mount` to contain `mount`. """ if mount != self._last_moved_mount and self._last_moved_mount: await self.retract(self._last_moved_mount, 10) self._last_moved_mount = mount
python
async def _cache_and_maybe_retract_mount(self, mount: top_types.Mount): """ Retract the 'other' mount if necessary If `mount` does not match the value in :py:attr:`_last_moved_mount` (and :py:attr:`_last_moved_mount` exists) then retract the mount in :py:attr:`_last_moved_mount`. Also unconditionally update :py:attr:`_last_moved_mount` to contain `mount`. """ if mount != self._last_moved_mount and self._last_moved_mount: await self.retract(self._last_moved_mount, 10) self._last_moved_mount = mount
[ "async", "def", "_cache_and_maybe_retract_mount", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ")", ":", "if", "mount", "!=", "self", ".", "_last_moved_mount", "and", "self", ".", "_last_moved_mount", ":", "await", "self", ".", "retract", "(", ...
Retract the 'other' mount if necessary If `mount` does not match the value in :py:attr:`_last_moved_mount` (and :py:attr:`_last_moved_mount` exists) then retract the mount in :py:attr:`_last_moved_mount`. Also unconditionally update :py:attr:`_last_moved_mount` to contain `mount`.
[ "Retract", "the", "other", "mount", "if", "necessary" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L615-L625
train
198,043
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API._move
async def _move(self, target_position: 'OrderedDict[Axis, float]', speed: float = None, home_flagged_axes: bool = True): """ Worker function to apply robot motion. Robot motion means the kind of motions that are relevant to the robot, i.e. only one pipette plunger and mount move at the same time, and an XYZ move in the coordinate frame of one of the pipettes. ``target_position`` should be an ordered dict (ordered by XYZABC) of deck calibrated values, containing any specified XY motion and at most one of a ZA or BC components. The frame in which to move is identified by the presence of (ZA) or (BC). """ # Transform only the x, y, and (z or a) axes specified since this could # get the b or c axes as well to_transform = tuple((tp for ax, tp in target_position.items() if ax in Axis.gantry_axes())) # Pre-fill the dict we’ll send to the backend with the axes we don’t # need to transform smoothie_pos = {ax.name: pos for ax, pos in target_position.items() if ax not in Axis.gantry_axes()} # We’d better have all of (x, y, (z or a)) or none of them since the # gantry transform requires them all if len(to_transform) != 3: self._log.error("Move derived {} axes to transform from {}" .format(len(to_transform), target_position)) raise ValueError("Moves must specify either exactly an x, y, and " "(z or a) or none of them") # Type ignored below because linal.apply_transform (rightly) specifies # Tuple[float, float, float] and the implied type from # target_position.items() is (rightly) Tuple[float, ...] with unbounded # size; unfortunately, mypy can’t quite figure out the length check # above that makes this OK transformed = linal.apply_transform( # type: ignore self.config.gantry_calibration, to_transform) # Since target_position is an OrderedDict with the axes ordered by # (x, y, z, a, b, c), and we’ll only have one of a or z (as checked # by the len(to_transform) check above) we can use an enumerate to # fuse the specified axes and the transformed values back together. # While we do this iteration, we’ll also check axis bounds. bounds = self._backend.axis_bounds for idx, ax in enumerate(target_position.keys()): if ax in Axis.gantry_axes(): smoothie_pos[ax.name] = transformed[idx] if smoothie_pos[ax.name] < bounds[ax.name][0]\ or smoothie_pos[ax.name] > bounds[ax.name][1]: deck_mins = self._deck_from_smoothie({ax: bound[0] for ax, bound in bounds.items()}) deck_max = self._deck_from_smoothie({ax: bound[1] for ax, bound in bounds.items()}) self._log.warning( "Out of bounds move: {}={} (transformed: {}) not in" "limits ({}, {}) (transformed: ({}, {})" .format(ax.name, target_position[ax], smoothie_pos[ax.name], deck_mins[ax], deck_max[ax], bounds[ax.name][0], bounds[ax.name][1])) async with self._motion_lock: try: self._backend.move(smoothie_pos, speed=speed, home_flagged_axes=home_flagged_axes) except Exception: self._log.exception('Move failed') self._current_position.clear() raise else: self._current_position.update(target_position)
python
async def _move(self, target_position: 'OrderedDict[Axis, float]', speed: float = None, home_flagged_axes: bool = True): """ Worker function to apply robot motion. Robot motion means the kind of motions that are relevant to the robot, i.e. only one pipette plunger and mount move at the same time, and an XYZ move in the coordinate frame of one of the pipettes. ``target_position`` should be an ordered dict (ordered by XYZABC) of deck calibrated values, containing any specified XY motion and at most one of a ZA or BC components. The frame in which to move is identified by the presence of (ZA) or (BC). """ # Transform only the x, y, and (z or a) axes specified since this could # get the b or c axes as well to_transform = tuple((tp for ax, tp in target_position.items() if ax in Axis.gantry_axes())) # Pre-fill the dict we’ll send to the backend with the axes we don’t # need to transform smoothie_pos = {ax.name: pos for ax, pos in target_position.items() if ax not in Axis.gantry_axes()} # We’d better have all of (x, y, (z or a)) or none of them since the # gantry transform requires them all if len(to_transform) != 3: self._log.error("Move derived {} axes to transform from {}" .format(len(to_transform), target_position)) raise ValueError("Moves must specify either exactly an x, y, and " "(z or a) or none of them") # Type ignored below because linal.apply_transform (rightly) specifies # Tuple[float, float, float] and the implied type from # target_position.items() is (rightly) Tuple[float, ...] with unbounded # size; unfortunately, mypy can’t quite figure out the length check # above that makes this OK transformed = linal.apply_transform( # type: ignore self.config.gantry_calibration, to_transform) # Since target_position is an OrderedDict with the axes ordered by # (x, y, z, a, b, c), and we’ll only have one of a or z (as checked # by the len(to_transform) check above) we can use an enumerate to # fuse the specified axes and the transformed values back together. # While we do this iteration, we’ll also check axis bounds. bounds = self._backend.axis_bounds for idx, ax in enumerate(target_position.keys()): if ax in Axis.gantry_axes(): smoothie_pos[ax.name] = transformed[idx] if smoothie_pos[ax.name] < bounds[ax.name][0]\ or smoothie_pos[ax.name] > bounds[ax.name][1]: deck_mins = self._deck_from_smoothie({ax: bound[0] for ax, bound in bounds.items()}) deck_max = self._deck_from_smoothie({ax: bound[1] for ax, bound in bounds.items()}) self._log.warning( "Out of bounds move: {}={} (transformed: {}) not in" "limits ({}, {}) (transformed: ({}, {})" .format(ax.name, target_position[ax], smoothie_pos[ax.name], deck_mins[ax], deck_max[ax], bounds[ax.name][0], bounds[ax.name][1])) async with self._motion_lock: try: self._backend.move(smoothie_pos, speed=speed, home_flagged_axes=home_flagged_axes) except Exception: self._log.exception('Move failed') self._current_position.clear() raise else: self._current_position.update(target_position)
[ "async", "def", "_move", "(", "self", ",", "target_position", ":", "'OrderedDict[Axis, float]'", ",", "speed", ":", "float", "=", "None", ",", "home_flagged_axes", ":", "bool", "=", "True", ")", ":", "# Transform only the x, y, and (z or a) axes specified since this cou...
Worker function to apply robot motion. Robot motion means the kind of motions that are relevant to the robot, i.e. only one pipette plunger and mount move at the same time, and an XYZ move in the coordinate frame of one of the pipettes. ``target_position`` should be an ordered dict (ordered by XYZABC) of deck calibrated values, containing any specified XY motion and at most one of a ZA or BC components. The frame in which to move is identified by the presence of (ZA) or (BC).
[ "Worker", "function", "to", "apply", "robot", "motion", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L645-L719
train
198,044
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.engaged_axes
def engaged_axes(self) -> Dict[Axis, bool]: """ Which axes are engaged and holding. """ return {Axis[ax]: eng for ax, eng in self._backend.engaged_axes().items()}
python
def engaged_axes(self) -> Dict[Axis, bool]: """ Which axes are engaged and holding. """ return {Axis[ax]: eng for ax, eng in self._backend.engaged_axes().items()}
[ "def", "engaged_axes", "(", "self", ")", "->", "Dict", "[", "Axis", ",", "bool", "]", ":", "return", "{", "Axis", "[", "ax", "]", ":", "eng", "for", "ax", ",", "eng", "in", "self", ".", "_backend", ".", "engaged_axes", "(", ")", ".", "items", "("...
Which axes are engaged and holding.
[ "Which", "axes", "are", "engaged", "and", "holding", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L722-L725
train
198,045
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.retract
async def retract(self, mount: top_types.Mount, margin: float): """ Pull the specified mount up to its home position. Works regardless of critical point or home status. """ smoothie_ax = Axis.by_mount(mount).name.upper() async with self._motion_lock: smoothie_pos = self._backend.fast_home(smoothie_ax, margin) self._current_position = self._deck_from_smoothie(smoothie_pos)
python
async def retract(self, mount: top_types.Mount, margin: float): """ Pull the specified mount up to its home position. Works regardless of critical point or home status. """ smoothie_ax = Axis.by_mount(mount).name.upper() async with self._motion_lock: smoothie_pos = self._backend.fast_home(smoothie_ax, margin) self._current_position = self._deck_from_smoothie(smoothie_pos)
[ "async", "def", "retract", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ",", "margin", ":", "float", ")", ":", "smoothie_ax", "=", "Axis", ".", "by_mount", "(", "mount", ")", ".", "name", ".", "upper", "(", ")", "async", "with", "self",...
Pull the specified mount up to its home position. Works regardless of critical point or home status.
[ "Pull", "the", "specified", "mount", "up", "to", "its", "home", "position", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L731-L739
train
198,046
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API._critical_point_for
def _critical_point_for( self, mount: top_types.Mount, cp_override: CriticalPoint = None) -> top_types.Point: """ Return the current critical point of the specified mount. The mount's critical point is the position of the mount itself, if no pipette is attached, or the pipette's critical point (which depends on tip status). If `cp_override` is specified, and that critical point actually exists, it will be used instead. Invalid `cp_override`s are ignored. """ pip = self._attached_instruments[mount] if pip is not None and cp_override != CriticalPoint.MOUNT: return pip.critical_point(cp_override) else: # TODO: The smoothie’s z/a home position is calculated to provide # the offset for a P300 single. Here we should decide whether we # implicitly accept this as correct (by returning a null offset) # or not (by returning an offset calculated to move back up the # length of the P300 single). return top_types.Point(0, 0, 0)
python
def _critical_point_for( self, mount: top_types.Mount, cp_override: CriticalPoint = None) -> top_types.Point: """ Return the current critical point of the specified mount. The mount's critical point is the position of the mount itself, if no pipette is attached, or the pipette's critical point (which depends on tip status). If `cp_override` is specified, and that critical point actually exists, it will be used instead. Invalid `cp_override`s are ignored. """ pip = self._attached_instruments[mount] if pip is not None and cp_override != CriticalPoint.MOUNT: return pip.critical_point(cp_override) else: # TODO: The smoothie’s z/a home position is calculated to provide # the offset for a P300 single. Here we should decide whether we # implicitly accept this as correct (by returning a null offset) # or not (by returning an offset calculated to move back up the # length of the P300 single). return top_types.Point(0, 0, 0)
[ "def", "_critical_point_for", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ",", "cp_override", ":", "CriticalPoint", "=", "None", ")", "->", "top_types", ".", "Point", ":", "pip", "=", "self", ".", "_attached_instruments", "[", "mount", "]", ...
Return the current critical point of the specified mount. The mount's critical point is the position of the mount itself, if no pipette is attached, or the pipette's critical point (which depends on tip status). If `cp_override` is specified, and that critical point actually exists, it will be used instead. Invalid `cp_override`s are ignored.
[ "Return", "the", "current", "critical", "point", "of", "the", "specified", "mount", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L741-L762
train
198,047
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.blow_out
async def blow_out(self, mount): """ Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette """ this_pipette = self._attached_instruments[mount] if not this_pipette: raise top_types.PipetteNotAttachedError( "No pipette attached to {} mount".format(mount.name)) self._backend.set_active_current(Axis.of_plunger(mount), this_pipette.config.plunger_current) try: await self._move_plunger( mount, this_pipette.config.blow_out) except Exception: self._log.exception('Blow out failed') raise finally: this_pipette.set_current_volume(0)
python
async def blow_out(self, mount): """ Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette """ this_pipette = self._attached_instruments[mount] if not this_pipette: raise top_types.PipetteNotAttachedError( "No pipette attached to {} mount".format(mount.name)) self._backend.set_active_current(Axis.of_plunger(mount), this_pipette.config.plunger_current) try: await self._move_plunger( mount, this_pipette.config.blow_out) except Exception: self._log.exception('Blow out failed') raise finally: this_pipette.set_current_volume(0)
[ "async", "def", "blow_out", "(", "self", ",", "mount", ")", ":", "this_pipette", "=", "self", ".", "_attached_instruments", "[", "mount", "]", "if", "not", "this_pipette", ":", "raise", "top_types", ".", "PipetteNotAttachedError", "(", "\"No pipette attached to {}...
Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette
[ "Force", "any", "remaining", "liquid", "to", "dispense", ".", "The", "liquid", "will", "be", "dispensed", "at", "the", "current", "location", "of", "pipette" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L898-L917
train
198,048
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.pick_up_tip
async def pick_up_tip(self, mount, tip_length: float, presses: int = None, increment: float = None): """ Pick up tip from current location. If ``presses`` or ``increment`` is not specified (or is ``None``), their value is taken from the pipette configuration """ instr = self._attached_instruments[mount] assert instr assert not instr.has_tip, 'Tip already attached' instr_ax = Axis.by_mount(mount) plunger_ax = Axis.of_plunger(mount) self._log.info('Picking up tip on {}'.format(instr.name)) # Initialize plunger to bottom position self._backend.set_active_current(plunger_ax, instr.config.plunger_current) await self._move_plunger( mount, instr.config.bottom) if not presses or presses < 0: checked_presses = instr.config.pick_up_presses else: checked_presses = presses if not increment or increment < 0: checked_increment = instr.config.pick_up_increment else: checked_increment = increment # Press the nozzle into the tip <presses> number of times, # moving further by <increment> mm after each press for i in range(checked_presses): # move nozzle down into the tip with self._backend.save_current(): self._backend.set_active_current(instr_ax, instr.config.pick_up_current) dist = -1.0 * instr.config.pick_up_distance\ + -1.0 * checked_increment * i target_pos = top_types.Point(0, 0, dist) await self.move_rel( mount, target_pos, instr.config.pick_up_speed) # move nozzle back up backup_pos = top_types.Point(0, 0, -dist) await self.move_rel(mount, backup_pos) instr.add_tip(tip_length=tip_length) instr.set_current_volume(0) # neighboring tips tend to get stuck in the space between # the volume chamber and the drop-tip sleeve on p1000. # This extra shake ensures those tips are removed if 'needs-pickup-shake' in instr.config.quirks: await self._shake_off_tips(mount) await self._shake_off_tips(mount) await self.retract(mount, instr.config.pick_up_distance)
python
async def pick_up_tip(self, mount, tip_length: float, presses: int = None, increment: float = None): """ Pick up tip from current location. If ``presses`` or ``increment`` is not specified (or is ``None``), their value is taken from the pipette configuration """ instr = self._attached_instruments[mount] assert instr assert not instr.has_tip, 'Tip already attached' instr_ax = Axis.by_mount(mount) plunger_ax = Axis.of_plunger(mount) self._log.info('Picking up tip on {}'.format(instr.name)) # Initialize plunger to bottom position self._backend.set_active_current(plunger_ax, instr.config.plunger_current) await self._move_plunger( mount, instr.config.bottom) if not presses or presses < 0: checked_presses = instr.config.pick_up_presses else: checked_presses = presses if not increment or increment < 0: checked_increment = instr.config.pick_up_increment else: checked_increment = increment # Press the nozzle into the tip <presses> number of times, # moving further by <increment> mm after each press for i in range(checked_presses): # move nozzle down into the tip with self._backend.save_current(): self._backend.set_active_current(instr_ax, instr.config.pick_up_current) dist = -1.0 * instr.config.pick_up_distance\ + -1.0 * checked_increment * i target_pos = top_types.Point(0, 0, dist) await self.move_rel( mount, target_pos, instr.config.pick_up_speed) # move nozzle back up backup_pos = top_types.Point(0, 0, -dist) await self.move_rel(mount, backup_pos) instr.add_tip(tip_length=tip_length) instr.set_current_volume(0) # neighboring tips tend to get stuck in the space between # the volume chamber and the drop-tip sleeve on p1000. # This extra shake ensures those tips are removed if 'needs-pickup-shake' in instr.config.quirks: await self._shake_off_tips(mount) await self._shake_off_tips(mount) await self.retract(mount, instr.config.pick_up_distance)
[ "async", "def", "pick_up_tip", "(", "self", ",", "mount", ",", "tip_length", ":", "float", ",", "presses", ":", "int", "=", "None", ",", "increment", ":", "float", "=", "None", ")", ":", "instr", "=", "self", ".", "_attached_instruments", "[", "mount", ...
Pick up tip from current location. If ``presses`` or ``increment`` is not specified (or is ``None``), their value is taken from the pipette configuration
[ "Pick", "up", "tip", "from", "current", "location", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L920-L978
train
198,049
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.drop_tip
async def drop_tip(self, mount, home_after=True): """ Drop tip at the current location :param Mount mount: The mount to drop a tip from :param bool home_after: Home the plunger motor after dropping tip. This is used in case the plunger motor skipped while dropping the tip, and is also used to recover the ejector shroud after a drop. """ instr = self._attached_instruments[mount] assert instr assert instr.has_tip, 'Cannot drop tip without a tip attached' self._log.info("Dropping tip off from {}".format(instr.name)) plunger_ax = Axis.of_plunger(mount) droptip = instr.config.drop_tip bottom = instr.config.bottom self._backend.set_active_current(plunger_ax, instr.config.plunger_current) await self._move_plunger(mount, bottom) self._backend.set_active_current(plunger_ax, instr.config.drop_tip_current) await self._move_plunger( mount, droptip, speed=instr.config.drop_tip_speed) await self._shake_off_tips(mount) self._backend.set_active_current(plunger_ax, instr.config.plunger_current) instr.set_current_volume(0) instr.remove_tip() if home_after: safety_margin = abs(bottom-droptip) async with self._motion_lock: smoothie_pos = self._backend.fast_home( plunger_ax.name.upper(), safety_margin) self._current_position = self._deck_from_smoothie(smoothie_pos) await self._move_plunger(mount, safety_margin)
python
async def drop_tip(self, mount, home_after=True): """ Drop tip at the current location :param Mount mount: The mount to drop a tip from :param bool home_after: Home the plunger motor after dropping tip. This is used in case the plunger motor skipped while dropping the tip, and is also used to recover the ejector shroud after a drop. """ instr = self._attached_instruments[mount] assert instr assert instr.has_tip, 'Cannot drop tip without a tip attached' self._log.info("Dropping tip off from {}".format(instr.name)) plunger_ax = Axis.of_plunger(mount) droptip = instr.config.drop_tip bottom = instr.config.bottom self._backend.set_active_current(plunger_ax, instr.config.plunger_current) await self._move_plunger(mount, bottom) self._backend.set_active_current(plunger_ax, instr.config.drop_tip_current) await self._move_plunger( mount, droptip, speed=instr.config.drop_tip_speed) await self._shake_off_tips(mount) self._backend.set_active_current(plunger_ax, instr.config.plunger_current) instr.set_current_volume(0) instr.remove_tip() if home_after: safety_margin = abs(bottom-droptip) async with self._motion_lock: smoothie_pos = self._backend.fast_home( plunger_ax.name.upper(), safety_margin) self._current_position = self._deck_from_smoothie(smoothie_pos) await self._move_plunger(mount, safety_margin)
[ "async", "def", "drop_tip", "(", "self", ",", "mount", ",", "home_after", "=", "True", ")", ":", "instr", "=", "self", ".", "_attached_instruments", "[", "mount", "]", "assert", "instr", "assert", "instr", ".", "has_tip", ",", "'Cannot drop tip without a tip a...
Drop tip at the current location :param Mount mount: The mount to drop a tip from :param bool home_after: Home the plunger motor after dropping tip. This is used in case the plunger motor skipped while dropping the tip, and is also used to recover the ejector shroud after a drop.
[ "Drop", "tip", "at", "the", "current", "location" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L981-L1016
train
198,050
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.update_module
async def update_module( self, module: modules.AbstractModule, firmware_file: str, loop: asyncio.AbstractEventLoop = None) -> Tuple[bool, str]: """ Update a module's firmware. Returns (ok, message) where ok is True if the update succeeded and message is a human readable message. """ details = (module.port, module.name()) mod = self._attached_modules.pop(details[0] + details[1]) try: new_mod = await self._backend.update_module( mod, firmware_file, loop) except modules.UpdateError as e: return False, e.msg else: new_details = new_mod.port + new_mod.device_info['model'] self._attached_modules[new_details] = new_mod return True, 'firmware update successful'
python
async def update_module( self, module: modules.AbstractModule, firmware_file: str, loop: asyncio.AbstractEventLoop = None) -> Tuple[bool, str]: """ Update a module's firmware. Returns (ok, message) where ok is True if the update succeeded and message is a human readable message. """ details = (module.port, module.name()) mod = self._attached_modules.pop(details[0] + details[1]) try: new_mod = await self._backend.update_module( mod, firmware_file, loop) except modules.UpdateError as e: return False, e.msg else: new_details = new_mod.port + new_mod.device_info['model'] self._attached_modules[new_details] = new_mod return True, 'firmware update successful'
[ "async", "def", "update_module", "(", "self", ",", "module", ":", "modules", ".", "AbstractModule", ",", "firmware_file", ":", "str", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":...
Update a module's firmware. Returns (ok, message) where ok is True if the update succeeded and message is a human readable message.
[ "Update", "a", "module", "s", "firmware", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L1102-L1121
train
198,051
Opentrons/opentrons
api/src/opentrons/hardware_control/__init__.py
API.update_instrument_offset
def update_instrument_offset(self, mount, new_offset: top_types.Point = None, from_tip_probe: top_types.Point = None): """ Update the instrument offset for a pipette on the specified mount. This will update both the stored value in the robot settings and the live value in the currently-loaded pipette. This can be specified either directly by using the new_offset arg or using the result of a previous call to :py:meth:`locate_tip_probe_center` with the same mount. :note: Z differences in the instrument offset cannot be disambiguated between differences in the position of the nozzle and differences in the length of the nozzle/tip interface (assuming that tips are of reasonably uniform length). For this reason, they are saved as adjustments to the nozzle interface length and only applied when a tip is present. """ if from_tip_probe: new_offset = (top_types.Point(*self._config.tip_probe.center) - from_tip_probe) elif not new_offset: raise ValueError( "Either from_tip_probe or new_offset must be specified") opt_pip = self._attached_instruments[mount] assert opt_pip, '{} has no pipette'.format(mount.name.lower()) pip = opt_pip inst_offs = self._config.instrument_offset pip_type = 'multi' if pip.config.channels > 1 else 'single' inst_offs[mount.name.lower()][pip_type] = [new_offset.x, new_offset.y, new_offset.z] self.update_config(instrument_offset=inst_offs) pip.update_instrument_offset(new_offset) robot_configs.save_robot_settings(self._config)
python
def update_instrument_offset(self, mount, new_offset: top_types.Point = None, from_tip_probe: top_types.Point = None): """ Update the instrument offset for a pipette on the specified mount. This will update both the stored value in the robot settings and the live value in the currently-loaded pipette. This can be specified either directly by using the new_offset arg or using the result of a previous call to :py:meth:`locate_tip_probe_center` with the same mount. :note: Z differences in the instrument offset cannot be disambiguated between differences in the position of the nozzle and differences in the length of the nozzle/tip interface (assuming that tips are of reasonably uniform length). For this reason, they are saved as adjustments to the nozzle interface length and only applied when a tip is present. """ if from_tip_probe: new_offset = (top_types.Point(*self._config.tip_probe.center) - from_tip_probe) elif not new_offset: raise ValueError( "Either from_tip_probe or new_offset must be specified") opt_pip = self._attached_instruments[mount] assert opt_pip, '{} has no pipette'.format(mount.name.lower()) pip = opt_pip inst_offs = self._config.instrument_offset pip_type = 'multi' if pip.config.channels > 1 else 'single' inst_offs[mount.name.lower()][pip_type] = [new_offset.x, new_offset.y, new_offset.z] self.update_config(instrument_offset=inst_offs) pip.update_instrument_offset(new_offset) robot_configs.save_robot_settings(self._config)
[ "def", "update_instrument_offset", "(", "self", ",", "mount", ",", "new_offset", ":", "top_types", ".", "Point", "=", "None", ",", "from_tip_probe", ":", "top_types", ".", "Point", "=", "None", ")", ":", "if", "from_tip_probe", ":", "new_offset", "=", "(", ...
Update the instrument offset for a pipette on the specified mount. This will update both the stored value in the robot settings and the live value in the currently-loaded pipette. This can be specified either directly by using the new_offset arg or using the result of a previous call to :py:meth:`locate_tip_probe_center` with the same mount. :note: Z differences in the instrument offset cannot be disambiguated between differences in the position of the nozzle and differences in the length of the nozzle/tip interface (assuming that tips are of reasonably uniform length). For this reason, they are saved as adjustments to the nozzle interface length and only applied when a tip is present.
[ "Update", "the", "instrument", "offset", "for", "a", "pipette", "on", "the", "specified", "mount", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/__init__.py#L1259-L1295
train
198,052
Opentrons/opentrons
api/src/opentrons/config/pipette_config.py
load
def load(pipette_model: str, pipette_id: str = None) -> pipette_config: """ Load pipette config data This function loads from a combination of - the pipetteModelSpecs.json file in the wheel (should never be edited) - the pipetteNameSpecs.json file in the wheel(should never be edited) - any config overrides found in ``opentrons.config.CONFIG['pipette_config_overrides_dir']`` This function reads from disk each time, so changes to the overrides will be picked up in subsequent calls. :param str pipette_model: The pipette model name (i.e. "p10_single_v1.3") for which to load configuration :param pipette_id: An (optional) unique ID for the pipette to locate config overrides. If the ID is not specified, the system assumes this is a simulated pipette and does not save settings. If the ID is specified but no overrides corresponding to the ID are found, the system creates a new overrides file for it. :type pipette_id: str or None :raises KeyError: if ``pipette_model`` is not in the top-level keys of pipetteModeLSpecs.json (and therefore not in :py:attr:`configs`) :returns pipette_config: The configuration, loaded and checked """ # Load the model config and update with the name config cfg = copy.deepcopy(configs[pipette_model]) cfg.update(copy.deepcopy(name_config()[cfg['name']])) # Load overrides if we have a pipette id if pipette_id: try: override = load_overrides(pipette_id) except FileNotFoundError: save_overrides(pipette_id, {}, pipette_model) log.info( "Save defaults for pipette model {} and id {}".format( pipette_model, pipette_id)) else: cfg.update(override) # the ulPerMm functions are structured in pipetteModelSpecs.json as # a list sorted from oldest to newest. That means the latest functions # are always the last element and, as of right now, the older ones are # the first element (for models that only have one function, the first # and last elements are the same, which is fine). If we add more in the # future, we’ll have to change this code to select items more # intelligently if ff.use_old_aspiration_functions(): log.info("Using old aspiration functions") ul_per_mm = cfg['ulPerMm'][0] else: log.info("Using new aspiration functions") ul_per_mm = cfg['ulPerMm'][-1] res = pipette_config( top=ensure_value( cfg, 'top', mutable_configs), bottom=ensure_value( cfg, 'bottom', mutable_configs), blow_out=ensure_value( cfg, 'blowout', mutable_configs), drop_tip=ensure_value( cfg, 'dropTip', mutable_configs), pick_up_current=ensure_value(cfg, 'pickUpCurrent', mutable_configs), pick_up_distance=ensure_value(cfg, 'pickUpDistance', mutable_configs), pick_up_increment=ensure_value( cfg, 'pickUpIncrement', mutable_configs), pick_up_presses=ensure_value(cfg, 'pickUpPresses', mutable_configs), pick_up_speed=ensure_value(cfg, 'pickUpSpeed', mutable_configs), aspirate_flow_rate=ensure_value( cfg, 'defaultAspirateFlowRate', mutable_configs), dispense_flow_rate=ensure_value( cfg, 'defaultDispenseFlowRate', mutable_configs), channels=ensure_value(cfg, 'channels', mutable_configs), model_offset=ensure_value(cfg, 'modelOffset', mutable_configs), plunger_current=ensure_value(cfg, 'plungerCurrent', mutable_configs), drop_tip_current=ensure_value(cfg, 'dropTipCurrent', mutable_configs), drop_tip_speed=ensure_value(cfg, 'dropTipSpeed', mutable_configs), min_volume=ensure_value(cfg, 'minVolume', mutable_configs), max_volume=ensure_value(cfg, 'maxVolume', mutable_configs), ul_per_mm=ul_per_mm, quirks=ensure_value(cfg, 'quirks', mutable_configs), tip_length=ensure_value(cfg, 'tipLength', mutable_configs), display_name=ensure_value(cfg, 'displayName', mutable_configs) ) return res
python
def load(pipette_model: str, pipette_id: str = None) -> pipette_config: """ Load pipette config data This function loads from a combination of - the pipetteModelSpecs.json file in the wheel (should never be edited) - the pipetteNameSpecs.json file in the wheel(should never be edited) - any config overrides found in ``opentrons.config.CONFIG['pipette_config_overrides_dir']`` This function reads from disk each time, so changes to the overrides will be picked up in subsequent calls. :param str pipette_model: The pipette model name (i.e. "p10_single_v1.3") for which to load configuration :param pipette_id: An (optional) unique ID for the pipette to locate config overrides. If the ID is not specified, the system assumes this is a simulated pipette and does not save settings. If the ID is specified but no overrides corresponding to the ID are found, the system creates a new overrides file for it. :type pipette_id: str or None :raises KeyError: if ``pipette_model`` is not in the top-level keys of pipetteModeLSpecs.json (and therefore not in :py:attr:`configs`) :returns pipette_config: The configuration, loaded and checked """ # Load the model config and update with the name config cfg = copy.deepcopy(configs[pipette_model]) cfg.update(copy.deepcopy(name_config()[cfg['name']])) # Load overrides if we have a pipette id if pipette_id: try: override = load_overrides(pipette_id) except FileNotFoundError: save_overrides(pipette_id, {}, pipette_model) log.info( "Save defaults for pipette model {} and id {}".format( pipette_model, pipette_id)) else: cfg.update(override) # the ulPerMm functions are structured in pipetteModelSpecs.json as # a list sorted from oldest to newest. That means the latest functions # are always the last element and, as of right now, the older ones are # the first element (for models that only have one function, the first # and last elements are the same, which is fine). If we add more in the # future, we’ll have to change this code to select items more # intelligently if ff.use_old_aspiration_functions(): log.info("Using old aspiration functions") ul_per_mm = cfg['ulPerMm'][0] else: log.info("Using new aspiration functions") ul_per_mm = cfg['ulPerMm'][-1] res = pipette_config( top=ensure_value( cfg, 'top', mutable_configs), bottom=ensure_value( cfg, 'bottom', mutable_configs), blow_out=ensure_value( cfg, 'blowout', mutable_configs), drop_tip=ensure_value( cfg, 'dropTip', mutable_configs), pick_up_current=ensure_value(cfg, 'pickUpCurrent', mutable_configs), pick_up_distance=ensure_value(cfg, 'pickUpDistance', mutable_configs), pick_up_increment=ensure_value( cfg, 'pickUpIncrement', mutable_configs), pick_up_presses=ensure_value(cfg, 'pickUpPresses', mutable_configs), pick_up_speed=ensure_value(cfg, 'pickUpSpeed', mutable_configs), aspirate_flow_rate=ensure_value( cfg, 'defaultAspirateFlowRate', mutable_configs), dispense_flow_rate=ensure_value( cfg, 'defaultDispenseFlowRate', mutable_configs), channels=ensure_value(cfg, 'channels', mutable_configs), model_offset=ensure_value(cfg, 'modelOffset', mutable_configs), plunger_current=ensure_value(cfg, 'plungerCurrent', mutable_configs), drop_tip_current=ensure_value(cfg, 'dropTipCurrent', mutable_configs), drop_tip_speed=ensure_value(cfg, 'dropTipSpeed', mutable_configs), min_volume=ensure_value(cfg, 'minVolume', mutable_configs), max_volume=ensure_value(cfg, 'maxVolume', mutable_configs), ul_per_mm=ul_per_mm, quirks=ensure_value(cfg, 'quirks', mutable_configs), tip_length=ensure_value(cfg, 'tipLength', mutable_configs), display_name=ensure_value(cfg, 'displayName', mutable_configs) ) return res
[ "def", "load", "(", "pipette_model", ":", "str", ",", "pipette_id", ":", "str", "=", "None", ")", "->", "pipette_config", ":", "# Load the model config and update with the name config", "cfg", "=", "copy", ".", "deepcopy", "(", "configs", "[", "pipette_model", "]"...
Load pipette config data This function loads from a combination of - the pipetteModelSpecs.json file in the wheel (should never be edited) - the pipetteNameSpecs.json file in the wheel(should never be edited) - any config overrides found in ``opentrons.config.CONFIG['pipette_config_overrides_dir']`` This function reads from disk each time, so changes to the overrides will be picked up in subsequent calls. :param str pipette_model: The pipette model name (i.e. "p10_single_v1.3") for which to load configuration :param pipette_id: An (optional) unique ID for the pipette to locate config overrides. If the ID is not specified, the system assumes this is a simulated pipette and does not save settings. If the ID is specified but no overrides corresponding to the ID are found, the system creates a new overrides file for it. :type pipette_id: str or None :raises KeyError: if ``pipette_model`` is not in the top-level keys of pipetteModeLSpecs.json (and therefore not in :py:attr:`configs`) :returns pipette_config: The configuration, loaded and checked
[ "Load", "pipette", "config", "data" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/pipette_config.py#L90-L182
train
198,053
Opentrons/opentrons
api/src/opentrons/config/pipette_config.py
known_pipettes
def known_pipettes() -> Sequence[str]: """ List pipette IDs for which we have known overrides """ return [fi.stem for fi in CONFIG['pipette_config_overrides_dir'].iterdir() if fi.is_file() and '.json' in fi.suffixes]
python
def known_pipettes() -> Sequence[str]: """ List pipette IDs for which we have known overrides """ return [fi.stem for fi in CONFIG['pipette_config_overrides_dir'].iterdir() if fi.is_file() and '.json' in fi.suffixes]
[ "def", "known_pipettes", "(", ")", "->", "Sequence", "[", "str", "]", ":", "return", "[", "fi", ".", "stem", "for", "fi", "in", "CONFIG", "[", "'pipette_config_overrides_dir'", "]", ".", "iterdir", "(", ")", "if", "fi", ".", "is_file", "(", ")", "and",...
List pipette IDs for which we have known overrides
[ "List", "pipette", "IDs", "for", "which", "we", "have", "known", "overrides" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/pipette_config.py#L264-L268
train
198,054
Opentrons/opentrons
api/src/opentrons/config/pipette_config.py
load_config_dict
def load_config_dict(pipette_id: str) -> Dict: """ Give updated config with overrides for a pipette. This will add the default value for a mutable config before returning the modified config value. """ override = load_overrides(pipette_id) model = override['model'] config = copy.deepcopy(model_config()['config'][model]) config.update(copy.deepcopy(name_config()[config['name']])) for top_level_key in config.keys(): add_default(config[top_level_key]) config.update(override) return config
python
def load_config_dict(pipette_id: str) -> Dict: """ Give updated config with overrides for a pipette. This will add the default value for a mutable config before returning the modified config value. """ override = load_overrides(pipette_id) model = override['model'] config = copy.deepcopy(model_config()['config'][model]) config.update(copy.deepcopy(name_config()[config['name']])) for top_level_key in config.keys(): add_default(config[top_level_key]) config.update(override) return config
[ "def", "load_config_dict", "(", "pipette_id", ":", "str", ")", "->", "Dict", ":", "override", "=", "load_overrides", "(", "pipette_id", ")", "model", "=", "override", "[", "'model'", "]", "config", "=", "copy", ".", "deepcopy", "(", "model_config", "(", ")...
Give updated config with overrides for a pipette. This will add the default value for a mutable config before returning the modified config value.
[ "Give", "updated", "config", "with", "overrides", "for", "a", "pipette", ".", "This", "will", "add", "the", "default", "value", "for", "a", "mutable", "config", "before", "returning", "the", "modified", "config", "value", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/pipette_config.py#L280-L295
train
198,055
Opentrons/opentrons
api/src/opentrons/config/pipette_config.py
list_mutable_configs
def list_mutable_configs(pipette_id: str) -> Dict[str, Any]: """ Returns dict of mutable configs only. """ cfg: Dict[str, Any] = {} if pipette_id in known_pipettes(): config = load_config_dict(pipette_id) else: log.info('Pipette id {} not found'.format(pipette_id)) return cfg for key in config: if key in mutable_configs: cfg[key] = config[key] return cfg
python
def list_mutable_configs(pipette_id: str) -> Dict[str, Any]: """ Returns dict of mutable configs only. """ cfg: Dict[str, Any] = {} if pipette_id in known_pipettes(): config = load_config_dict(pipette_id) else: log.info('Pipette id {} not found'.format(pipette_id)) return cfg for key in config: if key in mutable_configs: cfg[key] = config[key] return cfg
[ "def", "list_mutable_configs", "(", "pipette_id", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "cfg", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "if", "pipette_id", "in", "known_pipettes", "(", ")", ":", "config", ...
Returns dict of mutable configs only.
[ "Returns", "dict", "of", "mutable", "configs", "only", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/pipette_config.py#L298-L313
train
198,056
Opentrons/opentrons
api/src/opentrons/drivers/mag_deck/driver.py
MagDeck.probe_plate
def probe_plate(self) -> str: ''' Probes for the deck plate and calculates the plate distance from home. To be used for calibrating MagDeck ''' self.run_flag.wait() try: self._send_command(GCODES['PROBE_PLATE']) except (MagDeckError, SerialException, SerialNoResponse) as e: return str(e) return ''
python
def probe_plate(self) -> str: ''' Probes for the deck plate and calculates the plate distance from home. To be used for calibrating MagDeck ''' self.run_flag.wait() try: self._send_command(GCODES['PROBE_PLATE']) except (MagDeckError, SerialException, SerialNoResponse) as e: return str(e) return ''
[ "def", "probe_plate", "(", "self", ")", "->", "str", ":", "self", ".", "run_flag", ".", "wait", "(", ")", "try", ":", "self", ".", "_send_command", "(", "GCODES", "[", "'PROBE_PLATE'", "]", ")", "except", "(", "MagDeckError", ",", "SerialException", ",",...
Probes for the deck plate and calculates the plate distance from home. To be used for calibrating MagDeck
[ "Probes", "for", "the", "deck", "plate", "and", "calculates", "the", "plate", "distance", "from", "home", ".", "To", "be", "used", "for", "calibrating", "MagDeck" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/mag_deck/driver.py#L207-L219
train
198,057
Opentrons/opentrons
api/src/opentrons/drivers/mag_deck/driver.py
MagDeck.move
def move(self, position_mm) -> str: ''' Move the magnets along Z axis where the home position is 0.0; position_mm-> a point along Z. Does not self-check if the position is outside of the deck's linear range ''' self.run_flag.wait() try: position_mm = round(float(position_mm), GCODE_ROUNDING_PRECISION) self._send_command('{0} Z{1}'.format(GCODES['MOVE'], position_mm)) except (MagDeckError, SerialException, SerialNoResponse) as e: return str(e) return ''
python
def move(self, position_mm) -> str: ''' Move the magnets along Z axis where the home position is 0.0; position_mm-> a point along Z. Does not self-check if the position is outside of the deck's linear range ''' self.run_flag.wait() try: position_mm = round(float(position_mm), GCODE_ROUNDING_PRECISION) self._send_command('{0} Z{1}'.format(GCODES['MOVE'], position_mm)) except (MagDeckError, SerialException, SerialNoResponse) as e: return str(e) return ''
[ "def", "move", "(", "self", ",", "position_mm", ")", "->", "str", ":", "self", ".", "run_flag", ".", "wait", "(", ")", "try", ":", "position_mm", "=", "round", "(", "float", "(", "position_mm", ")", ",", "GCODE_ROUNDING_PRECISION", ")", "self", ".", "_...
Move the magnets along Z axis where the home position is 0.0; position_mm-> a point along Z. Does not self-check if the position is outside of the deck's linear range
[ "Move", "the", "magnets", "along", "Z", "axis", "where", "the", "home", "position", "is", "0", ".", "0", ";", "position_mm", "-", ">", "a", "point", "along", "Z", ".", "Does", "not", "self", "-", "check", "if", "the", "position", "is", "outside", "of...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/mag_deck/driver.py#L239-L252
train
198,058
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
save_calibration
def save_calibration(labware: Labware, delta: Point): """ Function to be used whenever an updated delta is found for the first well of a given labware. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the delta and the lastModified fields under the "default" key. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] if not calibration_path.exists(): calibration_path.mkdir(parents=True, exist_ok=True) labware_offset_path = calibration_path/'{}.json'.format(labware._id) calibration_data = _helper_offset_data_format( str(labware_offset_path), delta) with labware_offset_path.open('w') as f: json.dump(calibration_data, f) labware.set_calibration(delta)
python
def save_calibration(labware: Labware, delta: Point): """ Function to be used whenever an updated delta is found for the first well of a given labware. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the delta and the lastModified fields under the "default" key. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] if not calibration_path.exists(): calibration_path.mkdir(parents=True, exist_ok=True) labware_offset_path = calibration_path/'{}.json'.format(labware._id) calibration_data = _helper_offset_data_format( str(labware_offset_path), delta) with labware_offset_path.open('w') as f: json.dump(calibration_data, f) labware.set_calibration(delta)
[ "def", "save_calibration", "(", "labware", ":", "Labware", ",", "delta", ":", "Point", ")", ":", "calibration_path", "=", "CONFIG", "[", "'labware_calibration_offsets_dir_v4'", "]", "if", "not", "calibration_path", ".", "exists", "(", ")", ":", "calibration_path",...
Function to be used whenever an updated delta is found for the first well of a given labware. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the delta and the lastModified fields under the "default" key.
[ "Function", "to", "be", "used", "whenever", "an", "updated", "delta", "is", "found", "for", "the", "first", "well", "of", "a", "given", "labware", ".", "If", "an", "offset", "file", "does", "not", "exist", "create", "the", "file", "using", "labware", "id...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L649-L664
train
198,059
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
save_tip_length
def save_tip_length(labware: Labware, length: float): """ Function to be used whenever an updated tip length is found for of a given tip rack. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the length and the lastModified fields under the "tipLength" key. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] if not calibration_path.exists(): calibration_path.mkdir(parents=True, exist_ok=True) labware_offset_path = calibration_path/'{}.json'.format(labware._id) calibration_data = _helper_tip_length_data_format( str(labware_offset_path), length) with labware_offset_path.open('w') as f: json.dump(calibration_data, f) labware.tip_length = length
python
def save_tip_length(labware: Labware, length: float): """ Function to be used whenever an updated tip length is found for of a given tip rack. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the length and the lastModified fields under the "tipLength" key. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] if not calibration_path.exists(): calibration_path.mkdir(parents=True, exist_ok=True) labware_offset_path = calibration_path/'{}.json'.format(labware._id) calibration_data = _helper_tip_length_data_format( str(labware_offset_path), length) with labware_offset_path.open('w') as f: json.dump(calibration_data, f) labware.tip_length = length
[ "def", "save_tip_length", "(", "labware", ":", "Labware", ",", "length", ":", "float", ")", ":", "calibration_path", "=", "CONFIG", "[", "'labware_calibration_offsets_dir_v4'", "]", "if", "not", "calibration_path", ".", "exists", "(", ")", ":", "calibration_path",...
Function to be used whenever an updated tip length is found for of a given tip rack. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the length and the lastModified fields under the "tipLength" key.
[ "Function", "to", "be", "used", "whenever", "an", "updated", "tip", "length", "is", "found", "for", "of", "a", "given", "tip", "rack", ".", "If", "an", "offset", "file", "does", "not", "exist", "create", "the", "file", "using", "labware", "id", "as", "...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L667-L682
train
198,060
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
load_calibration
def load_calibration(labware: Labware): """ Look up a calibration if it exists and apply it to the given labware. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] labware_offset_path = calibration_path/'{}.json'.format(labware._id) if labware_offset_path.exists(): calibration_data = _read_file(str(labware_offset_path)) offset_array = calibration_data['default']['offset'] offset = Point(x=offset_array[0], y=offset_array[1], z=offset_array[2]) labware.set_calibration(offset) if 'tipLength' in calibration_data.keys(): tip_length = calibration_data['tipLength']['length'] labware.tip_length = tip_length
python
def load_calibration(labware: Labware): """ Look up a calibration if it exists and apply it to the given labware. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] labware_offset_path = calibration_path/'{}.json'.format(labware._id) if labware_offset_path.exists(): calibration_data = _read_file(str(labware_offset_path)) offset_array = calibration_data['default']['offset'] offset = Point(x=offset_array[0], y=offset_array[1], z=offset_array[2]) labware.set_calibration(offset) if 'tipLength' in calibration_data.keys(): tip_length = calibration_data['tipLength']['length'] labware.tip_length = tip_length
[ "def", "load_calibration", "(", "labware", ":", "Labware", ")", ":", "calibration_path", "=", "CONFIG", "[", "'labware_calibration_offsets_dir_v4'", "]", "labware_offset_path", "=", "calibration_path", "/", "'{}.json'", ".", "format", "(", "labware", ".", "_id", ")"...
Look up a calibration if it exists and apply it to the given labware.
[ "Look", "up", "a", "calibration", "if", "it", "exists", "and", "apply", "it", "to", "the", "given", "labware", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L685-L698
train
198,061
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
load_from_definition
def load_from_definition( definition: dict, parent: Location, label: str = None) -> Labware: """ Return a labware object constructed from a provided labware definition dict :param definition: A dict representing all required data for a labware, including metadata such as the display name of the labware, a definition of the order to iterate over wells, the shape of wells (shape, physical dimensions, etc), and so on. The correct shape of this definition is governed by the "labware-designer" project in the Opentrons/opentrons repo. :param parent: A :py:class:`.Location` representing the location where the front and left most point of the outside of labware is (often the front-left corner of a slot on the deck). :param str label: An optional label that will override the labware's display name from its definition """ labware = Labware(definition, parent, label) load_calibration(labware) return labware
python
def load_from_definition( definition: dict, parent: Location, label: str = None) -> Labware: """ Return a labware object constructed from a provided labware definition dict :param definition: A dict representing all required data for a labware, including metadata such as the display name of the labware, a definition of the order to iterate over wells, the shape of wells (shape, physical dimensions, etc), and so on. The correct shape of this definition is governed by the "labware-designer" project in the Opentrons/opentrons repo. :param parent: A :py:class:`.Location` representing the location where the front and left most point of the outside of labware is (often the front-left corner of a slot on the deck). :param str label: An optional label that will override the labware's display name from its definition """ labware = Labware(definition, parent, label) load_calibration(labware) return labware
[ "def", "load_from_definition", "(", "definition", ":", "dict", ",", "parent", ":", "Location", ",", "label", ":", "str", "=", "None", ")", "->", "Labware", ":", "labware", "=", "Labware", "(", "definition", ",", "parent", ",", "label", ")", "load_calibrati...
Return a labware object constructed from a provided labware definition dict :param definition: A dict representing all required data for a labware, including metadata such as the display name of the labware, a definition of the order to iterate over wells, the shape of wells (shape, physical dimensions, etc), and so on. The correct shape of this definition is governed by the "labware-designer" project in the Opentrons/opentrons repo. :param parent: A :py:class:`.Location` representing the location where the front and left most point of the outside of labware is (often the front-left corner of a slot on the deck). :param str label: An optional label that will override the labware's display name from its definition
[ "Return", "a", "labware", "object", "constructed", "from", "a", "provided", "labware", "definition", "dict" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L771-L790
train
198,062
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
clear_calibrations
def clear_calibrations(): """ Delete all calibration files for labware. This includes deleting tip-length data for tipracks. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] try: targets = [ f for f in calibration_path.iterdir() if f.suffix == '.json'] for target in targets: target.unlink() except FileNotFoundError: pass
python
def clear_calibrations(): """ Delete all calibration files for labware. This includes deleting tip-length data for tipracks. """ calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] try: targets = [ f for f in calibration_path.iterdir() if f.suffix == '.json'] for target in targets: target.unlink() except FileNotFoundError: pass
[ "def", "clear_calibrations", "(", ")", ":", "calibration_path", "=", "CONFIG", "[", "'labware_calibration_offsets_dir_v4'", "]", "try", ":", "targets", "=", "[", "f", "for", "f", "in", "calibration_path", ".", "iterdir", "(", ")", "if", "f", ".", "suffix", "...
Delete all calibration files for labware. This includes deleting tip-length data for tipracks.
[ "Delete", "all", "calibration", "files", "for", "labware", ".", "This", "includes", "deleting", "tip", "-", "length", "data", "for", "tipracks", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L793-L805
train
198,063
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
quirks_from_any_parent
def quirks_from_any_parent( loc: Union[Labware, Well, str, ModuleGeometry, None]) -> List[str]: """ Walk the tree of wells and labwares and extract quirks """ def recursive_get_quirks(obj, found): if isinstance(obj, Labware): return found + obj.quirks elif isinstance(obj, Well): return recursive_get_quirks(obj.parent, found) else: return found return recursive_get_quirks(loc, [])
python
def quirks_from_any_parent( loc: Union[Labware, Well, str, ModuleGeometry, None]) -> List[str]: """ Walk the tree of wells and labwares and extract quirks """ def recursive_get_quirks(obj, found): if isinstance(obj, Labware): return found + obj.quirks elif isinstance(obj, Well): return recursive_get_quirks(obj.parent, found) else: return found return recursive_get_quirks(loc, [])
[ "def", "quirks_from_any_parent", "(", "loc", ":", "Union", "[", "Labware", ",", "Well", ",", "str", ",", "ModuleGeometry", ",", "None", "]", ")", "->", "List", "[", "str", "]", ":", "def", "recursive_get_quirks", "(", "obj", ",", "found", ")", ":", "if...
Walk the tree of wells and labwares and extract quirks
[ "Walk", "the", "tree", "of", "wells", "and", "labwares", "and", "extract", "quirks" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L847-L857
train
198,064
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware._build_wells
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. """ 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]
python
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. """ 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", "]", ":", "return", "[", "Well", "(", "self", ".", "_well_definition", "[", "well", "]", ",", "Location", "(", "self", ".", "_calibrated_offset", ",", "self", ")", ",", "\"{} of {}\"", ...
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.
[ "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", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L253-L265
train
198,065
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware._create_indexed_dictionary
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 collect wells that have the same numeric postfix and therefore are considered to be in the same column. """ 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
python
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 collect wells that have the same numeric postfix and therefore are considered to be in the same column. """ 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", ")", ":", "dict_list", "=", "defaultdict", "(", "list", ")", "for", "index", ",", "well_obj", "in", "zip", "(", "self", ".", "_ordering", ",", "self", ".", "_wells", ")", ":", "d...
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 collect wells that have the same numeric postfix and therefore are considered to be in the same column.
[ "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"...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L267-L279
train
198,066
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.set_calibration
def set_calibration(self, delta: Point): """ Called by save calibration in order to update the offset on the object. """ 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()
python
def set_calibration(self, delta: Point): """ Called by save calibration in order to update the offset on the object. """ 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", ")", ":", "self", ".", "_calibrated_offset", "=", "Point", "(", "x", "=", "self", ".", "_offset", ".", "x", "+", "delta", ".", "x", ",", "y", "=", "self", ".", "_offset", ".", "y", ...
Called by save calibration in order to update the offset on the object.
[ "Called", "by", "save", "calibration", "in", "order", "to", "update", "the", "offset", "on", "the", "object", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L281-L288
train
198,067
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.wells_by_index
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 name """ return {well: wellObj for well, wellObj in zip(self._ordering, self._wells)}
python
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 name """ return {well: wellObj for well, wellObj in zip(self._ordering, self._wells)}
[ "def", "wells_by_index", "(", "self", ")", "->", "Dict", "[", "str", ",", "Well", "]", ":", "return", "{", "well", ":", "wellObj", "for", "well", ",", "wellObj", "in", "zip", "(", "self", ".", "_ordering", ",", "self", ".", "_wells", ")", "}" ]
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 name
[ "Accessor", "function", "used", "to", "create", "a", "look", "-", "up", "table", "of", "Wells", "by", "name", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L331-L342
train
198,068
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.rows
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-compatibility, but use of args is deprecated and will be removed in future versions. Args can be either strings or integers, but must all be the same type (e.g.: `self.rows(1, 4, 8)` or `self.rows('A', 'B')`, but `self.rows('A', 4)` is invalid. :return: A list of row lists """ 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): res = [row_dict[idx] for idx in args] else: raise TypeError return res
python
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-compatibility, but use of args is deprecated and will be removed in future versions. Args can be either strings or integers, but must all be the same type (e.g.: `self.rows(1, 4, 8)` or `self.rows('A', 'B')`, but `self.rows('A', 4)` is invalid. :return: A list of row lists """ 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): res = [row_dict[idx] for idx in args] else: raise TypeError return res
[ "def", "rows", "(", "self", ",", "*", "args", ")", "->", "List", "[", "List", "[", "Well", "]", "]", ":", "row_dict", "=", "self", ".", "_create_indexed_dictionary", "(", "group", "=", "1", ")", "keys", "=", "sorted", "(", "row_dict", ")", "if", "n...
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-compatibility, but use of args is deprecated and will be removed in future versions. Args can be either strings or integers, but must all be the same type (e.g.: `self.rows(1, 4, 8)` or `self.rows('A', 'B')`, but `self.rows('A', 4)` is invalid. :return: A list of row lists
[ "Accessor", "function", "used", "to", "navigate", "through", "a", "labware", "by", "row", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L344-L371
train
198,069
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.rows_by_index
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 by row name """ row_dict = self._create_indexed_dictionary(group=1) return row_dict
python
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 by row name """ row_dict = self._create_indexed_dictionary(group=1) return row_dict
[ "def", "rows_by_index", "(", "self", ")", "->", "Dict", "[", "str", ",", "List", "[", "Well", "]", "]", ":", "row_dict", "=", "self", ".", "_create_indexed_dictionary", "(", "group", "=", "1", ")", "return", "row_dict" ]
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 by row name
[ "Accessor", "function", "used", "to", "navigate", "through", "a", "labware", "by", "row", "name", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L373-L384
train
198,070
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.columns
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 backward-compatibility, but use of args is deprecated and will be removed in future versions. Args can be either strings or integers, but must all be the same type (e.g.: `self.columns(1, 4, 8)` or `self.columns('1', '2')`, but `self.columns('1', 4)` is invalid. :return: A list of column lists """ 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], str): res = [col_dict[idx] for idx in args] else: raise TypeError return res
python
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 backward-compatibility, but use of args is deprecated and will be removed in future versions. Args can be either strings or integers, but must all be the same type (e.g.: `self.columns(1, 4, 8)` or `self.columns('1', '2')`, but `self.columns('1', 4)` is invalid. :return: A list of column lists """ 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], str): res = [col_dict[idx] for idx in args] else: raise TypeError return res
[ "def", "columns", "(", "self", ",", "*", "args", ")", "->", "List", "[", "List", "[", "Well", "]", "]", ":", "col_dict", "=", "self", ".", "_create_indexed_dictionary", "(", "group", "=", "2", ")", "keys", "=", "sorted", "(", "col_dict", ",", "key", ...
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 backward-compatibility, but use of args is deprecated and will be removed in future versions. Args can be either strings or integers, but must all be the same type (e.g.: `self.columns(1, 4, 8)` or `self.columns('1', '2')`, but `self.columns('1', 4)` is invalid. :return: A list of column lists
[ "Accessor", "function", "used", "to", "navigate", "through", "a", "labware", "by", "column", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L386-L414
train
198,071
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.columns_by_index
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 Well lists keyed by column name """ col_dict = self._create_indexed_dictionary(group=2) return col_dict
python
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 Well lists keyed by column name """ col_dict = self._create_indexed_dictionary(group=2) return col_dict
[ "def", "columns_by_index", "(", "self", ")", "->", "Dict", "[", "str", ",", "List", "[", "Well", "]", "]", ":", "col_dict", "=", "self", ".", "_create_indexed_dictionary", "(", "group", "=", "2", ")", "return", "col_dict" ]
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 Well lists keyed by column name
[ "Accessor", "function", "used", "to", "navigate", "through", "a", "labware", "by", "column", "name", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L416-L428
train
198,072
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.next_tip
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 same column :type num_tips: int :return: the :py:class:`.Well` meeting the target criteria, or None """ 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 column in drop_leading_empties] long_enough = [ column for column in drop_at_first_gap if len(column) >= num_tips] try: first_long_enough = long_enough[0] result: Optional[Well] = first_long_enough[0] except IndexError: result = None return result
python
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 same column :type num_tips: int :return: the :py:class:`.Well` meeting the target criteria, or None """ 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 column in drop_leading_empties] long_enough = [ column for column in drop_at_first_gap if len(column) >= num_tips] try: first_long_enough = long_enough[0] result: Optional[Well] = first_long_enough[0] except IndexError: result = None return result
[ "def", "next_tip", "(", "self", ",", "num_tips", ":", "int", "=", "1", ")", "->", "Optional", "[", "Well", "]", ":", "assert", "num_tips", ">", "0", "columns", ":", "List", "[", "List", "[", "Well", "]", "]", "=", "self", ".", "columns", "(", ")"...
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 same column :type num_tips: int :return: the :py:class:`.Well` meeting the target criteria, or None
[ "Find", "the", "next", "valid", "well", "for", "pick", "-", "up", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L452-L482
train
198,073
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
Labware.use_tips
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 which tips are used based on the start well, the number of channels, and the geometry of the tiprack. :param start_well: The :py:class:`.Well` from which to pick up a tip. For a single-channel pipette, this is the well to send the pipette to. For a multi-channel pipette, this is the well to send the back-most nozzle of the pipette to. :type start_well: :py:class:`.Well` :param num_channels: The number of channels for the current pipette :type num_channels: int """ 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) # Number of tips to pick up is the lesser of (1) the number of tips # from the starting well to the end of the column, and (2) the number # of channels of the pipette (so a 4-channel pipette would pick up a # max of 4 tips, and picking up from the 2nd-to-bottom well in a # column would get a maximum of 2 tips) num_tips = min(len(target_column) - well_idx, num_channels) target_wells = target_column[well_idx: well_idx + num_tips] assert all([well.has_tip for well in target_wells]),\ '{} is out of tips'.format(str(self)) for well in target_wells: well.has_tip = False
python
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 which tips are used based on the start well, the number of channels, and the geometry of the tiprack. :param start_well: The :py:class:`.Well` from which to pick up a tip. For a single-channel pipette, this is the well to send the pipette to. For a multi-channel pipette, this is the well to send the back-most nozzle of the pipette to. :type start_well: :py:class:`.Well` :param num_channels: The number of channels for the current pipette :type num_channels: int """ 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) # Number of tips to pick up is the lesser of (1) the number of tips # from the starting well to the end of the column, and (2) the number # of channels of the pipette (so a 4-channel pipette would pick up a # max of 4 tips, and picking up from the 2nd-to-bottom well in a # column would get a maximum of 2 tips) num_tips = min(len(target_column) - well_idx, num_channels) target_wells = target_column[well_idx: well_idx + num_tips] assert all([well.has_tip for well in target_wells]),\ '{} is out of tips'.format(str(self)) for well in target_wells: well.has_tip = False
[ "def", "use_tips", "(", "self", ",", "start_well", ":", "Well", ",", "num_channels", ":", "int", "=", "1", ")", ":", "assert", "num_channels", ">", "0", ",", "'Bad call to use_tips: num_channels==0'", "# Select the column of the labware that contains the target well", "...
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 which tips are used based on the start well, the number of channels, and the geometry of the tiprack. :param start_well: The :py:class:`.Well` from which to pick up a tip. For a single-channel pipette, this is the well to send the pipette to. For a multi-channel pipette, this is the well to send the back-most nozzle of the pipette to. :type start_well: :py:class:`.Well` :param num_channels: The number of channels for the current pipette :type num_channels: int
[ "Removes", "tips", "from", "the", "tip", "tracker", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L484-L522
train
198,074
Opentrons/opentrons
update-server/otupdate/buildroot/ssh_key_management.py
require_linklocal
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) """ @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 connections' } if not ipaddr_str: return web.json_response( data=invalid_req_data, status=403) try: addr = ipaddress.ip_address(ipaddr_str) except ValueError: LOG.exception(f"Couldn't parse host ip address {ipaddr_str}") raise if not addr.is_link_local: return web.json_response(data=invalid_req_data, status=403) return await handler(request) return decorated
python
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) """ @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 connections' } if not ipaddr_str: return web.json_response( data=invalid_req_data, status=403) try: addr = ipaddress.ip_address(ipaddr_str) except ValueError: LOG.exception(f"Couldn't parse host ip address {ipaddr_str}") raise if not addr.is_link_local: return web.json_response(data=invalid_req_data, status=403) return await handler(request) return decorated
[ "def", "require_linklocal", "(", "handler", ")", ":", "@", "functools", ".", "wraps", "(", "handler", ")", "async", "def", "decorated", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "ipaddr_str", "=", "request", ".",...
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)
[ "Ensure", "the", "decorated", "is", "only", "called", "if", "the", "request", "is", "linklocal", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/ssh_key_management.py#L18-L45
train
198,075
Opentrons/opentrons
update-server/otupdate/buildroot/ssh_key_management.py
authorized_keys
def authorized_keys(mode='r'): """ Open the authorized_keys file. Separate function for mocking. :param mode: As :py:meth:`open` """ 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
python
def authorized_keys(mode='r'): """ Open the authorized_keys file. Separate function for mocking. :param mode: As :py:meth:`open` """ 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'", ")", ":", "path", "=", "'/var/home/.ssh/authorized_keys'", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "pat...
Open the authorized_keys file. Separate function for mocking. :param mode: As :py:meth:`open`
[ "Open", "the", "authorized_keys", "file", ".", "Separate", "function", "for", "mocking", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/ssh_key_management.py#L49-L59
train
198,076
Opentrons/opentrons
update-server/otupdate/buildroot/ssh_key_management.py
remove_by_hash
def remove_by_hash(hashval: str): """ Remove the key whose md5 sum matches hashval. :raises: KeyError if the hashval wasn't found """ 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)
python
def remove_by_hash(hashval: str): """ Remove the key whose md5 sum matches hashval. :raises: KeyError if the hashval wasn't found """ 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", ")", ":", "key_details", "=", "get_keys", "(", ")", "with", "authorized_keys", "(", "'w'", ")", "as", "ak", ":", "for", "keyhash", ",", "key", "in", "key_details", ":", "if", "keyhash", "!=", "hashval"...
Remove the key whose md5 sum matches hashval. :raises: KeyError if the hashval wasn't found
[ "Remove", "the", "key", "whose", "md5", "sum", "matches", "hashval", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/ssh_key_management.py#L71-L83
train
198,077
Opentrons/opentrons
update-server/otupdate/buildroot/ssh_key_management.py
list_keys
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) """ return web.json_response( {'public_keys': [{'key_md5': details[0], 'key': details[1]} for details in get_keys()]}, status=200)
python
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) """ 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", ":", "return", "web", ".", "json_response", "(", "{", "'public_keys'", ":", "[", "{", "'key_md5'", ":", "details", "[", "0", "]", ",", "'key'", ...
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)
[ "List", "keys", "in", "the", "authorized_keys", "file", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/ssh_key_management.py#L95-L106
train
198,078
Opentrons/opentrons
update-server/otupdate/buildroot/ssh_key_management.py
add
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 """ 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 invalid keys but # we still don’t want to have a bunch of invalid data in there alg = pubkey.split()[0] # We don’t allow dss so this has to be rsa or ecdsa and shouldn’t start # with restrictions if alg != 'ssh-rsa' and not alg.startswith('ecdsa'): LOG.warning(f"weird keyfile uploaded: starts with {alg}") return web.json_response( data={'error': 'bad-key', 'message': f'Key starts with invalid algorithm {alg}'}, status=400) if '\n' in pubkey[:-1]: LOG.warning(f"Newlines in keyfile that shouldn't be there") return web.json_response( data={'error': 'bad-key', 'message': f'Key has a newline'}, status=400) if '\n' == pubkey[-1]: pubkey = pubkey[:-1] # This is a more or less correct key we can write hashval = hashlib.new('md5', pubkey.encode()).hexdigest() if not key_present(hashval): with authorized_keys('a') as ak: ak.write(f'{pubkey}\n') return web.json_response( data={'message': 'Added key {hashval}', 'key_md5': hashval}, status=201)
python
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 """ 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 invalid keys but # we still don’t want to have a bunch of invalid data in there alg = pubkey.split()[0] # We don’t allow dss so this has to be rsa or ecdsa and shouldn’t start # with restrictions if alg != 'ssh-rsa' and not alg.startswith('ecdsa'): LOG.warning(f"weird keyfile uploaded: starts with {alg}") return web.json_response( data={'error': 'bad-key', 'message': f'Key starts with invalid algorithm {alg}'}, status=400) if '\n' in pubkey[:-1]: LOG.warning(f"Newlines in keyfile that shouldn't be there") return web.json_response( data={'error': 'bad-key', 'message': f'Key has a newline'}, status=400) if '\n' == pubkey[-1]: pubkey = pubkey[:-1] # This is a more or less correct key we can write hashval = hashlib.new('md5', pubkey.encode()).hexdigest() if not key_present(hashval): with authorized_keys('a') as ak: ak.write(f'{pubkey}\n') return web.json_response( data={'message': 'Added key {hashval}', 'key_md5': hashval}, status=201)
[ "async", "def", "add", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "body", "=", "await", "request", ".", "json", "(", ")", "if", "'key'", "not", "in", "body", "or", "not", "isinstance", "(", "body", "[", "'ke...
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
[ "Add", "a", "public", "key", "to", "the", "authorized_keys", "file", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/ssh_key_management.py#L110-L153
train
198,079
Opentrons/opentrons
update-server/otupdate/buildroot/ssh_key_management.py
remove
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 """ 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={'error': 'invalid-key-hash', 'message': f'No such key md5 {requested_hash}'}, status=404) with authorized_keys('w') as ak: ak.write('\n'.join(new_keys) + '\n') return web.json_response( data={ 'message': f'Key {requested_hash} deleted. ' 'Restart robot to take effect', 'restart_url': '/server/restart'}, status=200)
python
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 """ 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={'error': 'invalid-key-hash', 'message': f'No such key md5 {requested_hash}'}, status=404) with authorized_keys('w') as ak: ak.write('\n'.join(new_keys) + '\n') return web.json_response( data={ 'message': f'Key {requested_hash} deleted. ' 'Restart robot to take effect', 'restart_url': '/server/restart'}, status=200)
[ "async", "def", "remove", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "requested_hash", "=", "request", ".", "match_info", "[", "'key_md5'", "]", "new_keys", ":", "List", "[", "str", "]", "=", "[", "]", "found", ...
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
[ "Remove", "a", "public", "key", "from", "authorized_keys" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/ssh_key_management.py#L157-L187
train
198,080
Opentrons/opentrons
api/src/opentrons/main.py
log_init
def log_init(): """ Function that sets log levels and format strings. Checks for the OT_API_LOG_LEVEL environment variable otherwise defaults to DEBUG. """ 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._nameToLevel[ot_log_level] serial_log_filename = CONFIG['serial_log_file'] api_log_filename = CONFIG['api_log_file'] logging_config = dict( version=1, formatters={ 'basic': { 'format': '%(asctime)s %(name)s %(levelname)s [Line %(lineno)s] %(message)s' # noqa: E501 } }, handlers={ 'debug': { 'class': 'logging.StreamHandler', 'formatter': 'basic', 'level': level_value }, 'serial': { 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'basic', 'filename': serial_log_filename, 'maxBytes': 5000000, 'level': logging.DEBUG, 'backupCount': 3 }, 'api': { 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'basic', 'filename': api_log_filename, 'maxBytes': 1000000, 'level': logging.DEBUG, 'backupCount': 5 } }, loggers={ '__main__': { 'handlers': ['debug', 'api'], 'level': logging.INFO }, 'opentrons.server': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.api': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.instruments': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.config': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.drivers.smoothie_drivers.driver_3_0': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.drivers.serial_communication': { 'handlers': ['serial'], 'level': logging.DEBUG }, 'opentrons.drivers.thermocycler.driver': { 'handlers': ['serial'], 'level': logging.DEBUG }, 'opentrons.protocol_api': { 'handlers': ['api', 'debug'], 'level': level_value }, 'opentrons.hardware_control': { 'handlers': ['api', 'debug'], 'level': level_value }, 'opentrons.legacy_api.containers': { 'handlers': ['api'], 'level': level_value } } ) dictConfig(logging_config)
python
def log_init(): """ Function that sets log levels and format strings. Checks for the OT_API_LOG_LEVEL environment variable otherwise defaults to DEBUG. """ 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._nameToLevel[ot_log_level] serial_log_filename = CONFIG['serial_log_file'] api_log_filename = CONFIG['api_log_file'] logging_config = dict( version=1, formatters={ 'basic': { 'format': '%(asctime)s %(name)s %(levelname)s [Line %(lineno)s] %(message)s' # noqa: E501 } }, handlers={ 'debug': { 'class': 'logging.StreamHandler', 'formatter': 'basic', 'level': level_value }, 'serial': { 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'basic', 'filename': serial_log_filename, 'maxBytes': 5000000, 'level': logging.DEBUG, 'backupCount': 3 }, 'api': { 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'basic', 'filename': api_log_filename, 'maxBytes': 1000000, 'level': logging.DEBUG, 'backupCount': 5 } }, loggers={ '__main__': { 'handlers': ['debug', 'api'], 'level': logging.INFO }, 'opentrons.server': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.api': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.instruments': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.config': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.drivers.smoothie_drivers.driver_3_0': { 'handlers': ['debug', 'api'], 'level': level_value }, 'opentrons.drivers.serial_communication': { 'handlers': ['serial'], 'level': logging.DEBUG }, 'opentrons.drivers.thermocycler.driver': { 'handlers': ['serial'], 'level': logging.DEBUG }, 'opentrons.protocol_api': { 'handlers': ['api', 'debug'], 'level': level_value }, 'opentrons.hardware_control': { 'handlers': ['api', 'debug'], 'level': level_value }, 'opentrons.legacy_api.containers': { 'handlers': ['api'], 'level': level_value } } ) dictConfig(logging_config)
[ "def", "log_init", "(", ")", ":", "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...
Function that sets log levels and format strings. Checks for the OT_API_LOG_LEVEL environment variable otherwise defaults to DEBUG.
[ "Function", "that", "sets", "log", "levels", "and", "format", "strings", ".", "Checks", "for", "the", "OT_API_LOG_LEVEL", "environment", "variable", "otherwise", "defaults", "to", "DEBUG", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/main.py#L17-L113
train
198,081
Opentrons/opentrons
api/src/opentrons/main.py
main
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 :py:mod:`opentrons.legacy_api` or :py:mod:`opentrons.hardware_control` This function does not return until the server is brought down. """ 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")
python
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 :py:mod:`opentrons.legacy_api` or :py:mod:`opentrons.hardware_control` This function does not return until the server is brought down. """ 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", "(", ")", ":", "arg_parser", "=", "ArgumentParser", "(", "description", "=", "\"Opentrons robot software\"", ",", "parents", "=", "[", "build_arg_parser", "(", ")", "]", ")", "args", "=", "arg_parser", ".", "parse_args", "(", ")", "run", "(", ...
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 :py:mod:`opentrons.legacy_api` or :py:mod:`opentrons.hardware_control` This function does not return until the server is brought down.
[ "The", "main", "entrypoint", "for", "the", "Opentrons", "robot", "API", "server", "stack", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/main.py#L201-L219
train
198,082
Opentrons/opentrons
api/src/opentrons/system/udev.py
setup_rules_file
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/ """ 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 = subprocess.run('udevadm control --reload-rules', shell=True, stdout=subprocess.PIPE).stdout.decode() if res0: log.warning(res0.strip()) res1 = subprocess.run('udevadm trigger', shell=True, stdout=subprocess.PIPE).stdout.decode() if res1: log.warning(res1.strip())
python
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/ """ 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 = subprocess.run('udevadm control --reload-rules', shell=True, stdout=subprocess.PIPE).stdout.decode() if res0: log.warning(res0.strip()) res1 = subprocess.run('udevadm trigger', shell=True, stdout=subprocess.PIPE).stdout.decode() if res1: log.warning(res1.strip())
[ "def", "setup_rules_file", "(", ")", ":", "import", "shutil", "import", "subprocess", "rules_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__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/
[ "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" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/udev.py#L7-L35
train
198,083
Opentrons/opentrons
update-server/otupdate/buildroot/control.py
restart
async def restart(request: web.Request) -> web.Response: """ Restart the robot. Blocks while the restart lock is held. """ 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)
python
async def restart(request: web.Request) -> web.Response: """ Restart the robot. Blocks while the restart lock is held. """ 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", ":", "async", "with", "request", ".", "app", "[", "RESTART_LOCK_NAME", "]", ":", "asyncio", ".", "get_event_loop", "(", ")", ".", "call_later", "(",...
Restart the robot. Blocks while the restart lock is held.
[ "Restart", "the", "robot", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/control.py#L22-L30
train
198,084
Opentrons/opentrons
update-server/otupdate/balena/bootstrap.py
create_virtual_environment
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 """ 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') else: python = os.path.join(venv_dir, 'bin', 'python') venv_site_pkgs = install_dependencies(python) log.info("Created virtual environment at {}".format(venv_dir)) return venv_dir, python, venv_site_pkgs
python
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 """ 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') else: python = os.path.join(venv_dir, 'bin', 'python') venv_site_pkgs = install_dependencies(python) log.info("Created virtual environment at {}".format(venv_dir)) return venv_dir, python, venv_site_pkgs
[ "async", "def", "create_virtual_environment", "(", "loop", "=", "None", ")", ":", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "venv_dir", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "VENV_NAME", ")", "proc1", "=", "await", "asynci...
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
[ "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", ...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/balena/bootstrap.py#L21-L42
train
198,085
Opentrons/opentrons
update-server/otupdate/balena/bootstrap.py
install_dependencies
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 because it does not have permission to overwrite a package by the same name and then it picks up the system version of otupdate. Also, we have to do a copy rather than a symlink because a non- admin Windows account does not have permissions to create symlinks. """ # 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 idna import pip import setuptools import virtualenv # Determine where the site-packages directory exists in the virtualenv tmpdirname = python.split(VENV_NAME)[0] paths_raw = sp.check_output( '{} -c "import sys; [print(p) for p in sys.path]"'.format(python), shell=True) paths = paths_raw.decode().split() venv_site_pkgs = list( filter( lambda x: tmpdirname in x and 'site-packages' in x, paths))[-1] dependencies = [ ('aiohttp', aiohttp), ('virtualenv_support', virtualenv_support), ('async_timeout', async_timeout), ('chardet', chardet), ('multidict', multidict), ('yarl', yarl), ('idna', idna), ('pip', pip), ('setuptools', setuptools), ('virtualenv.py', virtualenv)] # Copy each dependency from is system-install location to the site-packages # directory of the virtualenv for dep_name, dep in dependencies: src_dir = os.path.abspath(os.path.dirname(dep.__file__)) dst = os.path.join(venv_site_pkgs, dep_name) if os.path.exists(dst): log.debug('{} already exists--skipping'.format(dst)) else: log.debug('Copying {} to {}'.format(dep_name, dst)) if dep_name.endswith('.py'): shutil.copy2(os.path.join(src_dir, dep_name), dst) else: shutil.copytree(src_dir, dst) return venv_site_pkgs
python
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 because it does not have permission to overwrite a package by the same name and then it picks up the system version of otupdate. Also, we have to do a copy rather than a symlink because a non- admin Windows account does not have permissions to create symlinks. """ # 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 idna import pip import setuptools import virtualenv # Determine where the site-packages directory exists in the virtualenv tmpdirname = python.split(VENV_NAME)[0] paths_raw = sp.check_output( '{} -c "import sys; [print(p) for p in sys.path]"'.format(python), shell=True) paths = paths_raw.decode().split() venv_site_pkgs = list( filter( lambda x: tmpdirname in x and 'site-packages' in x, paths))[-1] dependencies = [ ('aiohttp', aiohttp), ('virtualenv_support', virtualenv_support), ('async_timeout', async_timeout), ('chardet', chardet), ('multidict', multidict), ('yarl', yarl), ('idna', idna), ('pip', pip), ('setuptools', setuptools), ('virtualenv.py', virtualenv)] # Copy each dependency from is system-install location to the site-packages # directory of the virtualenv for dep_name, dep in dependencies: src_dir = os.path.abspath(os.path.dirname(dep.__file__)) dst = os.path.join(venv_site_pkgs, dep_name) if os.path.exists(dst): log.debug('{} already exists--skipping'.format(dst)) else: log.debug('Copying {} to {}'.format(dep_name, dst)) if dep_name.endswith('.py'): shutil.copy2(os.path.join(src_dir, dep_name), dst) else: shutil.copytree(src_dir, dst) return venv_site_pkgs
[ "def", "install_dependencies", "(", "python", ")", "->", "str", ":", "# 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_suppor...
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 because it does not have permission to overwrite a package by the same name and then it picks up the system version of otupdate. Also, we have to do a copy rather than a symlink because a non- admin Windows account does not have permissions to create symlinks.
[ "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", "-", "...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/balena/bootstrap.py#L45-L105
train
198,086
Opentrons/opentrons
update-server/otupdate/balena/bootstrap.py
_start_server
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 """ 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(' '.join(cmd), shell=True, cwd=cwd) atexit.register(lambda: _stop_server(proc)) n_retries = 3 async with aiohttp.ClientSession() as session: test_status, detail = await selftest.health_check( session=session, port=port, retries=n_retries) if test_status == 'failure': log.debug( "Test server failed to start after {} retries. Stopping.".format( n_retries)) _stop_server(proc) return proc
python
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 """ 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(' '.join(cmd), shell=True, cwd=cwd) atexit.register(lambda: _stop_server(proc)) n_retries = 3 async with aiohttp.ClientSession() as session: test_status, detail = await selftest.health_check( session=session, port=port, retries=n_retries) if test_status == 'failure': log.debug( "Test server failed to start after {} retries. Stopping.".format( n_retries)) _stop_server(proc) return proc
[ "async", "def", "_start_server", "(", "python", ",", "port", ",", "venv_site_pkgs", "=", "None", ",", "cwd", "=", "None", ")", "->", "sp", ".", "Popen", ":", "log", ".", "info", "(", "\"Starting sandboxed update server on port {}\"", ".", "format", "(", "por...
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
[ "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", ...
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/balena/bootstrap.py#L108-L135
train
198,087
Opentrons/opentrons
update-server/otupdate/balena/bootstrap.py
install_update
async def install_update(filename, loop): """ Install the update into the system environment. """ 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, 'filename': filename} return res, returncode
python
async def install_update(filename, loop): """ Install the update into the system environment. """ 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, 'filename': filename} return res, returncode
[ "async", "def", "install_update", "(", "filename", ",", "loop", ")", ":", "log", ".", "info", "(", "\"Installing update server into system environment\"", ")", "log", ".", "debug", "(", "'File {} exists? {}'", ".", "format", "(", "filename", ",", "os", ".", "pat...
Install the update into the system environment.
[ "Install", "the", "update", "into", "the", "system", "environment", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/balena/bootstrap.py#L166-L178
train
198,088
Opentrons/opentrons
api/src/opentrons/util/linal.py
solve
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: [ (1, 1), (2, 2), (1, 2) ] And the actual measured points are: [ (1.1, 1.1), (2.1, 2.1), (1.1, 2.1) ] (in other words, a shift of exaxtly +0.1 in both x and y) Then the resulting transformation matrix T should be: [ 1 0 -0.1 ] [ 0 1 -0.1 ] [ 0 0 1 ] Then, if we take a 3x3 matrix B representing one of the measured points on the deck: [ 1 0 1.1 ] [ 0 1 2.1 ] [ 0 0 1 ] The B*T will yeild the "actual" point: [ 1 0 1 ] [ 0 1 2 ] [ 0 0 1 ] The return value of this function is the transformation matrix T """ # 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 `expected` and `actual`: # [ (x1, y1), # (x2, y2), # (x3, y3) ] ex = np.array([ list(point) + [1] for point in expected ]).transpose() ac = np.array([ list(point) + [1] for point in actual ]).transpose() # Shape of `ex` and `ac`: # [ x1 x2 x3 ] # [ y1 y2 y3 ] # [ 1 1 1 ] transform = np.dot(ac, inv(ex)) # `dot` in numpy is a misnomer. When both arguments are square, N- # dimensional arrays, the return type is the result of performing matrix # multiplication, rather than the dot-product (so the return here will be # a 4x4 matrix) return transform
python
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: [ (1, 1), (2, 2), (1, 2) ] And the actual measured points are: [ (1.1, 1.1), (2.1, 2.1), (1.1, 2.1) ] (in other words, a shift of exaxtly +0.1 in both x and y) Then the resulting transformation matrix T should be: [ 1 0 -0.1 ] [ 0 1 -0.1 ] [ 0 0 1 ] Then, if we take a 3x3 matrix B representing one of the measured points on the deck: [ 1 0 1.1 ] [ 0 1 2.1 ] [ 0 0 1 ] The B*T will yeild the "actual" point: [ 1 0 1 ] [ 0 1 2 ] [ 0 0 1 ] The return value of this function is the transformation matrix T """ # 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 `expected` and `actual`: # [ (x1, y1), # (x2, y2), # (x3, y3) ] ex = np.array([ list(point) + [1] for point in expected ]).transpose() ac = np.array([ list(point) + [1] for point in actual ]).transpose() # Shape of `ex` and `ac`: # [ x1 x2 x3 ] # [ y1 y2 y3 ] # [ 1 1 1 ] transform = np.dot(ac, inv(ex)) # `dot` in numpy is a misnomer. When both arguments are square, N- # dimensional arrays, the return type is the result of performing matrix # multiplication, rather than the dot-product (so the return here will be # a 4x4 matrix) return transform
[ "def", "solve", "(", "expected", ":", "List", "[", "Tuple", "[", "float", ",", "float", "]", "]", ",", "actual", ":", "List", "[", "Tuple", "[", "float", ",", "float", "]", "]", ")", "->", "np", ".", "ndarray", ":", "# Note: input list shape validation...
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: [ (1, 1), (2, 2), (1, 2) ] And the actual measured points are: [ (1.1, 1.1), (2.1, 2.1), (1.1, 2.1) ] (in other words, a shift of exaxtly +0.1 in both x and y) Then the resulting transformation matrix T should be: [ 1 0 -0.1 ] [ 0 1 -0.1 ] [ 0 0 1 ] Then, if we take a 3x3 matrix B representing one of the measured points on the deck: [ 1 0 1.1 ] [ 0 1 2.1 ] [ 0 0 1 ] The B*T will yeild the "actual" point: [ 1 0 1 ] [ 0 1 2 ] [ 0 0 1 ] The return value of this function is the transformation matrix T
[ "Takes", "two", "lists", "of", "3", "x", "-", "y", "points", "each", "and", "calculates", "the", "matrix", "representing", "the", "transformation", "from", "one", "space", "to", "the", "other", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/util/linal.py#L7-L74
train
198,089
Opentrons/opentrons
api/src/opentrons/util/linal.py
apply_transform
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 transform or as a standard transform. You might use with_offsets=False :return: corresponding XYZ point in space B """ extended = 1 if with_offsets else 0 return tuple(dot(t, list(pos) + [extended])[:3])
python
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 transform or as a standard transform. You might use with_offsets=False :return: corresponding XYZ point in space B """ 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", ")", "-...
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 transform or as a standard transform. You might use with_offsets=False :return: corresponding XYZ point in space B
[ "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", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/util/linal.py#L117-L133
train
198,090
Opentrons/opentrons
api/src/opentrons/util/linal.py
apply_reverse
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 """ return apply_transform(inv(t), pos)
python
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 """ return apply_transform(inv(t), pos)
[ "def", "apply_reverse", "(", "t", ":", "Union", "[", "List", "[", "List", "[", "float", "]", "]", ",", "np", ".", "ndarray", "]", ",", "pos", ":", "Tuple", "[", "float", ",", "float", ",", "float", "]", ",", "with_offsets", "=", "True", ")", "->"...
Like apply_transform but inverts the transform first
[ "Like", "apply_transform", "but", "inverts", "the", "transform", "first" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/util/linal.py#L136-L142
train
198,091
Opentrons/opentrons
update-server/otupdate/balena/control.py
_resin_supervisor_restart
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. """ 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.ClientSession() as session: async with session.post(restart_url, params={'apikey': api}, json={'appId': app_id, 'force': True}) as resp: body = await resp.read() if resp.status != 202: log.error("Could not shut down: {}: {}" .format(resp.status, body))
python
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. """ 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.ClientSession() as session: async with session.post(restart_url, params={'apikey': api}, json={'appId': app_id, 'force': True}) as resp: body = await resp.read() if resp.status != 202: log.error("Could not shut down: {}: {}" .format(resp.status, body))
[ "async", "def", "_resin_supervisor_restart", "(", ")", ":", "supervisor", "=", "os", ".", "environ", ".", "get", "(", "'RESIN_SUPERVISOR_ADDRESS'", ",", "'http://127.0.0.1:48484'", ")", "restart_url", "=", "supervisor", "+", "'/v1/restart'", "api", "=", "os", ".",...
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.
[ "Execute", "a", "container", "restart", "by", "requesting", "it", "from", "the", "supervisor", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/balena/control.py#L35-L55
train
198,092
Opentrons/opentrons
api/src/opentrons/protocol_api/back_compat.py
BCRobot.connect
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 the context of protocols executed by an OT2 is automatically connected to either the hardware or a simulator (depending on whether the protocol is being simulated or run) this should be unnecessary. :param port: The port to connect to the smoothie board or the magic string ``"Virtual Smoothie"``, which will initialize and connect to a simulator :param options: Ignored. """ self._hardware.connect(port)
python
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 the context of protocols executed by an OT2 is automatically connected to either the hardware or a simulator (depending on whether the protocol is being simulated or run) this should be unnecessary. :param port: The port to connect to the smoothie board or the magic string ``"Virtual Smoothie"``, which will initialize and connect to a simulator :param options: Ignored. """ self._hardware.connect(port)
[ "def", "connect", "(", "self", ",", "port", ":", "str", "=", "None", ",", "options", ":", "Any", "=", "None", ")", ":", "self", ".", "_hardware", ".", "connect", "(", "port", ")" ]
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 the context of protocols executed by an OT2 is automatically connected to either the hardware or a simulator (depending on whether the protocol is being simulated or run) this should be unnecessary. :param port: The port to connect to the smoothie board or the magic string ``"Virtual Smoothie"``, which will initialize and connect to a simulator :param options: Ignored.
[ "Connect", "to", "the", "robot", "hardware", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/back_compat.py#L43-L62
train
198,093
Opentrons/opentrons
api/src/opentrons/protocol_api/back_compat.py
AddInstrumentCtors._load_instr
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 of the partials below. """ return ctx.load_instrument(name, Mount[mount.upper()])
python
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 of the partials below. """ return ctx.load_instrument(name, Mount[mount.upper()])
[ "def", "_load_instr", "(", "ctx", ",", "name", ":", "str", ",", "mount", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "InstrumentContext", ":", "return", "ctx", ".", "load_instrument", "(", "name", ",", "Mount", "[", "mount", "."...
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 of the partials below.
[ "Build", "an", "instrument", "in", "a", "backwards", "-", "compatible", "way", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/back_compat.py#L127-L138
train
198,094
Opentrons/opentrons
api/src/opentrons/protocol_api/back_compat.py
BCLabware.load
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.load_labware_by_name`. In addition, this function contains translations between old labware names and new labware names. """ 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" .format(container_name)) elif container_name in ('magdeck', 'tempdeck'): raise NotImplementedError("Module load not yet implemented") else: name = container_name return self._ctx.load_labware_by_name(name, slot, label)
python
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.load_labware_by_name`. In addition, this function contains translations between old labware names and new labware names. """ 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" .format(container_name)) elif container_name in ('magdeck', 'tempdeck'): raise NotImplementedError("Module load not yet implemented") else: name = container_name return self._ctx.load_labware_by_name(name, slot, label)
[ "def", "load", "(", "self", ",", "container_name", ",", "slot", ",", "label", "=", "None", ",", "share", "=", "False", ")", ":", "if", "share", ":", "raise", "NotImplementedError", "(", "\"Sharing not supported\"", ")", "try", ":", "name", "=", "self", "...
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.load_labware_by_name`. In addition, this function contains translations between old labware names and new labware names.
[ "Load", "a", "piece", "of", "labware", "by", "specifying", "its", "name", "and", "position", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/back_compat.py#L234-L259
train
198,095
Opentrons/opentrons
api/src/opentrons/hardware_control/adapters.py
SynchronousAdapter.build
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 builder method """ 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 = checked_loop.run_until_complete(builder(*args, **kwargs)) else: api = builder(*args, **kwargs) return cls(api, loop)
python
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 builder method """ 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 = checked_loop.run_until_complete(builder(*args, **kwargs)) else: api = builder(*args, **kwargs) return cls(api, loop)
[ "def", "build", "(", "cls", ",", "builder", ",", "*", "args", ",", "build_loop", "=", "None", ",", "*", "*", "kwargs", ")", ":", "loop", "=", "asyncio", ".", "new_event_loop", "(", ")", "kwargs", "[", "'loop'", "]", "=", "loop", "args", "=", "[", ...
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 builder method
[ "Build", "a", "hardware", "control", "API", "and", "initialize", "the", "adapter", "in", "one", "call" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/adapters.py#L28-L45
train
198,096
Opentrons/opentrons
api/src/opentrons/hardware_control/adapters.py
SingletonAdapter.connect
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/pyserial/pyserial_api.html#serial.Serial.__init__>`_. # noqa(E501) :param force: If `True`, connect even if a lockfile is established. See :py:meth:`.controller.Controller.__init__`. This should only ever be specified as `True` by the main software starting. """ 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_complete(new_api.cache_instruments()) setattr(self, '_api', new_api)
python
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/pyserial/pyserial_api.html#serial.Serial.__init__>`_. # noqa(E501) :param force: If `True`, connect even if a lockfile is established. See :py:meth:`.controller.Controller.__init__`. This should only ever be specified as `True` by the main software starting. """ 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_complete(new_api.cache_instruments()) setattr(self, '_api', new_api)
[ "def", "connect", "(", "self", ",", "port", ":", "str", "=", "None", ",", "force", ":", "bool", "=", "False", ")", ":", "old_api", "=", "object", ".", "__getattribute__", "(", "self", ",", "'_api'", ")", "loop", "=", "old_api", ".", "_loop", "new_api...
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/pyserial/pyserial_api.html#serial.Serial.__init__>`_. # noqa(E501) :param force: If `True`, connect even if a lockfile is established. See :py:meth:`.controller.Controller.__init__`. This should only ever be specified as `True` by the main software starting.
[ "Connect", "to", "hardware", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/adapters.py#L164-L184
train
198,097
Opentrons/opentrons
api/src/opentrons/hardware_control/adapters.py
SingletonAdapter.disconnect
def disconnect(self): """ Disconnect from connected hardware. """ 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)
python
def disconnect(self): """ Disconnect from connected hardware. """ 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", ")", ":", "old_api", "=", "object", ".", "__getattribute__", "(", "self", ",", "'_api'", ")", "new_api", "=", "API", ".", "build_hardware_simulator", "(", "loop", "=", "old_api", ".", "_loop", ",", "config", "=", "copy", ...
Disconnect from connected hardware.
[ "Disconnect", "from", "connected", "hardware", "." ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/adapters.py#L186-L192
train
198,098
Opentrons/opentrons
api/src/opentrons/hardware_control/adapters.py
SingletonAdapter.get_attached_pipettes
def get_attached_pipettes(self): """ Mimic the behavior of robot.get_attached_pipettes""" 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.by_mount(mount), 'plunger_axis': Axis.of_plunger(mount) } if data.get('name'): instrs[mount.name.lower()]['tip_length'] \ = data.get('tip_length', None) return instrs
python
def get_attached_pipettes(self): """ Mimic the behavior of robot.get_attached_pipettes""" 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.by_mount(mount), 'plunger_axis': Axis.of_plunger(mount) } if data.get('name'): instrs[mount.name.lower()]['tip_length'] \ = data.get('tip_length', None) return instrs
[ "def", "get_attached_pipettes", "(", "self", ")", ":", "api", "=", "object", ".", "__getattribute__", "(", "self", ",", "'_api'", ")", "instrs", "=", "{", "}", "for", "mount", ",", "data", "in", "api", ".", "attached_instruments", ".", "items", "(", ")",...
Mimic the behavior of robot.get_attached_pipettes
[ "Mimic", "the", "behavior", "of", "robot", ".", "get_attached_pipettes" ]
a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/adapters.py#L203-L218
train
198,099