signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def plot_feedback_params(hw_major_version, max_resistor_readings,<EOL>feedback_params, axis=None):
R1 = <NUM_LIT><EOL>if axis is None:<EOL><INDENT>fig = plt.figure()<EOL>axis = fig.add_subplot(<NUM_LIT>)<EOL><DEDENT>markers = MarkerStyle.filled_markers<EOL>def plot_resistor_params(args):<EOL><INDENT>resistor_index, x = args<EOL>try:<EOL><INDENT>color = next(axis._get_lines.color_cycle)<EOL><DEDENT>except: <EOL><INDE...
Plot the effective attenuation _(i.e., gain less than 1)_ of the control board measurements of high-voltage AC input according to: - AC signal frequency. - feedback resistor used _(varies based on amplitude of AC signal)_. Each high-voltage feedback resistor (unintentionally) forms a low-pass filter, resulting in a...
f7275:m4
def update_control_board_calibration(control_board, fitted_params):
<EOL>control_board.a0_series_resistance = fitted_params['<STR_LIT>'].values<EOL>control_board.a0_series_capacitance = fitted_params['<STR_LIT>'].values<EOL>
Update the control board with the specified fitted parameters.
f7275:m5
def savgol_filter(x, window_length, polyorder, deriv=<NUM_LIT:0>, delta=<NUM_LIT:1.0>, axis=-<NUM_LIT:1>, mode='<STR_LIT>', cval=<NUM_LIT:0.0>):
<EOL>x = np.ma.masked_invalid(pd.Series(x).interpolate())<EOL>try:<EOL><INDENT>ind = np.isfinite(x).nonzero()[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>x[ind:] = signal.savgol_filter(x[ind:], window_length, polyorder, deriv,<EOL>delta, axis, mode, cval)<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>return np.ma.maske...
Wrapper for the scipy.signal.savgol_filter function that handles Nan values. See: https://github.com/wheeler-microfluidics/dmf-control-board-firmware/issues/3 Returns ------- y : ndarray, same shape as `x` The filtered data.
f7276:m0
def serial_ports():
vid_pids = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']<EOL>return sd.comports(vid_pid=vid_pids, include_all=True)<EOL>
Returns ------- pandas.DataFrame Table of serial ports that match the USB vendor ID and product IDs for Arduino Mega2560 (from `official Arduino Windows driver`_). .. official Arduino Windows driver: https://github.com/arduino/Arduino/blob/27d1b8d9a190469e185af7484b52cc5884e7d731/build/windows/dist/drivers/ard...
f7276:m1
def feedback_results_to_measurements_frame(feedback_result):
index = pd.Index(feedback_result.time * <NUM_LIT>, name='<STR_LIT>')<EOL>df_feedback = pd.DataFrame(np.column_stack([feedback_result.V_fb,<EOL>feedback_result.V_hv,<EOL>feedback_result.fb_resistor,<EOL>feedback_result.hv_resistor]),<EOL>columns=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>'],<EOL>index=index)<...
Extract measured data from `FeedbackResults` instance into `pandas.DataFrame`.
f7276:m2
def feedback_results_to_impedance_frame(feedback_result):
index = pd.Index(feedback_result.time * <NUM_LIT>, name='<STR_LIT>')<EOL>df_feedback = pd.DataFrame(np.column_stack([feedback_result.V_actuation()<EOL>.filled(np.NaN),<EOL>feedback_result.capacitance()<EOL>.filled(np.NaN),<EOL>feedback_result.Z_device()<EOL>.filled(np.NaN)]),<EOL>columns=['<STR_LIT>', '<STR_LIT>',<EOL>...
Extract computed impedance data from `FeedbackResults` instance into `pandas.DataFrame`.
f7276:m3
def get_sketch_directory():
return os.path.join(package_path(), '<STR_LIT:src>', '<STR_LIT>')<EOL>
Return directory containing the `dmf_control_board` Arduino sketch.
f7276:m5
def get_includes():
return [get_sketch_directory()]<EOL>
Return directories containing the `dmf_control_board` Arduino header files. Modules that need to compile against `dmf_control_boad` should use this function to locate the appropriate include directories. Notes ===== For example: import dmf_control_board ... print ' '.join(['-I%s' % i for i in dmf_contro...
f7276:m6
def get_firmwares():
return OrderedDict([(board_dir.name, [f.abspath() for f in<EOL>board_dir.walkfiles('<STR_LIT>')])<EOL>for board_dir in<EOL>package_path().joinpath('<STR_LIT>').dirs()])<EOL>
Return `dmf_control_board` compiled Arduino hex file paths. This function may be used to locate firmware binaries that are available for flashing to [Arduino Mega2560][1] boards. [1]: http://arduino.cc/en/Main/arduinoBoardMega2560
f7276:m7
def get_sources():
return get_sketch_directory().files('<STR_LIT>')<EOL>
Return `dmf_control_board` Arduino source file paths. Modules that need to compile against `dmf_control_board` should use this function to locate the appropriate source files to compile. Notes ===== For example: import dmf_control_board ... print ' '.join(dmf_control_board.get_sources()) ...
f7276:m8
def safe_getattr(obj, attr, except_types):
try:<EOL><INDENT>return getattr(obj, attr, None)<EOL><DEDENT>except except_types:<EOL><INDENT>return None<EOL><DEDENT>
Execute `getattr` to retrieve the specified attribute from the provided object, returning a default value of `None` in the case where the attribute does not exist. In the case where an exception occurs during the `getattr` call, if the exception type is in `except_types`, ignore the exception and return `None`.
f7276:m9
@decorator.decorator<EOL>def safe_series_resistor_index_read(f, self, channel, resistor_index=None):
if resistor_index is not None:<EOL><INDENT>original_resistor_index = self.series_resistor_index(channel)<EOL>if resistor_index != original_resistor_index:<EOL><INDENT>self.set_series_resistor_index(channel, resistor_index)<EOL><DEDENT><DEDENT>value = f(self, channel)<EOL>if (resistor_index is not None and<EOL>resistor_...
This decorator checks the resistor-index from the current context _(i.e., the result of `self.series_resistor_index`)_. If the resistor-index specified by the `resistor_index` keyword argument is different than the current context value, the series-resistor-index is temporarily set to the value of `resistor_index` to ...
f7276:m10
@decorator.decorator<EOL>def safe_series_resistor_index_write(f, self, channel, value,<EOL>resistor_index=None):
if resistor_index is not None:<EOL><INDENT>original_resistor_index = self.series_resistor_index(channel)<EOL>if resistor_index != original_resistor_index:<EOL><INDENT>self.set_series_resistor_index(channel, resistor_index)<EOL><DEDENT><DEDENT>value = f(self, channel, value)<EOL>if (resistor_index is not None and<EOL>re...
This decorator checks the resistor-index from the current context _(i.e., the result of `self.series_resistor_index`)_. If the resistor-index specified by the `resistor_index` keyword argument is different than the current context value, the series-resistor-index is temporarily set to the value of `resistor_index` to ...
f7276:m11
@decorator.decorator<EOL>def remote_command(function, self, *args, **kwargs):
try:<EOL><INDENT>return function(self, *args, **kwargs)<EOL><DEDENT>except RuntimeError as exception:<EOL><INDENT>error_message = str(exception)<EOL>match = CRE_REMOTE_ERROR.match(error_message)<EOL>if match:<EOL><INDENT>command_code = int(match.group('<STR_LIT>'))<EOL>return_code = int(match.group('<STR_LIT>'))<EOL>ra...
Catch `RuntimeError` exceptions raised by remote control board firmware commands and re-raise as more specific `FirmwareError` exception type, which includes command code and return code.
f7276:m12
def _upgrade(self):
logging.debug('<STR_LIT>')<EOL>if hasattr(self, '<STR_LIT:version>'):<EOL><INDENT>version = Version.fromstring(self.version)<EOL><DEDENT>else:<EOL><INDENT>version = Version(<NUM_LIT:0>)<EOL><DEDENT>logging.debug('<STR_LIT>' %<EOL>(str(version), self.class_version))<EOL>if version > Version.fromstring(self.class_version...
Upgrade the serialized object if necessary. Raises: FutureVersionError: file was written by a future version of the software.
f7276:c3:m2
def V_total(self):
ind = mlab.find(self.hv_resistor >= <NUM_LIT:0>)<EOL>V1 = np.empty(self.hv_resistor.shape)<EOL>V1.fill(np.nan)<EOL>V1[ind] = compute_from_transfer_function(self.calibration.hw_version<EOL>.major, '<STR_LIT>',<EOL>V2=self.V_hv[ind], R1=<NUM_LIT>,<EOL>R2=self.calibration.R_hv<EOL>[self.hv_resistor[ind]],<EOL>C2=self.cali...
Compute the input voltage (i.e., ``V1``) based on the measured high-voltage feedback values for ``V2``, using the high-voltage transfer function. See also -------- :meth:`V_actuation` for diagram with ``V1`` and ``V2`` labelled.
f7276:c3:m5
def V_actuation(self):
if self.calibration.hw_version.major == <NUM_LIT:1>:<EOL><INDENT>return self.V_total() - np.array(self.V_fb)<EOL><DEDENT>else:<EOL><INDENT>return self.V_total()<EOL><DEDENT>
Return the voltage drop across the device (i.e., the ``Z1`` load) for each feedback measurement. Consider the feedback circuit diagrams below for the feedback measurement circuits of the two the control board hardware versions. .. code-block:: none # Hardware V1 # # Hardware V2 # ...
f7276:c3:m6
def Z_device(self, filter_order=None, window_size=None, tol=<NUM_LIT>):
ind = mlab.find(self.fb_resistor >= <NUM_LIT:0>)<EOL>Z1 = np.empty(self.fb_resistor.shape)<EOL>Z1.fill(np.nan)<EOL>Z1 = np.ma.masked_invalid(Z1)<EOL>R2 = self.calibration.R_fb[self.fb_resistor[ind]]<EOL>C2 = self.calibration.C_fb[self.fb_resistor[ind]]<EOL>Z1[ind] = compute_from_transfer_function(self.calibration.hw_ve...
Compute the impedance *(including resistive and capacitive load)* of the DMF device *(i.e., dielectric and droplet)*. See :func:`calibrate.compute_from_transfer_function` for details.
f7276:c3:m7
def force(self, Ly=None):
if self.calibration._c_drop:<EOL><INDENT>c_drop = self.calibration.c_drop(self.frequency)<EOL><DEDENT>else:<EOL><INDENT>c_drop = self.capacitance()[-<NUM_LIT:1>] / self.area<EOL><DEDENT>if self.calibration._c_filler:<EOL><INDENT>c_filler = self.calibration.c_filler(self.frequency)<EOL><DEDENT>else:<EOL><INDENT>c_filler...
Estimate the applied force (in Newtons) on a drop according to the electromechanical model [1]. Ly is the length of the actuated electrode along the y-axis (perpendicular to the direction of motion) in milimeters. By default, use the square root of the actuated electrode area, i.e., ...
f7276:c3:m8
def capacitance(self, filter_order=None, window_size=None, tol=<NUM_LIT>):
C = np.ma.masked_invalid(<NUM_LIT:1.0> / (<NUM_LIT> * math.pi * self.frequency *<EOL>self.Z_device(filter_order=filter_order,<EOL>window_size=window_size, tol=tol)))<EOL>C.fill_value = np.nan<EOL>C.data[C.mask] = C.fill_value<EOL>return C<EOL>
Compute the capacitance of the DMF device _(i.e., dielectric and droplet)_ based on the computed impedance value. Note: this assumes impedance is purely capacitive load. TODO: Is this assumption ok?
f7276:c3:m10
def x_position(self, filter_order=None, window_size=None, tol=<NUM_LIT>,<EOL>Lx=None):
if self.calibration._c_drop:<EOL><INDENT>c_drop = self.calibration.c_drop(self.frequency)<EOL><DEDENT>else:<EOL><INDENT>c_drop = self.capacitance()[-<NUM_LIT:1>] / self.area<EOL><DEDENT>if self.calibration._c_filler:<EOL><INDENT>c_filler = self.calibration.c_filler(self.frequency)<EOL><DEDENT>else:<EOL><INDENT>c_filler...
Calculate $x$-position according to: __ | C | ╲╱ a ⋅ | - - c_f | | a | x = ────────────── c_d - c_f where: - $C$ is the measured capacitance. - $c_f$ is the capacitance of the filler medium per unit area _(e.g., air)_. - $c_d$ is the capacitance of an ele...
f7276:c3:m11
def mean_velocity(self, tol=<NUM_LIT>, Lx=None):
dx = None<EOL>dt = None<EOL>p = None<EOL>ind = None<EOL>t_end = None<EOL>if self.area == <NUM_LIT:0>:<EOL><INDENT>return dict(dx=dx, dt=dt, p=p, ind=ind, t_end=t_end)<EOL><DEDENT>x = self.x_position(Lx=Lx)<EOL>ind_start = mlab.find(x.mask==False)[<NUM_LIT:0>]<EOL>ind_last = mlab.find(x.mask==False)[-<NUM_LIT:1>]<EOL>if...
Calculate the mean velocity for a step (mm/ms which is equivalent to m/s). Fit a line to the capacitance data and get the slope.
f7276:c3:m12
def to_frame(self, filter_order=<NUM_LIT:3>):
window_size = self._get_window_size()<EOL>L = np.sqrt(self.area)<EOL>velocity_results = self.mean_velocity(Lx=L)<EOL>mean_velocity = None<EOL>peak_velocity = None<EOL>dx = <NUM_LIT:0><EOL>dt = <NUM_LIT:0><EOL>dxdt = np.zeros(len(self.time))<EOL>dxdt_filtered = np.zeros(len(self.time))<EOL>if filter_order and window_siz...
Convert data to a `pandas.DataFrame`. Parameters ---------- filter_order : int Filter order to use when filtering Z_device, capacitance, x_position, and dxdt. Data is filtered using a Savitzky-Golay filter with a window size that is adjusted based on the mean velocity of the drop (see _get_window_size). R...
f7276:c3:m15
def _upgrade(self):
logging.debug("<STR_LIT>")<EOL>version = Version.fromstring(self.version)<EOL>logging.debug('<STR_LIT>',<EOL>str(version), self.class_version)<EOL>if version > Version.fromstring(self.class_version):<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>raise FutureVersionError(Version.fromstring(self.class_version),<EOL>version)...
Upgrade the serialized object if necessary. Raises: FutureVersionError: file was written by a future version of the software.
f7276:c4:m2
def C_drop(self, frequency):
logger.warning('<STR_LIT>')<EOL>return self.c_drop(frequency)<EOL>
This function has been depreciated. It has been replaced by the lowercase version c_drop, which signifies that the capacitance is normalized per unit area (i.e., units are F/mm^2).
f7276:c5:m1
def C_filler(self, frequency):
logger.warning('<STR_LIT>')<EOL>return self.c_filler(frequency)<EOL>
This function has been depreciated. It has been replaced by the lowercase version c_filler, which signifies that the capacitance is normalized per unit area (i.e., units are F/mm^2).
f7276:c5:m2
def c_drop(self, frequency):
try:<EOL><INDENT>return np.interp(frequency,<EOL>self._c_drop['<STR_LIT>'],<EOL>self._c_drop['<STR_LIT>']<EOL>)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return self._c_drop<EOL>
Capacitance of an electrode covered in liquid, normalized per unit area (i.e., units are F/mm^2).
f7276:c5:m3
def c_filler(self, frequency):
try:<EOL><INDENT>return np.interp(frequency,<EOL>self._c_filler['<STR_LIT>'],<EOL>self._c_filler['<STR_LIT>']<EOL>)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return self._c_filler<EOL>
Capacitance of an electrode covered in filler media (e.g., air or oil), normalized per unit area (i.e., units are F/mm^2).
f7276:c5:m4
def __getstate__(self):
out = copy.deepcopy(self.__dict__)<EOL>for k, v in list(out.items()):<EOL><INDENT>if isinstance(v, np.ndarray):<EOL><INDENT>out[k] = v.tolist()<EOL><DEDENT><DEDENT>return out<EOL>
Convert numpy arrays to lists for serialization
f7276:c5:m5
def __setstate__(self, state):
<EOL>for k in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if k in state:<EOL><INDENT>state['<STR_LIT:_>' + k.lower()] = state[k]<EOL>del state[k]<EOL><DEDENT><DEDENT>for k in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if k in state:<EOL><INDENT>state[k.lower()] = state[k]<EOL>del state[k]<EOL><DEDENT><DEDENT>self.__dict__ = s...
Convert lists to numpy arrays after loading serialized object
f7276:c5:m6
def _upgrade(self):
logging.debug("<STR_LIT>")<EOL>version = Version.fromstring(self.version)<EOL>logging.debug('<STR_LIT>',<EOL>str(version), self.class_version)<EOL>if version > Version.fromstring(self.class_version):<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>raise FutureVersionError(Version.fromstring(self.class_version),<EOL>version)...
Upgrade the serialized object if necessary. Raises: FutureVersionError: file was written by a future version of the software.
f7276:c5:m7
def force_to_voltage(self, force, frequency):
c_drop = self.calibration.c_drop(frequency)<EOL>if self.calibration._c_filler:<EOL><INDENT>c_filler = self.calibration.c_filler(frequency)<EOL><DEDENT>else:<EOL><INDENT>c_filler = <NUM_LIT:0><EOL><DEDENT>return np.sqrt(force * <NUM_LIT>/ (<NUM_LIT:0.5> * (c_drop - c_filler)))<EOL>
Convert a force in uN/mm to voltage. Parameters ---------- force : float Force in **uN/mm**. frequency : float Actuation frequency. Returns ------- float Actuation voltage to apply :data:`force` at an actuation frequency of :data:`frequency`.
f7276:c6:m1
@safe_series_resistor_index_read<EOL><INDENT>def series_capacitance(self, channel, resistor_index=None):<DEDENT>
if resistor_index is None:<EOL><INDENT>resistor_index = self.series_resistor_index(channel)<EOL><DEDENT>value = self._series_capacitance(channel)<EOL>try:<EOL><INDENT>if channel == <NUM_LIT:0>:<EOL><INDENT>self.calibration.C_hv[resistor_index] = value<EOL><DEDENT>else:<EOL><INDENT>self.calibration.C_fb[resistor_index] ...
Parameters ---------- channel : int Analog channel index. resistor_index : int, optional Series resistor channel index. If :data:`resistor_index` is not specified, the resistor-index from the current context _(i.e., the result of :attr:`series_resistor_index`)_ is used. Otherwise, the series-r...
f7276:c6:m2
@safe_series_resistor_index_read<EOL><INDENT>def series_resistance(self, channel, resistor_index=None):<DEDENT>
if resistor_index is None:<EOL><INDENT>resistor_index = self.series_resistor_index(channel)<EOL><DEDENT>value = self._series_resistance(channel)<EOL>try:<EOL><INDENT>if channel == <NUM_LIT:0>:<EOL><INDENT>self.calibration.R_hv[resistor_index] = value<EOL><DEDENT>else:<EOL><INDENT>self.calibration.R_fb[resistor_index] =...
Parameters ---------- channel : int Analog channel index. resistor_index : int, optional Series resistor channel index. If :data:`resistor_index` is not specified, the resistor-index from the current context _(i.e., the result of :attr:`series_resistor_index`)_ is used. Otherwise, the series-r...
f7276:c6:m3
@safe_series_resistor_index_write<EOL><INDENT>def set_series_capacitance(self, channel, value, resistor_index=None):<DEDENT>
if resistor_index is None:<EOL><INDENT>resistor_index = self.series_resistor_index(channel)<EOL><DEDENT>try:<EOL><INDENT>if channel == <NUM_LIT:0>:<EOL><INDENT>self.calibration.C_hv[resistor_index] = value<EOL><DEDENT>else:<EOL><INDENT>self.calibration.C_fb[resistor_index] = value<EOL><DEDENT><DEDENT>except:<EOL><INDEN...
Set the current series capacitance value for the specified channel. Parameters ---------- channel : int Analog channel index. value : float Series capacitance value. resistor_index : int, optional Series resistor channel index. If :data:`resistor_index` is not specified, the resistor-index from th...
f7276:c6:m4
@safe_series_resistor_index_write<EOL><INDENT>def set_series_resistance(self, channel, value, resistor_index=None):<DEDENT>
if resistor_index is None:<EOL><INDENT>resistor_index = self.series_resistor_index(channel)<EOL><DEDENT>try:<EOL><INDENT>if channel == <NUM_LIT:0>:<EOL><INDENT>self.calibration.R_hv[resistor_index] = value<EOL><DEDENT>else:<EOL><INDENT>self.calibration.R_fb[resistor_index] = value<EOL><DEDENT><DEDENT>except:<EOL><INDEN...
Set the current series resistance value for the specified channel. Parameters ---------- channel : int Analog channel index. value : float Series resistance value. resistor_index : int, optional Series resistor channel index. If :data:`resistor_index` is not specified, the resistor-index from the ...
f7276:c6:m5
@remote_command<EOL><INDENT>def connect(self, port=None, baud_rate=<NUM_LIT>):<DEDENT>
if isinstance(port, (str,)):<EOL><INDENT>ports = [port]<EOL><DEDENT>else:<EOL><INDENT>ports = port<EOL><DEDENT>if not ports:<EOL><INDENT>ports = serial_ports().index.tolist()<EOL>if not ports:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT><DEDENT>for comport_i in ports:<EOL><INDENT>if self.connected():<EOL><INDENT...
Parameters ---------- port : str or list-like, optional Port (or list of ports) to try to connect to as a DMF Control Board. baud_rate : int, optional Returns ------- str Port DMF control board was connected on. Raises ------ RuntimeError If connection could not be established. IOError If no ports...
f7276:c6:m7
def persistent_write(self, address, byte, refresh_config=False):
self._persistent_write(address, byte)<EOL>if refresh_config:<EOL><INDENT>self.load_config(False)<EOL><DEDENT>
Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. refresh_config : bool, optional Is ``True``, :meth:`load_config()` is called afterward to refresh the configuration settings.
f7276:c6:m10
def persistent_read_multibyte(self, address, count=None, dtype=np.uint8):
nbytes = np.dtype(dtype).itemsize<EOL>if count is not None:<EOL><INDENT>nbytes *= count<EOL><DEDENT>data_bytes = np.array([self.persistent_read(address + i)<EOL>for i in range(nbytes)], dtype=np.uint8)<EOL>result = data_bytes.view(dtype)<EOL>if count is None:<EOL><INDENT>return result[<NUM_LIT:0>]<EOL><DEDENT>return re...
Read a chunk of data from persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). count : int, optional Number of values to read. If not set, read a single value of the specified :data:`dtype`. dtype : numpy.dtype, optional The type of the value(s) to read. ...
f7276:c6:m11
def persistent_write_multibyte(self, address, data, refresh_config=False):
for i, byte in enumerate(data.view(np.uint8)):<EOL><INDENT>self.persistent_write(address + i, int(byte))<EOL><DEDENT>if refresh_config:<EOL><INDENT>self.load_config(False)<EOL><DEDENT>
Write multiple bytes to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). data : numpy.array Data to write. refresh_config : bool, optional Is ``True``, :meth:`load_config()` is called afterward to refresh the configuration settings.
f7276:c6:m12
@remote_command<EOL><INDENT>def measure_impedance(self, sampling_window_ms, n_sampling_windows,<EOL>delay_between_windows_ms, interleave_samples, rms,<EOL>state):<DEDENT>
state_ = uint8_tVector()<EOL>for i in range(<NUM_LIT:0>, len(state)):<EOL><INDENT>state_.append(int(state[i]))<EOL><DEDENT>buffer = np.array(Base.measure_impedance(self,<EOL>sampling_window_ms,<EOL>n_sampling_windows,<EOL>delay_between_windows_ms,<EOL>interleave_samples,<EOL>rms,<EOL>state_))<EOL>return self.measure_im...
Measure voltage across load of each of the following control board feedback circuits: - Reference _(i.e., attenuated high-voltage amplifier output)_. - Load _(i.e., voltage across DMF device)_. The measured voltage _(i.e., ``V2``)_ can be used to compute the impedance of the measured load, the input voltage _(i.e.,...
f7276:c6:m44
@remote_command<EOL><INDENT>def sweep_channels(self,<EOL>sampling_window_ms,<EOL>n_sampling_windows_per_channel,<EOL>delay_between_windows_ms,<EOL>interleave_samples,<EOL>rms,<EOL>channel_mask):<DEDENT>
channel_cumsum = np.cumsum(channel_mask)<EOL>n_channels_in_mask = channel_cumsum[-<NUM_LIT:1>]<EOL>max_channels_per_call = (self.MAX_PAYLOAD_LENGTH - <NUM_LIT:4>*<NUM_LIT:4>) /(<NUM_LIT:3>*<NUM_LIT:2>) / n_sampling_windows_per_channel<EOL>self._channel_mask_cache = np.array(channel_mask)<EOL>buffer = np.zeros(<NUM_LIT:...
Measure voltage across load of each of the following control board feedback circuits: - Reference _(i.e., attenuated high-voltage amplifier output)_. - Load _(i.e., voltage across DMF device)_. For each channel in the channel mask. The measured voltage _(i.e., ``V2``)_ can be used to compute the impedance of the me...
f7276:c6:m45
@remote_command<EOL><INDENT>def sweep_channels_slow(self, sampling_window_ms, n_sampling_windows,<EOL>delay_between_windows_ms, interleave_samples,<EOL>use_rms, channel_mask):<DEDENT>
channel_count = len(channel_mask)<EOL>scan_count = sum(channel_mask)<EOL>frames = []<EOL>print('<STR_LIT>')<EOL>scan_count_i = <NUM_LIT:0><EOL>for channel_i, state_i in enumerate(channel_mask):<EOL><INDENT>if state_i:<EOL><INDENT>scan_count_i += <NUM_LIT:1><EOL>print('<STR_LIT>'.format(channel_i,<EOL>scan_count_i,<EOL>...
Measure voltage across load of each of the following control board feedback circuits: - Reference _(i.e., attenuated high-voltage amplifier output)_. - Load _(i.e., voltage across DMF device)_. For each channel in the channel mask. The measured voltage _(i.e., ``V2``)_ can be used to compute the impedance of the me...
f7276:c6:m46
@remote_command<EOL><INDENT>def i2c_scan(self):<DEDENT>
return np.array(Base.i2c_scan(self))<EOL>
Returns ------- numpy.array Array of addresses of I2C devices responding to I2C scan.
f7276:c6:m47
@remote_command<EOL><INDENT>def i2c_write(self, address, data):<DEDENT>
data_ = uint8_tVector()<EOL>for i in range(<NUM_LIT:0>, len(data)):<EOL><INDENT>data_.append(int(data[i]))<EOL><DEDENT>Base.i2c_write(self, address, data_)<EOL>
Parameters ---------- address : int Address of I2C device. data : array-like Array of bytes to send to device.
f7276:c6:m48
def read_all_series_channel_values(self, f, channel):
values = []<EOL>channel_max_param_count = [<NUM_LIT:3>, <NUM_LIT:5>]<EOL>for i in range(channel_max_param_count[channel]):<EOL><INDENT>try:<EOL><INDENT>values.append(f(channel, i))<EOL><DEDENT>except RuntimeError:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return values<EOL>
Return all values for the specified channel of the type corresponding to the function `f`, where `f` is either `self.series_resistance` or `self.series_capacitance`.
f7276:c6:m76
def write_all_series_channel_values(self, read_f, write_f, channel,<EOL>values):
<EOL>values = copy.deepcopy(values)<EOL>original_values = self.read_all_series_channel_values(read_f, channel)<EOL>assert(len(values) == len(original_values))<EOL>for i in range(len(original_values)):<EOL><INDENT>if values[i] != original_values[i]:<EOL><INDENT>write_f(channel, values[i], i)<EOL><DEDENT><DEDENT>
Return all values for the specified channel of the type corresponding to the function `f`, where `f` is either `self.series_resistance` or `self.series_capacitance`.
f7276:c6:m77
def plot_capacitance_summary(data, fig=None, color_map=mcm.Reds_r,<EOL>vmax=<NUM_LIT>, <EOL>reduce_func='<STR_LIT>'):
<EOL>channel_groups = data['<STR_LIT>'].groupby('<STR_LIT>')<EOL>channel_capacitance = getattr(channel_groups['<STR_LIT>'], reduce_func)()<EOL>vmax = max(<NUM_LIT> * (channel_capacitance.median() + channel_capacitance.min()),<EOL>vmax)<EOL>grid = GridSpec(<NUM_LIT:2>, <NUM_LIT:8>)<EOL>if fig is None:<EOL><INDENT>fig = ...
| ---------- | ------------------------- | | | Capacitance of | | Device | channels (index order) | | drawing | ------------------------- | | | Capacitance of | | | channels (C order) | | ---------- | ------------------------- |
f7277:m2
def plot_channel_sweep(proxy, start_channel):
test_loads = TEST_LOADS.copy()<EOL>test_loads.index += start_channel<EOL>results = sweep_channels(proxy, test_loads)<EOL>normalized_measurements = (results['<STR_LIT>']<EOL>/ results['<STR_LIT>'])<EOL>fig, axis = plt.subplots(figsize=(<NUM_LIT:10>, <NUM_LIT:8>))<EOL>axis.bar(normalized_measurements.index - <NUM_LIT>, n...
Parameters ---------- proxy : DMFControlBoard start_channel : int Channel number from which to start a channel sweep (should be a multiple of 40, e.g., 0, 40, 80). Returns ------- pandas.DataFrame See description of return of :func:`sweep_channels`.
f7281:m1
def parse_args(args=None):
from argparse import ArgumentParser<EOL>if args is None:<EOL><INDENT>args = sys.argv<EOL><DEDENT>parser = ArgumentParser(description='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>args = parser.parse_args()<EOL>return args<EOL>
Parses arguments, returns (options, args).
f7282:m1
def makename(package, module):
<EOL>if package:<EOL><INDENT>name = package<EOL>if module:<EOL><INDENT>name += '<STR_LIT:.>' + module<EOL><DEDENT><DEDENT>else:<EOL><INDENT>name = module<EOL><DEDENT>return name<EOL>
Join package and module with a dot.
f7283:m0
def write_file(name, text, opts):
if opts.dryrun:<EOL><INDENT>return<EOL><DEDENT>fname = os.path.join(opts.destdir, "<STR_LIT>" % (name, opts.suffix))<EOL>if not opts.force and os.path.isfile(fname):<EOL><INDENT>print('<STR_LIT>' % fname)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % fname)<EOL>f = open(fname, '<STR_LIT:w>')<EOL>f.write(text)<EOL>f...
Write the output file for module/package <name>.
f7283:m1
def format_heading(level, text):
underlining = ['<STR_LIT:=>', '<STR_LIT:->', '<STR_LIT>', ][level-<NUM_LIT:1>] * len(text)<EOL>return '<STR_LIT>' % (text, underlining)<EOL>
Create a heading of <level> [1, 2 or 3 supported].
f7283:m2
def format_directive(module, package=None):
directive = '<STR_LIT>' % makename(package, module)<EOL>for option in OPTIONS:<EOL><INDENT>directive += '<STR_LIT>' % option<EOL><DEDENT>return directive<EOL>
Create the automodule directive and add the options.
f7283:m3
def create_module_file(package, module, opts):
text = format_heading(<NUM_LIT:1>, '<STR_LIT>' % module)<EOL>text += format_heading(<NUM_LIT:2>, '<STR_LIT>' % module)<EOL>text += format_directive(module, package)<EOL>write_file(makename(package, module), text, opts)<EOL>
Build the text of the file and write the file.
f7283:m4
def create_package_file(root, master_package, subroot, py_files, opts, subs):
package = os.path.split(root)[-<NUM_LIT:1>]<EOL>text = format_heading(<NUM_LIT:1>, '<STR_LIT>' % package)<EOL>for py_file in py_files:<EOL><INDENT>if shall_skip(os.path.join(root, py_file)):<EOL><INDENT>continue<EOL><DEDENT>is_package = py_file == INIT<EOL>py_file = os.path.splitext(py_file)[<NUM_LIT:0>]<EOL>py_path = ...
Build the text of the file and write the file.
f7283:m5
def create_modules_toc_file(master_package, modules, opts, name='<STR_LIT>'):
text = format_heading(<NUM_LIT:1>, '<STR_LIT>' % opts.header)<EOL>text += '<STR_LIT>'<EOL>text += '<STR_LIT>' % opts.maxdepth<EOL>modules.sort()<EOL>prev_module = '<STR_LIT>'<EOL>for module in modules:<EOL><INDENT>if module.startswith(prev_module + '<STR_LIT:.>'):<EOL><INDENT>continue<EOL><DEDENT>prev_module = module<E...
Create the module's index.
f7283:m6
def shall_skip(module):
<EOL>return os.path.getsize(module) < <NUM_LIT:3><EOL>
Check if we want to skip this module.
f7283:m7
def recurse_tree(path, excludes, opts):
<EOL>path = os.path.abspath(path)<EOL>if INIT in os.listdir(path):<EOL><INDENT>package_name = path.split(os.path.sep)[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>package_name = None<EOL><DEDENT>toc = []<EOL>tree = os.walk(path, False)<EOL>for root, subs, files in tree:<EOL><INDENT>py_files = sorted([f for f in files i...
Look for every file in the directory tree and create the corresponding ReST files.
f7283:m8
def normalize_excludes(rootpath, excludes):
sep = os.path.sep<EOL>f_excludes = []<EOL>for exclude in excludes:<EOL><INDENT>if not os.path.isabs(exclude) and not exclude.startswith(rootpath):<EOL><INDENT>exclude = os.path.join(rootpath, exclude)<EOL><DEDENT>if not exclude.endswith(sep):<EOL><INDENT>exclude += sep<EOL><DEDENT>f_excludes.append(exclude)<EOL><DEDENT...
Normalize the excluded directory list: * must be either an absolute path or start with rootpath, * otherwise it is joined with rootpath * with trailing slash
f7283:m9
def is_excluded(root, excludes):
sep = os.path.sep<EOL>if not root.endswith(sep):<EOL><INDENT>root += sep<EOL><DEDENT>for exclude in excludes:<EOL><INDENT>if root.startswith(exclude):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
Check if the directory is in the exclude list. Note: by having trailing slashes, we avoid common prefix issues, like e.g. an exlude "foo" also accidentally excluding "foobar".
f7283:m10
def main():
parser = optparse.OptionParser(usage="""<STR_LIT>""")<EOL>parser.add_option("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>", dest="<STR_LIT>", help="<STR_LIT>", default="<STR_LIT>")<EOL>parser.add_option("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>", dest="<STR_LIT>", help="<STR_LIT>", default="<STR_LIT>")<EOL>...
Parse and check the command line arguments.
f7283:m11
@register.filter<EOL>def get_page_count(pdf_file_path):
pdf = PdfFileReader(file(pdf_file_path, "<STR_LIT:rb>"))<EOL>return pdf.getNumPages()<EOL>
Returns the number of pages of a given pdf file. Usage:: {% load cmsplugin_pdf_tags %} Pages: {{ pdf_plugin.file.path|get_page_count }}
f7294:m0
def save(self, *args, **kwargs):
<EOL>img = Image(filename=self.file.path + '<STR_LIT>')<EOL>filename = os.path.basename(self.file.path).split('<STR_LIT:.>')[:-<NUM_LIT:1>]<EOL>if type(filename) == list:<EOL><INDENT>filename = '<STR_LIT>'.join(filename)<EOL><DEDENT>image_dir = os.path.join(<EOL>django_settings.MEDIA_ROOT, UPLOAD_TO_DIR)<EOL>if not os....
Customized to generate an image from the pdf file.
f7300:c0:m1
def read(*paths):
basedir = os.path.dirname(__file__)<EOL>fullpath = os.path.join(basedir, *paths)<EOL>contents = io.open(fullpath, encoding='<STR_LIT:utf-8>').read().strip()<EOL>return contents<EOL>
Read a text file.
f7346:m0
def create_cells(headers, schema_fields, values=None, row_number=None):
fillvalue = '<STR_LIT>'<EOL>is_header_row = (values is None)<EOL>cells = []<EOL>iterator = zip_longest(headers, schema_fields, values or [], fillvalue=fillvalue)<EOL>for column_number, (header, field, value) in enumerate(iterator, start=<NUM_LIT:1>):<EOL><INDENT>if header == fillvalue:<EOL><INDENT>header = None<EOL><DE...
Create list of cells from headers, fields and values. Args: headers (List[str]): The headers values. schema_fields (List[tableschema.field.Field]): The tableschema fields. values (List[Any], optional): The cells values. If not specified, the created cells will have t...
f7353:m0
@click.group(cls=DefaultGroup, default='<STR_LIT>', default_if_no_args=True)<EOL>@click.version_option(goodtables.__version__, message='<STR_LIT>')<EOL>def cli():
pass<EOL>
Tabular files validator. There are two categories of validation checks available: * Structural checks: ensure there are no empty rows, no blank headers, etc. * Content checks: ensure the values have the correct types (e.g. string), their format is valid (e.g. e-mail), and they respect some constrai...
f7354:m0
@cli.command()<EOL>@click.argument('<STR_LIT>', type=click.Path(), nargs=-<NUM_LIT:1>, required=True)<EOL>@click.option(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>type=click.File('<STR_LIT:w>'),<EOL>default='<STR_LIT:->',<EOL>help='<STR_LIT>'<EOL>)<EOL>def init(paths, output, **kwargs):
dp = goodtables.init_datapackage(paths)<EOL>click.secho(<EOL>json_module.dumps(dp.descriptor, indent=<NUM_LIT:4>),<EOL>file=output<EOL>)<EOL>exit(dp.valid)<EOL>
Init data package from list of files. It will also infer tabular data's schemas from their contents.
f7354:m2
def validate(source, **options):
source, options, inspector_settings = _parse_arguments(source, **options)<EOL>inspector = Inspector(**inspector_settings)<EOL>report = inspector.inspect(source, **options)<EOL>return report<EOL>
Validates a source file and returns a report. Args: source (Union[str, Dict, List[Dict], IO]): The source to be validated. It can be a local file path, URL, dict, list of dicts, or a file-like object. If it's a list of dicts and the `preset` is "nested", each of the dict...
f7379:m0
def init_datapackage(resource_paths):
dp = datapackage.Package({<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>})<EOL>for path in resource_paths:<EOL><INDENT>dp.infer(path)<EOL><DEDENT>return dp<EOL>
Create tabular data package with resources. It will also infer the tabular resources' schemas. Args: resource_paths (List[str]): Paths to the data package resources. Returns: datapackage.Package: The data package.
f7379:m1
def preset(name):
def decorator(func):<EOL><INDENT>registry.register_preset(func, name)<EOL>return func<EOL><DEDENT>return decorator<EOL>
https://github.com/frictionlessdata/goodtables-py#custom-presets
f7380:m0
def check(name, type=None, context=None, position=None):
def decorator(func):<EOL><INDENT>registry.register_check(func, name, type, context, position)<EOL>return func<EOL><DEDENT>return decorator<EOL>
https://github.com/frictionlessdata/goodtables-py#custom-checks
f7380:m1
def _clean_empty(d):
if not isinstance(d, (dict, list)):<EOL><INDENT>return d<EOL><DEDENT>if isinstance(d, list):<EOL><INDENT>return [v for v in (_clean_empty(v) for v in d) if v is not None]<EOL><DEDENT>return {<EOL>k: v for k, v in<EOL>((k, _clean_empty(v)) for k, v in d.items())<EOL>if v is not None<EOL>}<EOL>
Remove None values from a dict.
f7382:m3
def __init__(self,<EOL>checks=['<STR_LIT>', '<STR_LIT>'],<EOL>skip_checks=[],<EOL>infer_schema=False,<EOL>infer_fields=False,<EOL>order_fields=False,<EOL>error_limit=config.DEFAULT_ERROR_LIMIT,<EOL>table_limit=config.DEFAULT_TABLE_LIMIT,<EOL>row_limit=config.DEFAULT_ROW_LIMIT):
<EOL>self.__checks = checks<EOL>self.__skip_checks = skip_checks<EOL>self.__infer_schema = infer_schema<EOL>self.__infer_fields = infer_fields<EOL>self.__order_fields = order_fields<EOL>parse_limit = lambda num: float('<STR_LIT>') if (num < <NUM_LIT:0>) else num <EOL>self.__error_limit = parse_limit(error_limit)<EOL>s...
https://github.com/frictionlessdata/goodtables-py#inspector
f7382:c0:m0
def inspect(self, source, preset=None, **options):
<EOL>start = datetime.datetime.now()<EOL>preset = self.__get_source_preset(source, preset)<EOL>if preset == '<STR_LIT>':<EOL><INDENT>options['<STR_LIT>'] = self.__presets<EOL>for s in source:<EOL><INDENT>if s.get('<STR_LIT>') is None:<EOL><INDENT>s['<STR_LIT>'] = self.__get_source_preset(s['<STR_LIT:source>'])<EOL><DED...
https://github.com/frictionlessdata/goodtables-py#inspector
f7382:c0:m1
def _masquerade(origin: str, orig: ServiceDefn, new: ServiceDefn, **map: str) -> str:
origin: ParseResult = urlparse(origin)<EOL>prev_maps = {}<EOL>if origin.query:<EOL><INDENT>prev_maps = {k: v for k, v in parse_qsl(origin.query)}<EOL><DEDENT>r_args = {}<EOL>for new_k, orig_k in map.items():<EOL><INDENT>assert new_k in new.rpcs, [new_k, new.rpcs]<EOL>assert orig_k in orig.rpcs, [orig_k, orig.rpcs]<EOL>...
build an origin URL such that the orig has all of the mappings to new defined by map
f7388:m9
def masquerade(origin: str, orig: Type[TA], new: Type[TB], **map: str) -> str:
return _masquerade(origin, cache_get(orig), cache_get(new), **map)<EOL>
Make ``orig`` appear as new
f7388:m10
def popen(fn, *args, **kwargs) -> subprocess.Popen:
args = popen_encode(fn, *args, **kwargs)<EOL>logging.getLogger(__name__).debug('<STR_LIT>', args)<EOL>p = subprocess.Popen(args)<EOL>return p<EOL>
Please ensure you're not killing the process before it had started properly :param fn: :param args: :param kwargs: :return:
f7389:m5
@rpc(exc=True)<EOL><INDENT>def ep(self, exc: Exception) -> bool:<DEDENT>
if not isinstance(exc, ConnectionAbortedError):<EOL><INDENT>return False<EOL><DEDENT>if len(exc.args) != <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>origin, reason = exc.args<EOL>logging.getLogger(__name__).warning('<STR_LIT>')<EOL>return True<EOL>
Return False if the exception had not been handled gracefully
f7405:c1:m0
def _insert_ordered(insert_to, insert_val, insert_item, ord_col, cmp_fn=lambda x: x):
idx = ord_col.index(cmp_fn(insert_item))<EOL>return insert_to[:idx] + [insert_val] + insert_to[idx:]<EOL>
:param insert_to: ``len(insert_to) = len(ord_col) - 1`` :param insert_val: value to insert into ``insert_to`` :param insert_item: value inserted into ``ord_col`` :param ord_col: collection of ``insert_item`` ordered by cmp_fn :param cmp_fn: :return:
f7408:m2
def trc(postfix: Optional[str] = None, *, depth=<NUM_LIT:1>) -> logging.Logger:
x = inspect.stack()[depth]<EOL>code = x[<NUM_LIT:0>].f_code<EOL>func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][<NUM_LIT:0>]<EOL>mod = inspect.getmodule(x.frame)<EOL>parts = (mod.__name__, func.__qualname__)<EOL>if postfix:<EOL><INDENT>parts += (postfix,)<EOL><DEDENT>logger_name = '<STR_LIT:.>...
Automatically generate a logger from the calling function :param postfix: append another logger name on top this :param depth: depth of the call stack at which to capture the caller name :return: instance of a logger with a correct path to a current caller
f7409:m0
def _start_services(self, console_env):
self._ad.load_snippet(name='<STR_LIT>', package=self._package)<EOL>console_env['<STR_LIT>'] = self._ad.snippet<EOL>console_env['<STR_LIT:s>'] = self._ad.snippet<EOL>
Overrides superclass.
f7451:c0:m1
def _start_services(self, console_env):
self._ad.services.register('<STR_LIT>', sl4a_service.Sl4aService)<EOL>console_env['<STR_LIT:s>'] = self._ad.services.sl4a<EOL>console_env['<STR_LIT>'] = self._ad.sl4a<EOL>console_env['<STR_LIT>'] = self._ad.ed<EOL>
Overrides superclass.
f7452:c0:m0
def get_print_function_name():
if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Gets the name of the print function for mocking. Returns: A str representing the print function to mock.
f7458:m0
def __getattr__(self, name):
def adb_call(*args):<EOL><INDENT>arg_str = '<STR_LIT:U+0020>'.join(str(elem) for elem in args)<EOL>return arg_str<EOL><DEDENT>return adb_call<EOL>
All calls to the none-existent functions in adb proxy would simply return the adb command string.
f7458:c0:m3
def __getattr__(self, name):
def adb_call(*args):<EOL><INDENT>arg_str = '<STR_LIT:U+0020>'.join(str(elem) for elem in args)<EOL>return arg_str<EOL><DEDENT>return adb_call<EOL>
All calls to the none-existent functions in adb proxy would simply return the adb command string.
f7461:c0:m3
def tearDown(self):
shutil.rmtree(self.tmp_dir)<EOL>
Removes the temp dir.
f7464:c0:m1
def tearDown(self):
shutil.rmtree(self.tmp_dir)<EOL>
Removes the temp dir.
f7470:c0:m1
def setup_mock_socket_file(self, mock_create_connection, resp=MOCK_RESP):
fake_file = self.MockSocketFile(resp)<EOL>fake_conn = mock.MagicMock()<EOL>fake_conn.makefile.return_value = fake_file<EOL>mock_create_connection.return_value = fake_conn<EOL>return fake_file<EOL>
Sets up a fake socket file from the mock connection. Args: mock_create_connection: The mock method for creating a method. resp: (str) response to give. MOCK_RESP by default. Returns: The mock file that will be injected into the code.
f7480:c0:m0
def get_mock_ads(num):
ads = []<EOL>for i in range(num):<EOL><INDENT>ad = mock.MagicMock(name="<STR_LIT>", serial=str(i), h_port=None)<EOL>ad.skip_logcat = False<EOL>ads.append(ad)<EOL><DEDENT>return ads<EOL>
Generates a list of mock AndroidDevice objects. The serial number of each device will be integer 0 through num - 1. Args: num: An integer that is the number of mock AndroidDevice objects to create.
f7482:m0
def __getattr__(self, name):
def adb_call(*args, **kwargs):<EOL><INDENT>arg_str = '<STR_LIT:U+0020>'.join(str(elem) for elem in args)<EOL>return arg_str<EOL><DEDENT>return adb_call<EOL>
All calls to the none-existent functions in adb proxy would simply return the adb command string.
f7482:c1:m4
def __init__(self, configs):
self.tests = []<EOL>self._class_name = self.__class__.__name__<EOL>if configs.test_class_name_suffix and self.TAG is None:<EOL><INDENT>self.TAG = '<STR_LIT>' % (self._class_name,<EOL>configs.test_class_name_suffix)<EOL><DEDENT>elif self.TAG is None:<EOL><INDENT>self.TAG = self._class_name<EOL><DEDENT>self.log_path = co...
Constructor of BaseTestClass. The constructor takes a config_parser.TestRunConfig object and which has all the information needed to execute this test class, like log_path and controller configurations. For details, see the definition of class config_parser.TestRunConfig. Args:...
f7490:c1:m0
def unpack_userparams(self,<EOL>req_param_names=None,<EOL>opt_param_names=None,<EOL>**kwargs):
req_param_names = req_param_names or []<EOL>opt_param_names = opt_param_names or []<EOL>for k, v in kwargs.items():<EOL><INDENT>if k in self.user_params:<EOL><INDENT>v = self.user_params[k]<EOL><DEDENT>setattr(self, k, v)<EOL><DEDENT>for name in req_param_names:<EOL><INDENT>if hasattr(self, name):<EOL><INDENT>continue<...
An optional function that unpacks user defined parameters into individual variables. After unpacking, the params can be directly accessed with self.xxx. If a required param is not provided, an exception is raised. If an optional param is not provided, a warning line will be logged. ...
f7490:c1:m3
def register_controller(self, module, required=True, min_number=<NUM_LIT:1>):
return self._controller_manager.register_controller(<EOL>module, required, min_number)<EOL>
Loads a controller module and returns its loaded devices. A Mobly controller module is a Python lib that can be used to control a device, service, or equipment. To be Mobly compatible, a controller module needs to have the following members: .. code-block:: python def crea...
f7490:c1:m4
def _setup_class(self):
<EOL>class_record = records.TestResultRecord(STAGE_NAME_SETUP_CLASS,<EOL>self.TAG)<EOL>class_record.test_begin()<EOL>self.current_test_info = runtime_test_info.RuntimeTestInfo(<EOL>STAGE_NAME_SETUP_CLASS, self.log_path, class_record)<EOL>expects.recorder.reset_internal_states(class_record)<EOL>try:<EOL><INDENT>with sel...
Proxy function to guarantee the base implementation of setup_class is called. Returns: If `self.results` is returned instead of None, this means something has gone wrong, and the rest of the test class should not execute.
f7490:c1:m8
def setup_class(self):
Setup function that will be called before executing any test in the class. To signal setup failure, use asserts or raise your own exception. Errors raised from `setup_class` will trigger `on_fail`. Implementation is optional.
f7490:c1:m9
def _teardown_class(self):
stage_name = STAGE_NAME_TEARDOWN_CLASS<EOL>record = records.TestResultRecord(stage_name, self.TAG)<EOL>record.test_begin()<EOL>self.current_test_info = runtime_test_info.RuntimeTestInfo(<EOL>stage_name, self.log_path, record)<EOL>expects.recorder.reset_internal_states(record)<EOL>try:<EOL><INDENT>with self._log_test_st...
Proxy function to guarantee the base implementation of teardown_class is called.
f7490:c1:m10
def teardown_class(self):
Teardown function that will be called after all the selected tests in the test class have been executed. Errors raised from `teardown_class` do not trigger `on_fail`. Implementation is optional.
f7490:c1:m11
def _on_fail(self, record):
self.on_fail(record)<EOL>
Proxy function to guarantee the base implementation of on_fail is called. Args: record: records.TestResultRecord, a copy of the test record for this test, containing all information of the test execution including exception objects.
f7490:c1:m17
def on_fail(self, record):
A function that is executed upon a test failure. User implementation is optional. Args: record: records.TestResultRecord, a copy of the test record for this test, containing all information of the test execution including exception objects.
f7490:c1:m18