code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if top is not None:
self.plunger_positions['top'] = top
if bottom is not None:
self.plunger_positions['bottom'] = bottom
if blow_out is not None:
self.plunger_positions['blow_out'] = blow_out
if drop_tip is not None:
self.plunger_p... | def calibrate_plunger(
self,
top=None,
bottom=None,
blow_out=None,
drop_tip=None) | Set calibration values for the pipette plunger.
This can be called multiple times as the user sets each value,
or you can set them all at once.
Parameters
----------
top : int
Touching but not engaging the plunger.
bottom: int
Must be above the ... | 1.43486 | 1.696607 | 0.845724 |
try:
value = self.plunger_positions[position]
if helpers.is_number(value):
return value
else:
raise RuntimeError(
'Plunger position "{}" not yet calibrated'.format(
position))
except ... | def _get_plunger_position(self, position) | Returns the calibrated coordinate of a given plunger position
Raises exception if the position has not been calibrated yet | 3.155982 | 2.773914 | 1.137736 |
millimeters = ul / self._ul_per_mm(ul, 'aspirate')
destination_mm = self._get_plunger_position('bottom') + millimeters
return round(destination_mm, 6) | def _aspirate_plunger_position(self, ul) | Calculate axis position for a given liquid volume.
Translates the passed liquid volume to absolute coordinates
on the axis associated with this pipette.
Calibration of the pipette motor's ul-to-mm conversion is required | 5.788824 | 6.616096 | 0.874961 |
millimeters = ul / self._ul_per_mm(ul, 'dispense')
destination_mm = self._get_plunger_position('bottom') + millimeters
return round(destination_mm, 6) | def _dispense_plunger_position(self, ul) | Calculate axis position for a given liquid volume.
Translates the passed liquid volume to absolute coordinates
on the axis associated with this pipette.
Calibration of the pipette motor's ul-to-mm conversion is required | 6.542159 | 7.47023 | 0.875764 |
sequence = self.ul_per_mm[func]
return pipette_config.piecewise_volume_conversion(ul, sequence) | def _ul_per_mm(self, ul: float, func: str) -> float | :param ul: microliters as a float
:param func: must be one of 'aspirate' or 'dispense'
:return: microliters/mm as a float | 20.491156 | 13.005366 | 1.575592 |
if volume < 0:
raise RuntimeError(
"Volume must be a positive number, got {}.".format(volume))
if volume > self.max_volume:
raise RuntimeError(
"{0}µl exceeds pipette's maximum volume ({1}ul).".format(
volume, self.max_... | def _volume_percentage(self, volume) | Returns the plunger percentage for a given volume.
We use this to calculate what actual position the plunger axis
needs to be at in order to achieve the correct volume of liquid. | 2.968741 | 2.878054 | 1.03151 |
if self.has_tip_rack() and tips > 0 and not self.current_tip():
self.pick_up_tip() | def _add_tip_during_transfer(self, tips, **kwargs) | Performs a :any:`pick_up_tip` when running a :any:`transfer`,
:any:`distribute`, or :any:`consolidate`. | 8.085104 | 5.668772 | 1.426253 |
rate = kwargs.get('rate', 1)
mix_before = kwargs.get('mix', kwargs.get('mix_before', (0, 0)))
air_gap = kwargs.get('air_gap', 0)
touch_tip = kwargs.get('touch_tip', False)
well, _ = unpack_location(loc)
if self.current_volume == 0:
self._mix_during_... | def _aspirate_during_transfer(self, vol, loc, **kwargs) | Performs an :any:`aspirate` when running a :any:`transfer`, and
optionally a :any:`touch_tip` afterwards. | 3.344606 | 3.21422 | 1.040566 |
mix_after = kwargs.get('mix_after', (0, 0))
rate = kwargs.get('rate', 1)
air_gap = kwargs.get('air_gap', 0)
well, _ = unpack_location(loc)
if air_gap:
self.dispense(air_gap, well.top(5), rate=rate)
self.dispense(vol, loc, rate=rate)
self._mi... | def _dispense_during_transfer(self, vol, loc, **kwargs) | Performs a :any:`dispense` when running a :any:`transfer`, and
optionally a :any:`mix`, :any:`touch_tip`, and/or
:any:`blow_out` afterwards. | 3.63339 | 3.539473 | 1.026534 |
trash = kwargs.get('trash', True)
if tips > 1 or (i + 1 == total and tips > 0):
if trash and self.trash_container:
self.drop_tip()
else:
self.return_tip()
tips -= 1
return tips | def _drop_tip_during_transfer(self, tips, i, total, **kwargs) | Performs a :any:`drop_tip` or :any:`return_tip` when
running a :any:`transfer`, :any:`distribute`, or :any:`consolidate`. | 4.250902 | 3.648295 | 1.165175 |
if aspirate:
self.speeds['aspirate'] = aspirate
if dispense:
self.speeds['dispense'] = dispense
return self | def set_speed(self, aspirate=None, dispense=None) | Set the speed (mm/second) the :any:`Pipette` plunger will move
during :meth:`aspirate` and :meth:`dispense`
Parameters
----------
aspirate: int
The speed in millimeters-per-second, at which the plunger will
move while performing an aspirate
dispense: int... | 1.973885 | 2.954592 | 0.668074 |
ul = self.max_volume
if aspirate:
# Set the ul_per_mm for the pipette
ul_per_mm = self._ul_per_mm(ul, 'aspirate')
self.set_speed(
aspirate=round(aspirate / ul_per_mm, 6))
if dispense:
# Set the ul_per_mm for the pipette
... | def set_flow_rate(self, aspirate=None, dispense=None) | Set the speed (uL/second) the :any:`Pipette` plunger will move
during :meth:`aspirate` and :meth:`dispense`. The speed is set using
nominal max volumes for any given pipette model.
Parameters
----------
aspirate: int
The speed in microliters-per-second, at which the p... | 2.436172 | 2.367773 | 1.028888 |
if amperes >= 0 and amperes <= 2.0:
self._pick_up_current = amperes
else:
raise ValueError(
'Amperes must be a floating point between 0.0 and 2.0')
return self | def set_pick_up_current(self, amperes) | Set the current (amperes) the pipette mount's motor will use while
picking up a tip.
Parameters
----------
amperes: float (0.0 - 2.0)
The amperage of the motor while creating a seal with tips. | 2.855824 | 3.222289 | 0.886272 |
if height > MAX_ENGAGE_HEIGHT or height < 0:
raise ValueError('Invalid engage height. Should be 0 to {}'.format(
MAX_ENGAGE_HEIGHT))
self._driver.move(height)
self._engaged = True | def engage(self, height) | Move the magnet to a specific height, in mm from home position | 4.096519 | 3.881259 | 1.055461 |
heading = target - p1
if mode == 'relative':
heading = target
length = heading.length()
length_steps = length / increment
length_remainder = length % increment
vector_step = Vector(0, 0, 0)
if length_steps > 0:
vector_step = heading / length_steps
vector_remainder... | def break_down_travel(p1, target, increment=5, mode='absolute') | given two points p1 and target, this returns a list of
incremental positions or relative steps | 2.318664 | 2.29687 | 1.009488 |
max_vol = float(max_vol)
carryover = kwargs.get('carryover', True)
if not carryover:
return plan
new_transfer_plan = []
for p in plan:
source = p['aspirate']['location']
target = p['dispense']['location']
volume = float(p['aspirate']['volume'])
while volu... | def _expand_for_carryover(max_vol, plan, **kwargs) | Divide volumes larger than maximum volume into separate transfers | 1.858247 | 1.725626 | 1.076854 |
max_vol = float(max_vol)
mode = kwargs.get('mode', 'transfer')
if mode == 'distribute': # combine target volumes into single aspirate
return _compress_for_distribute(max_vol, plan, **kwargs)
if mode == 'consolidate': # combine target volumes into multiple aspirates
return _compre... | def _compress_for_repeater(max_vol, plan, **kwargs) | Reduce size of transfer plan, if mode is distribute or consolidate | 3.613539 | 2.589777 | 1.395309 |
source = None
new_source = None
a_vol = 0
temp_dispenses = []
new_transfer_plan = []
disposal_vol = kwargs.get('disposal_vol', 0)
max_vol = max_vol - disposal_vol
def _append_dispenses():
nonlocal a_vol, temp_dispenses, new_transfer_plan, source
if not temp_dispense... | def _compress_for_distribute(max_vol, plan, **kwargs) | Combines as many dispenses as can fit within the maximum volume | 2.366999 | 2.196839 | 1.077457 |
target = None
new_target = None
d_vol = 0
temp_aspirates = []
new_transfer_plan = []
def _append_aspirates():
nonlocal d_vol, temp_aspirates, new_transfer_plan, target
if not temp_aspirates:
return
for a in temp_aspirates:
new_transfer_plan.a... | def _compress_for_consolidate(max_vol, plan, **kwargs) | Combines as many aspirates as can fit within the maximum volume | 2.330624 | 2.154393 | 1.081801 |
settings_file = CONFIG['feature_flags_file']
values, _ = _read_settings_file(settings_file)
return {
key: {**settings_by_id[key].__dict__,
'value': value}
for key, value in values.items()
} | def get_all_adv_settings() -> Dict[str, Dict[str, Union[str, bool, None]]] | :return: a dict of settings keyed by setting ID, where each value is a
dict with keys "id", "title", "description", and "value" | 5.877753 | 5.893667 | 0.9973 |
# Read settings from persistent file
data = _read_json_file(settings_file)
settings, version = _migrate(data)
if (data.get('_version') != version):
_write_settings_file(settings, version, settings_file)
return settings, version | def _read_settings_file(settings_file: 'Path') -> SettingsData | Read the settings file, which is a json object with settings IDs as keys
and boolean values. For each key, look up the `Settings` object with that
key. If the key is one of the old IDs (kebab case), replace it with the
new ID and rewrite the settings file
:param settings_file: the path to the settings ... | 5.358612 | 6.850238 | 0.782252 |
next: SettingsMap = {}
for s in settings:
id = s.id
old_id = s.old_id
if previous.get(id) is True:
next[id] = True
elif previous.get(old_id) is True:
next[id] = True
else:
next[id] = None
return next | def _migrate0to1(previous: Mapping[str, Any]) -> SettingsMap | Migrate to version 1 of the feature flags file. Replaces old IDs with new
IDs and sets any False values to None | 2.914415 | 2.630756 | 1.107824 |
next = dict(data)
version = next.pop('_version', 0)
target_version = len(_MIGRATIONS)
migrations = _MIGRATIONS[version:]
if len(migrations) > 0:
log.info(
"Migrating advanced settings from version {} to {}"
.format(version, target_version))
for m in migrati... | def _migrate(data: Mapping[str, Any]) -> SettingsData | Check the version integer of the JSON file data a run any necessary
migrations to get us to the latest file format. Returns dictionary of
settings and version migrated to | 3.891814 | 3.796306 | 1.025158 |
to_return = {}
should_write = False
for keyname, typekind, default in REQUIRED_DATA:
if keyname not in data:
LOG.debug(f"Defaulted config value {keyname} to {default}")
to_return[keyname] = default
should_write = True
elif not isinstance(data[keyname]... | def _ensure_values(data: Mapping[str, Any]) -> Tuple[Dict[str, Any], bool] | Make sure we have appropriate keys and say if we should write | 2.47107 | 2.391458 | 1.03329 |
data = _ensure_load(path)
if not data:
data = {}
values, should_write = _ensure_values(data)
values.update({'path': path})
config = Config(**values)
if config.signature_required:
if not os.path.exists(config.update_cert_path):
LOG.warning(
f"No si... | def load_from_path(path: str) -> Config | Load a config from a file and ensure its structure.
Writes a default if necessary | 4.374238 | 4.272079 | 1.023913 |
env_path = os.getenv(PATH_ENVIRONMENT_VARIABLE)
for path, source in ((args_path, 'arg'),
(env_path, 'env')):
if not path:
LOG.debug(f"config.load: skipping {source} (path None)")
continue
else:
LOG.debug(f"config.load: using confi... | def _get_path(args_path: Optional[str]) -> str | Find the valid path from args then env then default | 5.087341 | 4.271731 | 1.190932 |
LOG.debug(f"Saving config to {path}")
with open(path, 'w') as cf:
cf.write(json.dumps({k: v for k, v in config._asdict().items()
if k != 'path'})) | def save_to_path(path: str, config: Config) -> None | Save the config file to a specific path (not what's in the config) | 3.511183 | 2.966043 | 1.183793 |
assert stage in Stages
LOG.info(f'Update session: stage {self._stage.name}->{stage.name}')
self._stage = stage | def set_stage(self, stage: Stages) | Convenience method to set the stage and lookup message | 9.151128 | 7.616537 | 1.201481 |
LOG.error(f"Update session: error in stage {self._stage.name}: "
f"{error_shortmsg}: {error_longmsg}")
self._error = Value(error_shortmsg, error_longmsg)
self.set_stage(Stages.ERROR) | def set_error(self, error_shortmsg: str, error_longmsg: str) | Set the stage to error and add a message | 5.664615 | 4.829373 | 1.17295 |
if self.is_error:
assert self._error
return self._error.human
else:
return self._stage.value.human | def message(self) -> str | The human readable message of the current stage | 11.877025 | 7.415257 | 1.601701 |
return sum([
[(child, level)] + descendants(state, child, level + 1)
for child in state[obj].children
], []) | def descendants(state, obj, level=0) | Returns a flattened list tuples of DFS traversal of subtree
from object that contains descendant object and it's depth | 4.832856 | 4.611587 | 1.047981 |
def fold(objects):
return functools.reduce(
lambda a, b: a.dot(b),
[state[key].transform for key in objects],
np.identity(4)
)
up, down = ascend(state, src), list(reversed(ascend(state, dst)))
# Find common prefix. Last item is common root
root ... | def change_base(state, point=Point(0, 0, 0), src=ROOT, dst=ROOT) | Transforms point from source coordinate system to destination.
Point(0, 0, 0) means the origin of the source. | 4.658619 | 4.558038 | 1.022067 |
return (cls.X, cls.Y, cls.Z, cls.A) | def gantry_axes(cls) -> Tuple['Axis', 'Axis', 'Axis', 'Axis'] | The axes which are tied to the gantry and require the deck
calibration transform | 3.24685 | 3.903553 | 0.831768 |
from copy import deepcopy
from opentrons.trackers.pose_tracker import update
robot = instrument.robot
config = robot.config
instrument_offset = deepcopy(config.instrument_offset)
dx, dy, dz = array(measured_center) - config.tip_probe.center
log.debug("This is measured probe center dx... | def update_instrument_config(
instrument, measured_center) -> Tuple[Point, float] | Update config and pose tree with instrument's x and y offsets
and tip length based on delta between probe center and measured_center,
persist updated config and return it | 4.941585 | 4.789009 | 1.03186 |
'''
Returns the number in the expected string "N:12.3", where "N" is the
axis, and "12.3" is a floating point value for the axis' position
'''
try:
return round(
float(smoothie_substring.split(':')[1]),
GCODE_ROUNDING_PRECISION
)
except (ValueError, IndexE... | def _parse_number_from_substring(smoothie_substring) | Returns the number in the expected string "N:12.3", where "N" is the
axis, and "12.3" is a floating point value for the axis' position | 4.552804 | 2.507772 | 1.815477 |
'''
Returns the axis in the expected string "N:12.3", where "N" is the
axis, and "12.3" is a floating point value for the axis' position
'''
try:
return smoothie_substring.split(':')[0].title() # upper 1st letter
except (ValueError, IndexError, TypeError, AttributeError):
log.ex... | def _parse_axis_from_substring(smoothie_substring) | Returns the axis in the expected string "N:12.3", where "N" is the
axis, and "12.3" is a floating point value for the axis' position | 5.022457 | 2.77568 | 1.809451 |
'''
Parse the Smoothieware response to a G28.6 command (homing-status)
A "1" means it has been homed, and "0" means it has not been homed
Example response after homing just X axis:
"X:1 Y:0 Z:0 A:0 B:0 C:0"
returns: dict
Key is axis, value is True if the axis ne... | def _parse_homing_status_values(raw_homing_status_values) | Parse the Smoothieware response to a G28.6 command (homing-status)
A "1" means it has been homed, and "0" means it has not been homed
Example response after homing just X axis:
"X:1 Y:0 Z:0 A:0 B:0 C:0"
returns: dict
Key is axis, value is True if the axis needs to be homed | 4.071379 | 1.969598 | 2.067112 |
'''
Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None
'''
res: Optional[str] = None
if self.simulating:
res = '123... | def read_pipette_id(self, mount) -> Optional[str] | Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None | 5.399524 | 2.907329 | 1.857211 |
'''
Reads an attached pipette's MODEL
The MODEL is a unique string for this model of pipette
:param mount: string with value 'left' or 'right'
:return model string, or None
'''
if self.simulating:
res = None
else:
res = self._read_... | def read_pipette_model(self, mount) -> Optional[str] | Reads an attached pipette's MODEL
The MODEL is a unique string for this model of pipette
:param mount: string with value 'left' or 'right'
:return model string, or None | 5.769522 | 3.848082 | 1.499324 |
'''
Queries Smoothieware for it's build version, and returns
the parsed response.
returns: str
Current version of attached Smoothi-driver. Versions are derived
from git branch-hash (eg: edge-66ec883NOMSD)
Example Smoothieware response:
Build ver... | def get_fw_version(self) | Queries Smoothieware for it's build version, and returns
the parsed response.
returns: str
Current version of attached Smoothi-driver. Versions are derived
from git branch-hash (eg: edge-66ec883NOMSD)
Example Smoothieware response:
Build version: edge-66ec883NO... | 14.74122 | 1.817464 | 8.110872 |
return {k.upper(): v for k, v in self._position.items()} | def position(self) | Instead of sending M114.2 we are storing target values in
self._position since movement and home commands are blocking and
assumed to go the correct place.
Cases where Smoothie would not be in the correct place (such as if a
belt slips) would not be corrected by getting position with M1... | 7.756253 | 6.247884 | 1.241421 |
'''
Returns Smoothieware's current homing-status, which is a dictionary
of boolean values for each axis (XYZABC). If an axis is False, then it
still needs to be homed, and it's coordinate cannot be trusted.
Smoothieware sets it's internal homing flags for all axes to False when
... | def update_homed_flags(self, flags=None) | Returns Smoothieware's current homing-status, which is a dictionary
of boolean values for each axis (XYZABC). If an axis is False, then it
still needs to be homed, and it's coordinate cannot be trusted.
Smoothieware sets it's internal homing flags for all axes to False when
it has yet to... | 5.018666 | 2.071952 | 2.422192 |
''' set total axes movement speed in mm/second'''
self._combined_speed = float(value)
speed_per_min = int(self._combined_speed * SEC_PER_MIN)
command = GCODES['SET_SPEED'] + str(speed_per_min)
log.debug("set_speed: {}".format(command))
self._send_command(command) | def set_speed(self, value) | set total axes movement speed in mm/second | 6.488712 | 4.966343 | 1.306537 |
'''
Sets the acceleration (mm/sec^2) that a given axis will move
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for mm-per-second-squared (mm/sec^2)
'''
self._acceleration.update(settings)
value... | def set_acceleration(self, settings) | Sets the acceleration (mm/sec^2) that a given axis will move
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for mm-per-second-squared (mm/sec^2) | 5.55284 | 2.298337 | 2.416025 |
'''
Sets the amperage of each motor for when it is activated by driver.
Values are initialized from the `robot_config.high_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the active-current of it's pipette,
... | def set_active_current(self, settings) | Sets the amperage of each motor for when it is activated by driver.
Values are initialized from the `robot_config.high_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the active-current of it's pipette,
depending on ... | 7.753641 | 2.11692 | 3.662699 |
'''
Sets the amperage of each motor for when it is dwelling.
Values are initialized from the `robot_config.log_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the dwelling-current of it's pipette,
dep... | def set_dwelling_current(self, settings) | Sets the amperage of each motor for when it is dwelling.
Values are initialized from the `robot_config.log_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the dwelling-current of it's pipette,
depending on what model... | 7.548967 | 2.213197 | 3.410889 |
'''
Sets the current in Amperes (A) by axis. Currents are limited to be
between 0.0-2.0 amps per axis motor.
Note: this method does not send gcode commands, but instead stores the
desired current setting. A seperate call to _generate_current_command()
will return a gcode... | def _save_current(self, settings, axes_active=True) | Sets the current in Amperes (A) by axis. Currents are limited to be
between 0.0-2.0 amps per axis motor.
Note: this method does not send gcode commands, but instead stores the
desired current setting. A seperate call to _generate_current_command()
will return a gcode command that can be... | 9.665794 | 1.80503 | 5.354922 |
'''
Returns a constructed GCode string that contains this driver's
axis-current settings, plus a small delay to wait for those settings
to take effect.
'''
values = ['{}{}'.format(axis, value)
for axis, value in sorted(self.current.items())]
curr... | def _generate_current_command(self) | Returns a constructed GCode string that contains this driver's
axis-current settings, plus a small delay to wait for those settings
to take effect. | 7.085805 | 3.668285 | 1.93164 |
'''
Disable the stepper-motor-driver's 36v output to motor
This is a safe GCODE to send to Smoothieware, as it will automatically
re-engage the motor if it receives a home or move command
axes
String containing the axes to be disengaged
(e.g.: 'XY' or 'ZA... | def disengage_axis(self, axes) | Disable the stepper-motor-driver's 36v output to motor
This is a safe GCODE to send to Smoothieware, as it will automatically
re-engage the motor if it receives a home or move command
axes
String containing the axes to be disengaged
(e.g.: 'XY' or 'ZA' or 'XYZABC') | 8.853233 | 2.142771 | 4.131675 |
'''
Sets motors to low current, for when they are not moving.
Dwell for XYZA axes is only called after HOMING
Dwell for BC axes is called after both HOMING and MOVING
axes:
String containing the axes to set to low current (eg: 'XYZABC')
'''
axes = ''... | def dwell_axes(self, axes) | Sets motors to low current, for when they are not moving.
Dwell for XYZA axes is only called after HOMING
Dwell for BC axes is called after both HOMING and MOVING
axes:
String containing the axes to set to low current (eg: 'XYZABC') | 9.193755 | 3.068554 | 2.99612 |
'''
Sets motors to a high current, for when they are moving
and/or must hold position
Activating XYZABC axes before both HOMING and MOVING
axes:
String containing the axes to set to high current (eg: 'XYZABC')
'''
axes = ''.join(set(axes) & set(AXES)... | def activate_axes(self, axes) | Sets motors to a high current, for when they are moving
and/or must hold position
Activating XYZABC axes before both HOMING and MOVING
axes:
String containing the axes to set to high current (eg: 'XYZABC') | 10.762657 | 3.300807 | 3.260614 |
if self.simulating:
return
command_line = command + ' ' + SMOOTHIE_COMMAND_TERMINATOR
ret_code = self._recursive_write_and_return(
command_line, timeout, DEFAULT_COMMAND_RETRIES)
ret_code = self._remove_unwanted_characters(command_line, ret_code)
... | def _send_command(self, command, timeout=DEFAULT_SMOOTHIE_TIMEOUT) | Submit a GCODE command to the robot, followed by M400 to block until
done. This method also ensures that any command on the B or C axis
(the axis for plunger control) do current ramp-up and ramp-down, so
that plunger motors rest at a low current to prevent burn-out.
In the case of a lim... | 6.399467 | 5.948475 | 1.075816 |
'''
Read from an attached pipette's internal memory. The gcode used
determines which portion of memory is read and returned.
All motors must be disengaged to consistently read over I2C lines
gcode:
String (str) containing a GCode
either 'READ_INSTRUMENT_... | def _read_from_pipette(self, gcode, mount) -> Optional[str] | Read from an attached pipette's internal memory. The gcode used
determines which portion of memory is read and returned.
All motors must be disengaged to consistently read over I2C lines
gcode:
String (str) containing a GCode
either 'READ_INSTRUMENT_ID' or 'READ_INSTRUM... | 9.349717 | 5.048525 | 1.85197 |
'''
Write to an attached pipette's internal memory. The gcode used
determines which portion of memory is written to.
NOTE: To enable write-access to the pipette, it's button must be held
gcode:
String (str) containing a GCode
either 'WRITE_INSTRUMENT_ID'... | def _write_to_pipette(self, gcode, mount, data_string) | Write to an attached pipette's internal memory. The gcode used
determines which portion of memory is written to.
NOTE: To enable write-access to the pipette, it's button must be held
gcode:
String (str) containing a GCode
either 'WRITE_INSTRUMENT_ID' or 'WRITE_INSTRUMEN... | 7.331327 | 3.993352 | 1.835883 |
'''
Move to the `target` Smoothieware coordinate, along any of the size
axes, XYZABC.
target: dict
dict setting the coordinate that Smoothieware will be at when
`move()` returns. `target` keys are the axis in upper-case, and the
values are the coordin... | def move(self, target, home_flagged_axes=False) | Move to the `target` Smoothieware coordinate, along any of the size
axes, XYZABC.
target: dict
dict setting the coordinate that Smoothieware will be at when
`move()` returns. `target` keys are the axis in upper-case, and the
values are the coordinate in millimeters (... | 6.018942 | 3.131739 | 1.921917 |
''' home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home.
'''
# move some mm distance away from the target axes endstop switch(es)
destination = {
... | def fast_home(self, axis, safety_margin) | home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home. | 11.887965 | 6.632453 | 1.792393 |
'''
The plunger axes on OT2 can build up static friction over time and
when it's cold. To get over this, the robot can move that plunger at
normal current and a very slow speed to increase the torque, removing
the static friction
axes:
String containing each ... | def unstick_axes(self, axes, distance=None, speed=None) | The plunger axes on OT2 can build up static friction over time and
when it's cold. To get over this, the robot can move that plunger at
normal current and a very slow speed to increase the torque, removing
the static friction
axes:
String containing each axis to be moved. Ex... | 5.652795 | 2.697575 | 2.09551 |
log.debug("kill")
self._smoothie_hard_halt()
self._reset_from_error()
self._setup() | def kill(self) | In order to terminate Smoothie motion immediately (including
interrupting a command in progress, we set the reset pin low and then
back to high, then call `_setup` method to send the RESET_FROM_ERROR
Smoothie code to return Smoothie to a normal waiting state and reset
any other state nee... | 17.672853 | 6.379225 | 2.770376 |
'''
Given a list of axes to check, this method will home each axis if
Smoothieware's internal flag sets it as needing to be homed
'''
axes_that_need_to_home = [
axis
for axis, already_homed in self.homed_flags.items()
if (not already_homed) and... | def home_flagged_axes(self, axes_string) | Given a list of axes to check, this method will home each axis if
Smoothieware's internal flag sets it as needing to be homed | 4.455756 | 2.326138 | 1.915516 |
# ensure there is a reference to the port
if self.simulating:
return 'Did nothing (simulating)'
smoothie_update._ensure_programmer_executable()
if not self.is_connected():
self._connect_to_port()
# get port name
port = self._connection.... | async def update_firmware(self,
filename: str,
loop: asyncio.AbstractEventLoop = None,
explicit_modeset: bool = True) -> str | Program the smoothie board with a given hex file.
If explicit_modeset is True (default), explicitly place the smoothie in
programming mode.
If explicit_modeset is False, assume the smoothie is already in
programming mode. | 6.058615 | 5.749906 | 1.053689 |
if self._poller:
self._poller.join()
self._driver.connect(self._port)
self._device_info = self._driver.get_device_info()
self._poller = Poller(self._driver)
self._poller.start() | async def _connect(self) | Connect to the 'TempDeck' port
Planned change- will connect to the correct port in case of multiple
TempDecks | 3.359102 | 2.900487 | 1.158116 |
# OT-One users specify columns in the A1, B3 fashion
# below methods help convert to the 1, 2, etc integer names
def is_ot_one_slot_name(s):
return isinstance(s, str) and len(s) == 2 and s[0] in 'ABCD'
def convert_ot_one_slot_names(s):
col = 'ABCD'.index(slot[0])
row = int... | def load(robot, container_name, slot, label=None, share=False) | Examples
--------
>>> from opentrons import containers
>>> containers.load('96-flat', '1')
<Deck>/<Slot 1>/<Container 96-flat>
>>> containers.load('96-flat', '4', 'plate')
<Deck>/<Slot 4>/<Container plate>
>>> containers.load('non-existent-type', '4') # doctest: +ELLIPSIS
Exception: Cont... | 4.321957 | 4.353587 | 0.992735 |
columns, rows = grid
col_spacing, row_spacing = spacing
custom_container = Container()
properties = {
'type': 'custom',
'diameter': diameter,
'height': depth,
'total-liquid-volume': volume
}
for c in range(columns):
for r in range(rows):
... | def create(name, grid, spacing, diameter, depth, volume=0) | Creates a labware definition based on a rectangular gird, depth, diameter,
and spacing. Note that this function can only create labware with regularly
spaced wells in a rectangular format, of equal height, depth, and radius.
Irregular labware defintions will have to be made in other ways or modified
usi... | 3.62642 | 3.626118 | 1.000083 |
defn = new_labware.load_definition_by_name(container_name)
labware_id = defn['otId']
saved_offset = _look_up_offsets(labware_id)
container = Container()
log.info(f"Container name {container_name}")
container.properties['type'] = container_name
container.properties['otId'] = labware_id
... | def load_new_labware(container_name) | Load a labware in the new schema into a placeable.
:raises KeyError: If the labware name is not found | 5.136925 | 5.727786 | 0.896843 |
page_xml = d.dump_hierarchy(compressed=False, pretty=False).encode('utf-8')
dom = xml.dom.minidom.parseString(page_xml)
root = dom.documentElement
def travel(node):
# print(node)
if node.attributes is None:
return
json_node = parse_uiautomator_node(node)
... | def get_android_hierarchy(d) | Returns:
JSON object | 3.26378 | 3.344563 | 0.975847 |
try:
print("DEBUG: run code\n%s" % code)
env = os.environ.copy()
env['UIAUTOMATOR_DEBUG'] = 'true'
if device_url and device_url != 'default':
env['ATX_CONNECT_URL'] = tostr(device_url)
start_time = time.time()
sel... | def _run(self, device_url, code) | Thanks: https://gist.github.com/mosquito/e638dded87291d313717 | 3.748451 | 3.697407 | 1.013805 |
lines = ""
if isinstance(config, ConfigTree):
if len(config) == 0:
lines += '{}'
else:
lines += '{\n'
bet_lines = []
for key, item in config.items():
bet_lines.append('{indent}"{key}": {v... | def to_json(cls, config, compact=False, indent=2, level=0) | Convert HOCON input into a JSON output
:return: JSON string representation
:type return: basestring | 1.987991 | 1.988443 | 0.999773 |
lines = ""
if isinstance(config, ConfigTree):
if len(config) == 0:
lines += '{}'
else:
if level > 0: # don't display { at root level
lines += '{\n'
bet_lines = []
for key, item in confi... | def to_hocon(cls, config, compact=False, indent=2, level=0) | Convert HOCON input into a HOCON output
:return: JSON string representation
:type return: basestring | 2.037293 | 2.040754 | 0.998304 |
lines = ""
if isinstance(config, ConfigTree):
if len(config) > 0:
if level > 0:
lines += '\n'
bet_lines = []
for key, item in config.items():
bet_lines.append('{indent}{key}: {value}'.format(
... | def to_yaml(cls, config, compact=False, indent=2, level=0) | Convert HOCON input into a YAML output
:return: YAML string representation
:type return: basestring | 2.491854 | 2.488495 | 1.00135 |
def escape_value(value):
return value.replace('=', '\\=').replace('!', '\\!').replace('#', '\\#').replace('\n', '\\\n')
stripped_key_stack = [key.strip('"') for key in key_stack]
lines = []
if isinstance(config, ConfigTree):
for key, item in config.item... | def to_properties(cls, config, compact=False, indent=2, key_stack=[]) | Convert HOCON input into a .properties output
:return: .properties string representation
:type return: basestring
:return: | 1.865412 | 1.899309 | 0.982153 |
if input_file is None:
content = sys.stdin.read()
config = ConfigFactory.parse_string(content)
else:
config = ConfigFactory.parse_file(input_file)
res = cls.convert(config, output_format, indent, compact)
if output_file is None:
... | def convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False) | Convert to json, properties or yaml
:param input_file: input file, if not specified stdin
:param output_file: output file, if not specified stdout
:param output_format: json, properties or yaml
:return: json, properties or yaml string representation | 1.986338 | 2.109289 | 0.941709 |
try:
with codecs.open(filename, 'r', encoding=encoding) as fd:
content = fd.read()
return cls.parse_string(content, os.path.dirname(filename), resolve, unresolved_value)
except IOError as e:
if required:
raise e
... | def parse_file(cls, filename, encoding='utf-8', required=True, resolve=True, unresolved_value=DEFAULT_SUBSTITUTION) | Parse file
:param filename: filename
:type filename: basestring
:param encoding: file encoding
:type encoding: basestring
:param required: If true, raises an exception if can't load file
:type required: boolean
:param resolve: if true, resolve substitutions
... | 2.873873 | 3.36794 | 0.853303 |
socket_timeout = socket._GLOBAL_DEFAULT_TIMEOUT if timeout is None else timeout
try:
with contextlib.closing(urlopen(url, timeout=socket_timeout)) as fd:
content = fd.read() if use_urllib2 else fd.read().decode('utf-8')
return cls.parse_string(conten... | def parse_URL(cls, url, timeout=None, resolve=True, required=False, unresolved_value=DEFAULT_SUBSTITUTION) | Parse URL
:param url: url to parse
:type url: basestring
:param resolve: if true, resolve substitutions
:type resolve: boolean
:param unresolved_value: assigned value value to unresolved substitution.
If overriden with a default value, it will replace all unresolved valu... | 3.604635 | 4.017397 | 0.897256 |
return ConfigParser().parse(content, basedir, resolve, unresolved_value) | def parse_string(cls, content, basedir=None, resolve=True, unresolved_value=DEFAULT_SUBSTITUTION) | Parse URL
:param content: content to parse
:type content: basestring
:param resolve: If true, resolve substitutions
:param resolve: if true, resolve substitutions
:type resolve: boolean
:param unresolved_value: assigned value value to unresolved substitution.
If ... | 7.441035 | 6.996583 | 1.063524 |
def create_tree(value):
if isinstance(value, dict):
res = ConfigTree(root=root)
for key, child_value in value.items():
res.put(key, create_tree(child_value))
return res
if isinstance(value, list):
... | def from_dict(cls, dictionary, root=False) | Convert dictionary (and ordered dictionary) into a ConfigTree
:param dictionary: dictionary to convert
:type dictionary: dict
:return: Config object
:type return: Config | 2.547906 | 2.447891 | 1.040857 |
variable = substitution.variable
try:
return True, config.get(variable)
except ConfigMissingException:
# default to environment variable
value = os.environ.get(variable)
if value is None:
if substitution.optional:
... | def _resolve_variable(cls, config, substitution) | :param config:
:param substitution:
:return: (is_resolved, resolved_variable) | 3.25012 | 3.160759 | 1.028272 |
if isinstance(item, ConfigValues):
return item.get_substitutions()
substitutions = []
elements = []
if isinstance(item, ConfigTree):
elements = item.values()
elif isinstance(item, list):
elements = item
for child in elements:... | def _find_substitutions(cls, item) | Convert HOCON input into a JSON output
:return: JSON string representation
:type return: basestring | 3.182839 | 3.517231 | 0.904927 |
cleaned_token_list = [token for tokens in (token.tokens if isinstance(token, ConfigInclude) else [token]
for token in token_list if token != '')
for token in tokens]
config_list = ConfigList(cleaned_token_list)
... | def postParse(self, instring, loc, token_list) | Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return: | 5.670996 | 5.8266 | 0.973294 |
config_tree = ConfigTree(root=self.root)
for element in token_list:
expanded_tokens = element.tokens if isinstance(element, ConfigInclude) else [element]
for tokens in expanded_tokens:
# key, value1 (optional), ...
key = tokens[0].strip()... | def postParse(self, instring, loc, token_list) | Create ConfigTree from tokens
:param instring:
:param loc:
:param token_list:
:return: | 3.091343 | 3.056455 | 1.011415 |
for key, value in b.items():
# if key is in both a and b and both values are dictionary then merge it otherwise override it
if key in a and isinstance(a[key], ConfigTree) and isinstance(b[key], ConfigTree):
if copy_trees:
a[key] = a[key].copy(... | def merge_configs(a, b, copy_trees=False) | Merge config b into a
:param a: target config
:type a: ConfigTree
:param b: source config
:type b: ConfigTree
:return: merged config a | 2.663503 | 2.742239 | 0.971288 |
special_characters = '$}[]:=+#`^?!@*&.'
tokens = re.findall(r'"[^"]+"|[^{special_characters}]+'.format(special_characters=re.escape(special_characters)), string)
def contains_special_character(token):
return any((c in special_characters) for c in token)
return [tok... | def parse_key(string) | Split a key into path elements:
- a.b.c => a, b, c
- a."b.c" => a, QuotedKey("b.c") if . is any of the special characters: $}[]:=+#`^?!@*&.
- "a" => a
- a.b."c" => a, b, c (special case)
:param str:
:return: | 4.722183 | 2.939197 | 1.606624 |
self._put(ConfigTree.parse_key(key), value, append) | def put(self, key, value, append=False) | Put a value in the tree (dot separated)
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param value: value to put | 13.943568 | 18.618015 | 0.748929 |
return self._get(ConfigTree.parse_key(key), 0, default) | def get(self, key, default=UndefinedKey) | Get a value from the tree
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:return: value in the tree located at key | 13.835675 | 18.026104 | 0.767536 |
value = self.get(key, default)
if value is None:
return None
string_value = unicode(value)
if isinstance(value, bool):
string_value = string_value.lower()
return string_value | def get_string(self, key, default=UndefinedKey) | Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: string value
:type return: basestring | 3.009247 | 3.558051 | 0.845757 |
if default != UndefinedKey and key not in self:
return default
value = self.get(key, UndefinedKey)
lst = ConfigTree.parse_key(key)
parent = self.KEY_SEP.join(lst[0:-1])
child = lst[-1]
if parent:
self.get(parent).__delitem__(child)
... | def pop(self, key, default=UndefinedKey) | Remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise ConfigMissingException is raised
This method assumes the user wants to remove the last value in the chain so it parses via parse_key
and pops the last value out of the dict.
... | 3.974718 | 3.870209 | 1.027003 |
value = self.get(key, default)
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'int'".format(key=key, type=type(value).__name__)) | def get_int(self, key, default=UndefinedKey) | Return int representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: int
:return: int value
:type return: int | 3.286354 | 4.028067 | 0.815864 |
value = self.get(key, default)
try:
return float(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'float'".format(key=key, type=type(value).__name__)) | def get_float(self, key, default=UndefinedKey) | Return float representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: float
:return: float value
:type return: float | 3.26269 | 4.049028 | 0.805796 |
# String conversions as per API-recommendations:
# https://github.com/typesafehub/config/blob/master/HOCON.md#automatic-type-conversions
bool_conversions = {
None: None,
'true': True, 'yes': True, 'on': True,
'false': False, 'no': False, 'off': False... | def get_bool(self, key, default=UndefinedKey) | Return boolean representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: bool
:return: boolean value
:type return: bool | 3.532773 | 3.517603 | 1.004313 |
value = self.get(key, default)
if isinstance(value, list):
return value
elif isinstance(value, ConfigTree):
lst = []
for k, v in sorted(value.items(), key=lambda kv: kv[0]):
if re.match('^[1-9][0-9]*$|0', k):
lst.ap... | def get_list(self, key, default=UndefinedKey) | Return list representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: list
:return: list value
:type return: list | 2.962482 | 3.212624 | 0.922138 |
value = self.get(key, default)
if isinstance(value, dict):
return value
elif value is None:
return None
else:
raise ConfigException(
u"{key} has type '{type}' rather than 'config'".format(key=key, type=type(value).__name__)) | def get_config(self, key, default=UndefinedKey) | Return tree config representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: config
:return: config value
:type return: ConfigTree | 3.60595 | 4.260231 | 0.846421 |
if isinstance(config, ConfigTree):
result = ConfigTree.merge_configs(copy.deepcopy(config), copy.deepcopy(self))
else:
from . import ConfigFactory
result = ConfigTree.merge_configs(ConfigFactory.parse_file(config, resolve=False), copy.deepcopy(self))
... | def with_fallback(self, config, resolve=True) | return a new config with fallback on config
:param config: config or filename of the config to fallback on
:param resolve: resolve substitutions
:return: new config with fallback on config | 3.554115 | 3.241563 | 1.09642 |
def plain_value(v):
if isinstance(v, list):
return [plain_value(e) for e in v]
elif isinstance(v, ConfigTree):
return v.as_plain_ordered_dict()
else:
if isinstance(v, ConfigValues):
raise ConfigExcep... | def as_plain_ordered_dict(self) | return a deep copy of this config as a plain OrderedDict
The config tree should be fully resolved.
This is useful to get an object with no special semantics such as path expansion for the keys.
In particular this means that keys that contain dots are not surrounded with '"' in the plain Ordere... | 3.747191 | 3.319035 | 1.129 |
'''Label a single matplotlib line at position x
Parameters
----------
line : matplotlib.lines.Line
The line holding the label
x : number
The location in data unit of the label
label : string, optional
The label to set. This is inferred from the line by default
kwargs : ... | def labelLine(line, x, label=None, align=True, **kwargs) | Label a single matplotlib line at position x
Parameters
----------
line : matplotlib.lines.Line
The line holding the label
x : number
The location in data unit of the label
label : string, optional
The label to set. This is inferred from the line by default
kwargs : dict, o... | 2.194822 | 1.818878 | 1.20669 |
'''Label all lines with their respective legends.
Parameters
----------
lines : list of matplotlib lines
The lines to label
align : boolean, optional
If True, the label will be aligned with the slope of the line
at the location of the label. If False, they will be horizontal.
... | def labelLines(lines, align=True, xvals=None, **kwargs) | Label all lines with their respective legends.
Parameters
----------
lines : list of matplotlib lines
The lines to label
align : boolean, optional
If True, the label will be aligned with the slope of the line
at the location of the label. If False, they will be horizontal.
xval... | 3.087125 | 1.971478 | 1.565894 |
if param in self.config:
return self.config[param]
elif default is not None:
return default
else:
raise MissingParameter('ppolicy', param) | def get_param(self, param, default=None) | Get a parameter in config (handle default value)
:param param: name of the parameter to recover
:type param: string
:param default: the default value, raises an exception
if param is not in configuration and default
is None (which is the default value).
:type def... | 4.487262 | 5.235922 | 0.857015 |
# Load INI file into a dict
result = {}
for section in self.sections():
if section not in result:
result[section] = {}
for option in self.options(section):
value = self.get(section, option, raw=raw, vars=vars)
try:
value = cherrypy.lib... | def new_as_dict(self, raw=True, vars=None) | Convert an INI file to a dictionary | 3.012567 | 2.865602 | 1.051286 |
if username not in self.users:
return False
elif self.users[username][self.pwd_attr] == password:
return True
return False | def auth(self, username, password) | Check authentication against the backend
:param username: 'key' attribute of the user
:type username: string
:param password: password of the user
:type password: string
:rtype: boolean (True is authentication success, False otherwise) | 4.008017 | 4.273546 | 0.937867 |
username = attrs[self.key]
if username in self.users:
raise UserAlreadyExists(username, self.backend_name)
self.users[username] = attrs
self.users[username]['groups'] = set([]) | def add_user(self, attrs) | Add a user to the backend
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>})
.. warning:: raise UserAlreadyExists if user already exists | 4.252468 | 4.297264 | 0.989576 |
self._check_fix_users(username)
try:
del self.users[username]
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | def del_user(self, username) | Delete a user from the backend
:param username: 'key' attribute of the user
:type username: string | 6.088102 | 6.317607 | 0.963672 |
self._check_fix_users(username)
for attr in attrs:
self.users[username][attr] = attrs[attr] | def set_attrs(self, username, attrs) | set a list of attributes for a given user
:param username: 'key' attribute of the user
:type username: string
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>}) | 5.923415 | 5.84853 | 1.012804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.