positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _initLayerCtors(self): ''' Registration for built-in Layer ctors ''' ctors = { 'lmdb': s_lmdblayer.LmdbLayer, 'remote': s_remotelayer.RemoteLayer, } self.layrctors.update(**ctors)
Registration for built-in Layer ctors
def _mk_uninit_array(self, bounds): """ given a list of bounds for the N dimensions of an array, _mk_uninit_array() creates and returns an N-dimensional array of the size specified by the bounds with each element set to the value None.""" if len(bounds) == 0: ...
given a list of bounds for the N dimensions of an array, _mk_uninit_array() creates and returns an N-dimensional array of the size specified by the bounds with each element set to the value None.
def create_id_token(token, user, aud, nonce='', at_hash='', request=None, scope=None): """ Creates the id_token dictionary. See: http://openid.net/specs/openid-connect-core-1_0.html#IDToken Return a dic. """ if scope is None: scope = [] sub = settings.get('OIDC_IDTOKEN_SUB_GENERATOR'...
Creates the id_token dictionary. See: http://openid.net/specs/openid-connect-core-1_0.html#IDToken Return a dic.
def hash_parameters(keys, minimize=True, to_int=None): """ Calculates the parameters for a perfect hash. The result is returned as a HashInfo tuple which has the following fields: t The "table parameter". This is the minimum side length of the table used to create the hash. In practice, t...
Calculates the parameters for a perfect hash. The result is returned as a HashInfo tuple which has the following fields: t The "table parameter". This is the minimum side length of the table used to create the hash. In practice, t**2 is the maximum size of the output hash. slots ...
def to_dict(self): """ Return a dictionary representation of the dataset. """ d = dict(doses=self.doses, ns=self.ns, means=self.means, stdevs=self.stdevs) d.update(self.kwargs) return d
Return a dictionary representation of the dataset.
async def activate_scene(self, scene_id: int): """Activate a scene :param scene_id: Scene id. :return: """ _scene = await self.get_scene(scene_id) await _scene.activate()
Activate a scene :param scene_id: Scene id. :return:
def run(self): '''Extends the run() method of threading.Thread ''' self.connect() while True: for event in self.slack_client.rtm_read(): logger.debug(event) if 'type' in event and event['type'] in self.supported_events: eve...
Extends the run() method of threading.Thread
def _print_entity_intro(self, g=None, entity=None, first_time=True): """after a selection, prints on screen basic info about onto or entity, plus change prompt 2015-10-18: removed the sound 2016-01-18: entity is the shell wrapper around the ontospy entity """ if entity: ...
after a selection, prints on screen basic info about onto or entity, plus change prompt 2015-10-18: removed the sound 2016-01-18: entity is the shell wrapper around the ontospy entity
def cdf(arr, **kwargs): """ ARGS arr array to calculate cumulative distribution function **kwargs Passed directly to numpy.histogram. Typical options include: bins = <num_bins> normed = True|False DESC Determines the cumulative distribution functi...
ARGS arr array to calculate cumulative distribution function **kwargs Passed directly to numpy.histogram. Typical options include: bins = <num_bins> normed = True|False DESC Determines the cumulative distribution function.
def delete_alias(self, addressid, data): """Delete alias address""" return self.api_call( ENDPOINTS['aliases']['delete'], dict(addressid=addressid), body=data)
Delete alias address
def login(self, email, password): """Login to the flightradar24 session The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans. For users who have signed up for a plan, this method allows to login with the credentials from...
Login to the flightradar24 session The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans. For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains a tok...
def setStimReps(self): """Sets the reps of the StimulusModel from values pulled from this widget""" reps = self.ui.nrepsSpnbx.value() self.stimModel.setRepCount(reps)
Sets the reps of the StimulusModel from values pulled from this widget
def compare_zips(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right ZipFile instances """ ll = set(left.namelist()) rl = set(right.namelist()) for f in ll: if f in rl: rl.remove(f) if f[-1] == '/': #...
yields EVENT,ENTRY pairs describing the differences between left and right ZipFile instances
async def wait_tasks(tasks, flatten=True): '''Gather a list of asynchronous tasks and wait their completion. :param list tasks: A list of *asyncio* tasks wrapped in :func:`asyncio.ensure_future`. :param bool flatten: If ``True`` the returned results are flattened into one list if the ...
Gather a list of asynchronous tasks and wait their completion. :param list tasks: A list of *asyncio* tasks wrapped in :func:`asyncio.ensure_future`. :param bool flatten: If ``True`` the returned results are flattened into one list if the tasks return iterable objects. The parameter doe...
def _timer_update(self): """Add some moving points to the dependency resolution text.""" self._timer_counter += 1 dot = self._timer_dots.pop(0) self._timer_dots = self._timer_dots + [dot] self._rows = [[_(u'Resolving dependencies') + dot, u'', u'', u'']] index = self.crea...
Add some moving points to the dependency resolution text.
def rgba_to_rgb(color, bg='rgb(255,255,255)'): """ Converts from rgba to rgb Parameters: ----------- color : string Color representation in rgba bg : string Color representation in rgb Example: rgba_to_rgb('rgb(23,25,24,.4...
Converts from rgba to rgb Parameters: ----------- color : string Color representation in rgba bg : string Color representation in rgb Example: rgba_to_rgb('rgb(23,25,24,.4)''
def solid_angle(center, coords): """ Helper method to calculate the solid angle of a set of coords from the center. Args: center (3x1 array): Center to measure solid angle from. coords (Nx3 array): List of coords to determine solid angle. Returns: The solid angle. """ ...
Helper method to calculate the solid angle of a set of coords from the center. Args: center (3x1 array): Center to measure solid angle from. coords (Nx3 array): List of coords to determine solid angle. Returns: The solid angle.
def validate_json_field(dist, attr, value): """ Check for json validity. """ try: is_json_compat(value) except ValueError as e: raise DistutilsSetupError("%r %s" % (attr, e)) return True
Check for json validity.
def validate(self): """Validate this object as Image API data. Raise IIIFInfoError with helpful message if not valid. """ errors = [] for param in self.required_params: if (not hasattr(self, param) or getattr(self, param) is None): errors.append("miss...
Validate this object as Image API data. Raise IIIFInfoError with helpful message if not valid.
def movMF( X, n_clusters, posterior_type="soft", force_weights=None, n_init=10, n_jobs=1, max_iter=300, verbose=False, init="random-class", random_state=None, tol=1e-6, copy_x=True, ): """Wrapper for parallelization of _movMF and running n_init times. """ if n...
Wrapper for parallelization of _movMF and running n_init times.
def available(name, limit=''): ''' Return True if the named service is available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.available sshd salt '*' service.available sshd limit=upstart salt '*...
Return True if the named service is available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.available sshd salt '*' service.available sshd limit=upstart salt '*' service.available sshd limit=sysvinit
def is_running(process): ''' Check if process is running. Check if the given process name is running or not. Note: On a Linux system, kernel threads (like ``kthreadd`` etc.) are excluded. Args: process (str): The name of the process. Returns: bool: Is the process running? ''' if os.name == 'nt'...
Check if process is running. Check if the given process name is running or not. Note: On a Linux system, kernel threads (like ``kthreadd`` etc.) are excluded. Args: process (str): The name of the process. Returns: bool: Is the process running?
def Debugger_setScriptSource(self, scriptId, scriptSource, **kwargs): """ Function path: Debugger.setScriptSource Domain: Debugger Method name: setScriptSource Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script to edit. 'scriptSource' (type: string) -> ...
Function path: Debugger.setScriptSource Domain: Debugger Method name: setScriptSource Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script to edit. 'scriptSource' (type: string) -> New content of the script. Optional arguments: 'dryRun' (type: boolea...
def _timedatectl(): ''' get the output of timedatectl ''' ret = __salt__['cmd.run_all'](['timedatectl'], python_shell=False) if ret['retcode'] != 0: msg = 'timedatectl failed: {0}'.format(ret['stderr']) raise CommandExecutionError(msg) return ret
get the output of timedatectl
def delete_bulk_device_enrollment(self, enrollment_identities, **kwargs): # noqa: E501 """Bulk delete # noqa: E501 With bulk delete, you can upload a `CSV` file containing a number of enrollment IDs to be deleted. **Example usage:** ``` curl -X POST \\ -H 'Authorization: Bearer <valid access token>'...
Bulk delete # noqa: E501 With bulk delete, you can upload a `CSV` file containing a number of enrollment IDs to be deleted. **Example usage:** ``` curl -X POST \\ -H 'Authorization: Bearer <valid access token>' \\ -F 'enrollment_identities=@/path/to/enrollments/enrollments.csv' \\ https://api.us-east-1.mbedc...
def is_adb_root(self): """True if adb is running as root for this device. """ try: return '0' == self.adb.shell('id -u').decode('utf-8').strip() except adb.AdbError: # Wait a bit and retry to work around adb flakiness for this cmd. time.sleep(0.2) ...
True if adb is running as root for this device.
def create(self, from_=values.unset, attributes=values.unset, date_created=values.unset, date_updated=values.unset, last_updated_by=values.unset, body=values.unset, media_sid=values.unset): """ Create a new MessageInstance :param unicode from_: The i...
Create a new MessageInstance :param unicode from_: The identity of the new message's author :param unicode attributes: A valid JSON string that contains application-specific data :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created :param datetim...
async def generate_wallet_key(config: Optional[str]) -> str: """ Generate wallet master key. Returned key is compatible with "RAW" key derivation method. It allows to avoid expensive key derivation for use cases when wallet keys can be stored in a secure enclave. :param config: (optional) key confi...
Generate wallet master key. Returned key is compatible with "RAW" key derivation method. It allows to avoid expensive key derivation for use cases when wallet keys can be stored in a secure enclave. :param config: (optional) key configuration json. { "seed": string, (optional) Seed that allows...
def write(self, chunk): """WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application). """ if not self.started_response: raise AssertionError('WSGI wri...
WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).
def _extract_axes_for_slice(self, axes): """ Return the slice dictionary for these axes. """ return {self._AXIS_SLICEMAP[i]: a for i, a in zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)}
Return the slice dictionary for these axes.
def append(self, filename_in_zip, file_contents): ''' Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip. ''' # Set the file pointer to the end of the file self.in_memory_zip.seek(-1, io.SEEK_END) # Get a handle to the in-...
Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip.
def randomize_colors(im, keep_vals=[0]): r''' Takes a greyscale image and randomly shuffles the greyscale values, so that all voxels labeled X will be labelled Y, and all voxels labeled Y will be labeled Z, where X, Y, Z and so on are randomly selected from the values in the input image. This f...
r''' Takes a greyscale image and randomly shuffles the greyscale values, so that all voxels labeled X will be labelled Y, and all voxels labeled Y will be labeled Z, where X, Y, Z and so on are randomly selected from the values in the input image. This function is useful for improving the visibilit...
def current(): """ Returns the current environment manager for the projex system. :return <EnvManager> """ if not EnvManager._current: path = os.environ.get('PROJEX_ENVMGR_PATH') module = os.environ.get('PROJEX_ENVMGR_MODULE') clsn...
Returns the current environment manager for the projex system. :return <EnvManager>
def count(self): """ Compute count of group, excluding missing values """ ids, _, ngroups = self.grouper.group_info val = self.obj.get_values() mask = (ids != -1) & ~isna(val) ids = ensure_platform_int(ids) minlength = ngroups or 0 out = np.bincount(ids[mask], mi...
Compute count of group, excluding missing values
def get_firmware(self): """Get the current firmware version.""" self.get_status() try: self.firmware = self.data['fw_version'] except TypeError: self.firmware = 'Unknown' return self.firmware
Get the current firmware version.
def get_num_processors(): """ Return number of online processor cores. """ # try different strategies and use first one that succeeeds try: return os.cpu_count() # Py3 only except AttributeError: pass try: import multiprocessing return multiprocessing.cpu_cou...
Return number of online processor cores.
def base36encode(number): """Converts an integer into a base36 string.""" ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz" base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <= number < len(ALPHABET): return sign + ALPHABET[number] while numbe...
Converts an integer into a base36 string.
def return_tip(self, home_after=True): """ Drop the pipette's current tip to it's originating tip rack Notes ----- This method requires one or more tip-rack :any:`Container` to be in this Pipette's `tip_racks` list (see :any:`Pipette`) Returns ------- ...
Drop the pipette's current tip to it's originating tip rack Notes ----- This method requires one or more tip-rack :any:`Container` to be in this Pipette's `tip_racks` list (see :any:`Pipette`) Returns ------- This instance of :class:`Pipette`. Examples...
def advantage_as_result(self, move, val_scheme): """ Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rtype: double """ test_board = cp(self) test_board.update(move) return test_board.material_advantage(m...
Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rtype: double
def render_POST(self, request): """ Responds to events and starts the build process different implementations can decide on what methods they will accept :arguments: request the http request object """ try: d = self.getAndSubmitC...
Responds to events and starts the build process different implementations can decide on what methods they will accept :arguments: request the http request object
def _get_client(): ''' Return a cloud client ''' client = salt.cloud.CloudClient( os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'), pillars=copy.deepcopy(__pillar__.get('cloud', {})) ) return client
Return a cloud client
def parse_multipart_form(body, boundary): '''Parse a request body and returns fields and files :param body: bytes request body :param boundary: bytes multipart boundary :return: fields (RequestParameters), files (RequestParameters) ''' files = RequestParameters() fields = RequestParameters(...
Parse a request body and returns fields and files :param body: bytes request body :param boundary: bytes multipart boundary :return: fields (RequestParameters), files (RequestParameters)
def _get_class_name(error_code): """ Gets the corresponding class name for the given error code, this either being an integer (thus base error name) or str. """ if isinstance(error_code, int): return KNOWN_BASE_CLASSES.get( error_code, 'RPCError' + str(error_code).replace('-', 'N...
Gets the corresponding class name for the given error code, this either being an integer (thus base error name) or str.
def GetFileSystem(self, path_spec): """Retrieves a file system object defined by path specification. Args: path_spec (PathSpec): path specification. Returns: FileSystem: a file system object or None if not cached. """ identifier = self._GetFileSystemCacheIdentifier(path_spec) retur...
Retrieves a file system object defined by path specification. Args: path_spec (PathSpec): path specification. Returns: FileSystem: a file system object or None if not cached.
def distributions_for_instances(self, data): """ Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ndar...
Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ndarray
def purge(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. Th...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Sa...
def _change_kind(self, post_uid): ''' To modify the category of the post, and kind. ''' post_data = self.get_post_data() logger.info('admin post update: {0}'.format(post_data)) MPost.update_misc(post_uid, kind=post_data['kcat']) # self.update_category(post_uid)...
To modify the category of the post, and kind.
def success(item): '''Successful finish''' try: # mv to done trg_queue = item.queue os.rename(fsq_path.item(trg_queue, item.id, host=item.host), os.path.join(fsq_path.done(trg_queue, host=item.host), item.id)) except AttributeError, e:...
Successful finish
def tzname(self, dt): """datetime -> string name of time zone.""" tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) return _time.tzname[tt.tm_isdst > 0]
datetime -> string name of time zone.
def encode_refresh_token(identity, secret, algorithm, expires_delta, user_claims, csrf, identity_claim_key, user_claims_key, json_encoder=None): """ Creates a new encoded (utf-8) refresh token. :param identity: Some identifier used to identify the owner of ...
Creates a new encoded (utf-8) refresh token. :param identity: Some identifier used to identify the owner of this token :param secret: Secret key to encode the JWT with :param algorithm: Which algorithm to use for the toek :param expires_delta: How far in the future this token should expire ...
def calc_timestep_statistic(self, statistic, time): """ Calculate statistics from the primary attribute of the StObject. Args: statistic: statistic being calculated time: Timestep being investigated Returns: Value of the statistic """ ...
Calculate statistics from the primary attribute of the StObject. Args: statistic: statistic being calculated time: Timestep being investigated Returns: Value of the statistic
def ObjectTransitionedEventHandler(obj, event): """Object has been transitioned to an new state """ # only snapshot supported objects if not supports_snapshots(obj): return # default transition entry entry = { "modified": DateTime().ISO(), "action": event.action, } ...
Object has been transitioned to an new state
def _GetUtf8Contents(self, file_name): """Check for errors in file_name and return a string for csv reader.""" contents = self._FileContents(file_name) if not contents: # Missing file return # Check for errors that will prevent csv.reader from working if len(contents) >= 2 and contents[0:2] ...
Check for errors in file_name and return a string for csv reader.
def ontologyClassTree(self): """ Returns a dict representing the ontology tree Top level = {0:[top classes]} Multi inheritance is represented explicitly """ treedict = {} if self.all_classes: treedict[0] = self.toplayer_classes for element ...
Returns a dict representing the ontology tree Top level = {0:[top classes]} Multi inheritance is represented explicitly
def set_flag(self, info, code=None): """Flag this instance for investigation.""" self.flag = True self.flag_info += info if code is not None: self.flag_code = code
Flag this instance for investigation.
def get_os_file_names(files): """ returns file names :param files: list of strings and\\or :class:`file_configuration_t` instances. :type files: list """ fnames = [] for f in files: if utils.is_str(f): fnames.app...
returns file names :param files: list of strings and\\or :class:`file_configuration_t` instances. :type files: list
def adjust_text(x, y, texts, ax=None, expand_text=(1.2, 1.2), expand_points=(1.2, 1.2), autoalign=True, va='center', ha='center', force_text=1., force_points=1., lim=100, precision=0, only_move={}, text_from_text=True, text_from_points=True, save_steps=Fa...
Iteratively adjusts the locations of texts. First moves all texts that are outside the axes limits inside. Then in each iteration moves all texts away from each other and from points. In the end hides texts and substitutes them with annotations to link them to the rescpective points. Args: x (s...
def buildlist(self, category=tpb.CATEGORIES.VIDEO.TV_SHOWS, limit=1000): """ Build the torrent list Return list of list sorted by seeders count Id can be used to retrieve torrent associate with this id [[<title>, <Seeders>, <id>] ...] """ try: s = sel...
Build the torrent list Return list of list sorted by seeders count Id can be used to retrieve torrent associate with this id [[<title>, <Seeders>, <id>] ...]
def entities(self, tc_data, resource_type): """ Yields a entity. Takes both a list of indicators/groups or a individual indicator/group response. example formats: { "status":"Success", "data":{ "resultCount":984240, "address":[ ...
Yields a entity. Takes both a list of indicators/groups or a individual indicator/group response. example formats: { "status":"Success", "data":{ "resultCount":984240, "address":[ { "id":4222035, ...
def open_outside_spyder(self, fnames): """Open file outside Spyder with the appropriate application If this does not work, opening unknown file in Spyder, as text file""" for path in sorted(fnames): path = file_uri(path) ok = programs.start_file(path) if...
Open file outside Spyder with the appropriate application If this does not work, opening unknown file in Spyder, as text file
def bodn2c(name): """ Translate the name of a body or object to the corresponding SPICE integer ID code. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodn2c_c.html :param name: Body name to be translated into a SPICE ID code. :type name: str :return: SPICE integer ID code for th...
Translate the name of a body or object to the corresponding SPICE integer ID code. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodn2c_c.html :param name: Body name to be translated into a SPICE ID code. :type name: str :return: SPICE integer ID code for the named body. :rtype: int
def process_post_author(self, bulk_mode, api_author): """ Create or update an Author related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_author: the data in the api for the Author :return: the up-to-date Author object ...
Create or update an Author related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_author: the data in the api for the Author :return: the up-to-date Author object
def forget_canvas(canvas): """ Forget about the given canvas. Used by the canvas when closed. """ cc = [c() for c in canvasses if c() is not None] while canvas in cc: cc.remove(canvas) canvasses[:] = [weakref.ref(c) for c in cc]
Forget about the given canvas. Used by the canvas when closed.
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class...
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this ...
def attach_zoom(ax, scaling=2.0): """ Attach an event handler that supports zooming within a plot using the mouse scroll wheel. Parameters ---------- ax : :class:`matplotlib.axes.Axes` object Axes to which event handling is to be attached scaling : float, optional (default 2.0) ...
Attach an event handler that supports zooming within a plot using the mouse scroll wheel. Parameters ---------- ax : :class:`matplotlib.axes.Axes` object Axes to which event handling is to be attached scaling : float, optional (default 2.0) Scaling factor for zooming in and out Ret...
def _check_user(user, group): ''' Checks if the named user and group are present on the minion ''' err = '' if user: uid = __salt__['file.user_to_uid'](user) if uid == '': err += 'User {0} is not available '.format(user) if group: gid = __salt__['file.group_to...
Checks if the named user and group are present on the minion
def process_boolean(self, tag): """Process Boolean type tags""" tag.set_address(self.normal_register.current_bit_address) self.normal_register.move_to_next_bit_address()
Process Boolean type tags
def create_ticket(self, ticket=None, **kwargs): """ Create a new ``Ticket``. Additional arguments are passed to the ``create()`` function. Return the newly created ``Ticket``. """ if not ticket: ticket = self.create_ticket_str() if 'service' in kwargs: ...
Create a new ``Ticket``. Additional arguments are passed to the ``create()`` function. Return the newly created ``Ticket``.
async def expand_foreign_keys(self, database, table, column, values): "Returns dict mapping (column, value) -> label" labeled_fks = {} foreign_keys = await self.foreign_keys_for_table(database, table) # Find the foreign_key for this column try: fk = [ ...
Returns dict mapping (column, value) -> label
def position(axis, hardware, cp=None): """ Read position from driver into a tuple and map 3-rd value to the axis of a pipette currently used """ if not ff.use_protocol_api_v2(): p = hardware._driver.position return (p['X'], p['Y'], p[axis]) else: p = hardware.gantry_posi...
Read position from driver into a tuple and map 3-rd value to the axis of a pipette currently used
def get_masquerade(zone=None, permanent=True): ''' Show if masquerading is enabled on a zone. If zone is omitted, default zone will be used. CLI Example: .. code-block:: bash salt '*' firewalld.get_masquerade zone ''' zone_info = list_all(zone, permanent) if 'no' in [zone_inf...
Show if masquerading is enabled on a zone. If zone is omitted, default zone will be used. CLI Example: .. code-block:: bash salt '*' firewalld.get_masquerade zone
def get_bio(self, section, language=None): """ Returns a section of the bio. section can be "content", "summary" or "published" (for published date) """ if language: params = self._get_params() params["lang"] = language else: ...
Returns a section of the bio. section can be "content", "summary" or "published" (for published date)
def _backup_file(path): """ Backup a file but never overwrite an existing backup file """ backup_base = '/var/local/woven-backup' backup_path = ''.join([backup_base,path]) if not exists(backup_path): directory = ''.join([backup_base,os.path.split(path)[0]]) sudo('mkdir -p %s'% di...
Backup a file but never overwrite an existing backup file
def split_glides(n_samples, dur, fs_a, GL, min_dur=None): '''Get start/stop indices of each `dur` length sub-glide for glides in GL Args ---- dur: int Desired duration of glides GL: ndarray, (n, 2) Matrix containing the start time (first column) and end time (2nd column) of ...
Get start/stop indices of each `dur` length sub-glide for glides in GL Args ---- dur: int Desired duration of glides GL: ndarray, (n, 2) Matrix containing the start time (first column) and end time (2nd column) of any glides.Times are in seconds. min_dur: int, default (bool ...
def trailing_window(rows, group_by=None, order_by=None): """Create a trailing window for use with aggregate window functions. Parameters ---------- rows : int Number of trailing rows to include. 0 includes only the current row group_by : expressions, default None Either specify here...
Create a trailing window for use with aggregate window functions. Parameters ---------- rows : int Number of trailing rows to include. 0 includes only the current row group_by : expressions, default None Either specify here or with TableExpr.group_by order_by : expressions, default ...
def enable_all_breakpoints(self): """ Enables all disabled breakpoints in all processes. @see: enable_code_breakpoint, enable_page_breakpoint, enable_hardware_breakpoint """ # disable code breakpoints for (pid, bp) in self.get_all_cod...
Enables all disabled breakpoints in all processes. @see: enable_code_breakpoint, enable_page_breakpoint, enable_hardware_breakpoint
def add_conditional_clause(self, clause): """ Adds a iff clause to this statement :param clause: The clause that will be added to the iff statement :type clause: ConditionalClause """ clause.set_context_id(self.context_counter) self.context_counter += clause.get_...
Adds a iff clause to this statement :param clause: The clause that will be added to the iff statement :type clause: ConditionalClause
def resolve_font(name): """Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') >>> noto_path = os.path.join(fontdir,...
Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') >>> noto_path = os.path.join(fontdir, 'NotoSans-Bold.ttf') >...
def metric_path(cls, project, metric): """Return a fully-qualified metric string.""" return google.api_core.path_template.expand( "projects/{project}/metrics/{metric}", project=project, metric=metric )
Return a fully-qualified metric string.
def getScan(self, title, peptide=None): """ allows random lookup """ if self.ra.has_key(title): self.filename.seek(self.ra[title][0],0) toRead = self.ra[title][1]-self.ra[title][0] info = self.filename.read(toRead) scan = self.parseScan(inf...
allows random lookup
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(...
Parse until the next block tag with a given name.
def _handle_sub_action(self, input_dict, handler): """ Handles resolving replacements in the Sub action based on the handler that is passed as an input. :param input_dict: Dictionary to be resolved :param supported_values: One of several different objects that contain the supported valu...
Handles resolving replacements in the Sub action based on the handler that is passed as an input. :param input_dict: Dictionary to be resolved :param supported_values: One of several different objects that contain the supported values that need to be changed. See each method above for speci...
def sum_2_dictionaries(dicta, dictb): """Given two dictionaries of totals, where each total refers to a key in the dictionary, add the totals. E.g.: dicta = { 'a' : 3, 'b' : 1 } dictb = { 'a' : 1, 'c' : 5 } dicta + dictb = { 'a' : 4, 'b' : 1, 'c' : 5 } @param dicta:...
Given two dictionaries of totals, where each total refers to a key in the dictionary, add the totals. E.g.: dicta = { 'a' : 3, 'b' : 1 } dictb = { 'a' : 1, 'c' : 5 } dicta + dictb = { 'a' : 4, 'b' : 1, 'c' : 5 } @param dicta: (dictionary) @param dictb: (dictionar...
def spark_config(self): """ config spark :return: """ configs = [ 'export LD_LIBRARY_PATH={0}/lib/native/:$LD_LIBRARY_PATH'.format( bigdata_conf.hadoop_home ), 'export SPARK_LOCAL_IP={0}'.format(env.host_string) ] ...
config spark :return:
def continuous_partition_data(data, bins='auto', n_bins=10): """Convenience method for building a partition object on continuous data Args: data (list-like): The data from which to construct the estimate. bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-space...
Convenience method for building a partition object on continuous data Args: data (list-like): The data from which to construct the estimate. bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins) n_bins (i...
def astype(self, dtype): """Return a copy of this space with new ``dtype``. Parameters ---------- dtype : Scalar data type of the returned space. Can be provided in any way the `numpy.dtype` constructor understands, e.g. as built-in type or as a strin...
Return a copy of this space with new ``dtype``. Parameters ---------- dtype : Scalar data type of the returned space. Can be provided in any way the `numpy.dtype` constructor understands, e.g. as built-in type or as a string. Data types with non-trivial ...
def load_molecule(name, format=None): '''Read a `~chemlab.core.Molecule` from a file. .. seealso:: `chemlab.io.datafile` ''' mol = datafile(name, format=format).read('molecule') display_system(System([mol]))
Read a `~chemlab.core.Molecule` from a file. .. seealso:: `chemlab.io.datafile`
def _convert_from_pandas(self, pdf, schema, timezone): """ Convert a pandas.DataFrame to list of records that can be used to make a DataFrame :return list of records """ if timezone is not None: from pyspark.sql.types import _check_series_convert_timestamps_tz_local...
Convert a pandas.DataFrame to list of records that can be used to make a DataFrame :return list of records
def warn(self, cmd, desc=''): ''' Style for warning message. ''' return self._label_desc(cmd, desc, self.warn_color)
Style for warning message.
def compute_invar(self): """ Compute the three invariants (I0, I1, I2) of the tensor, as well as the quantity I = -(I2/2)**2 / (I1/3)**3. """ self.i0 = self.vxx + self.vyy + self.vzz self.i1 = (self.vxx*self.vyy + self.vyy*self.vzz + self.vxx*self.vzz - ...
Compute the three invariants (I0, I1, I2) of the tensor, as well as the quantity I = -(I2/2)**2 / (I1/3)**3.
def find_keywords(self, string, **kwargs): """ Returns a sorted list of keywords in the given string. """ return find_keywords(string, parser = self, top = kwargs.pop("top", 10), frequency = kwargs.pop("frequency", {}), **kwargs ...
Returns a sorted list of keywords in the given string.
def _ellipsoid_phantom_3d(space, ellipsoids): """Create an ellipsoid phantom in 3d space. Parameters ---------- space : `DiscreteLp` Space in which the phantom should be generated. If ``space.shape`` is 1 in an axis, a corresponding slice of the phantom is created (instead of sq...
Create an ellipsoid phantom in 3d space. Parameters ---------- space : `DiscreteLp` Space in which the phantom should be generated. If ``space.shape`` is 1 in an axis, a corresponding slice of the phantom is created (instead of squashing the whole phantom into the slice). ellips...
def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' ...
Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key
def add_receiver( self, consumer_group, partition, offset=None, prefetch=300, operation=None, keep_alive=30, auto_reconnect=True): """ Add a receiver to the client for a particular consumer group and partition. :param consumer_group: The name of the consumer group. ...
Add a receiver to the client for a particular consumer group and partition. :param consumer_group: The name of the consumer group. :type consumer_group: str :param partition: The ID of the partition. :type partition: str :param offset: The offset from which to start receiving. ...
def align_subplot_array(axes,xlim=None, ylim=None): """ Make all of the axes in the array hae the same limits, turn off unnecessary ticks use plt.subplots() to get an array of axes """ #find sensible xlim,ylim if xlim is None: xlim = [np.inf,-np.inf] for ax in axes.flatten(): ...
Make all of the axes in the array hae the same limits, turn off unnecessary ticks use plt.subplots() to get an array of axes
def response(self, action=None): """ returns cached response (as dict) for given action, or list of cached actions """ if action in self.cache: return utils.json_loads(self.cache[action]['response']) return self.cache.keys() or None
returns cached response (as dict) for given action, or list of cached actions
def commit_or_abort(self, ctx, timeout=None, metadata=None, credentials=None): """Runs commit or abort operation.""" return self.stub.CommitOrAbort(ctx, timeout=timeout, metadata=metadata, credentials=credentials)
Runs commit or abort operation.
def get_python_args(fname, python_args, interact, debug, end_args): """Construct Python interpreter arguments""" p_args = [] if python_args is not None: p_args += python_args.split() if interact: p_args.append('-i') if debug: p_args.extend(['-m', 'pdb']) if fname...
Construct Python interpreter arguments
def size(self): """Get the number of elements in the DataFrame. Returns: The number of elements in the DataFrame. """ return len(self._query_compiler.index) * len(self._query_compiler.columns)
Get the number of elements in the DataFrame. Returns: The number of elements in the DataFrame.
def get_polygon_constraints_m(self, polygons_m, print_out=False): """ :param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b """ rows_b = [] rows_A = [] m = len(polygons_m[0]) ...
:param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b