code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def replace(text, replacements): """ Replaces multiple slices of text with new values. This is a convenience method for making code modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is an iterable of ``(start, end, new_text)`` tuples. For example, ``replace("this ...
Replaces multiple slices of text with new values. This is a convenience method for making code modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is an iterable of ``(start, end, new_text)`` tuples. For example, ``replace("this is a test", [(0, 4, "X"), (8, 1, "THE")])...
def TNE_metric(bpmn_graph): """ Returns the value of the TNE metric (Total Number of Events of the Model) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. """ events_counts = get_events_counts(bpmn_graph) return sum( [c...
Returns the value of the TNE metric (Total Number of Events of the Model) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
async def _senddms(self): """Toggles sending DMs to owner.""" data = self.bot.config.get("meta", {}) tosend = data.get('send_dms', True) data['send_dms'] = not tosend await self.bot.config.put('meta', data) await self.bot.responses.toggle(message="Forwarding of DMs to own...
Toggles sending DMs to owner.
def update_activity(self, activity_id, activity_name=None, desc=None, started_on=None, ended_on=None): """ Send PUT request to /activities/{activity_id} to update the activity metadata. Raises ValueError if at least one field is not updated. :param activity_id: st...
Send PUT request to /activities/{activity_id} to update the activity metadata. Raises ValueError if at least one field is not updated. :param activity_id: str uuid of activity :param activity_name: str new name of the activity (optional) :param desc: str description of the activity (opti...
def exitDialog(self): """ Helper method that exits the dialog. This method will cause the previously active submenu to activate. """ if self.prev_submenu is not None: # change back to the previous submenu # could in theory form a stack if one dial...
Helper method that exits the dialog. This method will cause the previously active submenu to activate.
def configure_logging(self): """Create logging handlers for any log output.""" root_logger = logging.getLogger('') # Set up logging to a file root_logger.setLevel(logging.DEBUG) # Send higher-level messages to the console via stderr console = logging.StreamHandler(self....
Create logging handlers for any log output.
def parse_ssh_destination(destination): """Parses the SSH destination argument. """ match = _re_ssh.match(destination) if not match: raise InvalidDestination("Invalid destination: %s" % destination) user, password, host, port = match.groups() info = {} if user: info['username...
Parses the SSH destination argument.
def make_block_creator(yaml_path, filename=None): # type: (str, str) -> Callable[..., List[Controller]] """Make a collection function that will create a list of blocks Args: yaml_path (str): File path to YAML file, or a file in the same dir filename (str): If give, use this filename as the ...
Make a collection function that will create a list of blocks Args: yaml_path (str): File path to YAML file, or a file in the same dir filename (str): If give, use this filename as the last element in the yaml_path (so yaml_path can be __file__) Returns: function: A collecti...
def get_name(self): """ @rtype: str @return: Module name, as used in labels. @warning: Names are B{NOT} guaranteed to be unique. If you need unique identification for a loaded module, use the base address instead. @see: L{get_label} """ ...
@rtype: str @return: Module name, as used in labels. @warning: Names are B{NOT} guaranteed to be unique. If you need unique identification for a loaded module, use the base address instead. @see: L{get_label}
def circumcircleForTriangle(cls, triangle): ''' :param: triangle - Triangle class :return: Circle class Returns the circle where every vertex in the input triangle is on the radius of that circle. ''' if triangle.isRight: # circumcircle origin is th...
:param: triangle - Triangle class :return: Circle class Returns the circle where every vertex in the input triangle is on the radius of that circle.
def _m2m_rev_field_name(model1, model2): """Gets the name of the reverse m2m accessor from `model1` to `model2` For example, if User has a ManyToManyField connected to Group, `_m2m_rev_field_name(Group, User)` retrieves the name of the field on Group that lists a group's Users. (By default, this field ...
Gets the name of the reverse m2m accessor from `model1` to `model2` For example, if User has a ManyToManyField connected to Group, `_m2m_rev_field_name(Group, User)` retrieves the name of the field on Group that lists a group's Users. (By default, this field is called `user_set`, but the name can be ov...
def visit_FunctionDef(self, node): """ Update import context using overwriting name information. Examples -------- >> import foo >> import bar >> def foo(bar): >> print(bar) In this case, neither bar nor foo can be used in the foo function an...
Update import context using overwriting name information. Examples -------- >> import foo >> import bar >> def foo(bar): >> print(bar) In this case, neither bar nor foo can be used in the foo function and in future function, foo will not be usable.
def reverse(self, point, language=None, sensor=False): '''Reverse geocode a point. Pls refer to the Google Maps Web API for the details of the parameters ''' params = { 'latlng': point, 'sensor': str(sensor).lower() } if language: ...
Reverse geocode a point. Pls refer to the Google Maps Web API for the details of the parameters
def floor(self): """Round `x` and `y` down to integers.""" return Point(int(math.floor(self.x)), int(math.floor(self.y)))
Round `x` and `y` down to integers.
def buffer(self, *args, **kwargs): """Buffer documents, in the current session""" self.check_session() result = self.session.buffer(*args, **kwargs) return result
Buffer documents, in the current session
def convert_ram_sdp_ar(ADDR_WIDTH=8, DATA_WIDTH=8): ''' Convert RAM: Simple-Dual-Port, Asynchronous Read''' clk = Signal(bool(0)) we = Signal(bool(0)) addrw = Signal(intbv(0)[ADDR_WIDTH:]) addrr = Signal(intbv(0)[ADDR_WIDTH:]) di = Signal(intbv(0)[DATA_WIDTH:]) do = Signal(intbv(0)[DATA_WIDT...
Convert RAM: Simple-Dual-Port, Asynchronous Read
def symlink(src, link): ''' Create a symbolic link to a file This is only supported with Windows Vista or later and must be executed by a user with the SeCreateSymbolicLink privilege. The behavior of this function matches the Unix equivalent, with one exception - invalid symlinks cannot be cre...
Create a symbolic link to a file This is only supported with Windows Vista or later and must be executed by a user with the SeCreateSymbolicLink privilege. The behavior of this function matches the Unix equivalent, with one exception - invalid symlinks cannot be created. The source path must exist. ...
def qa(ctx): '''Run a quality report''' header('Performing static analysis') info('Python static analysis') flake8_results = lrun('flake8 udata --jobs 1', pty=True, warn=True) info('JavaScript static analysis') eslint_results = lrun('npm -s run lint', pty=True, warn=True) if flake8_results.f...
Run a quality report
def graph_from_incidence_matrix(matrix, node_prefix='', directed=False): """Creates a basic graph out of an incidence matrix. The matrix has to be a list of rows of values representing an incidence matrix. The values can be anything: bool, int, float, as long as they can evaluate to True or False. ...
Creates a basic graph out of an incidence matrix. The matrix has to be a list of rows of values representing an incidence matrix. The values can be anything: bool, int, float, as long as they can evaluate to True or False.
def lock(): ''' Attempts an exclusive lock on the candidate configuration. This is a non-blocking call. .. note:: When locking, it is important to remember to call :py:func:`junos.unlock <salt.modules.junos.unlock>` once finished. If locking during orchestration, remember to inc...
Attempts an exclusive lock on the candidate configuration. This is a non-blocking call. .. note:: When locking, it is important to remember to call :py:func:`junos.unlock <salt.modules.junos.unlock>` once finished. If locking during orchestration, remember to include a step in the ...
def discard(self, element, multiplicity=None): """Removes the `element` from the multiset. If multiplicity is ``None``, all occurrences of the element are removed: >>> ms = Multiset('aab') >>> ms.discard('a') 2 >>> sorted(ms) ['b'] Otherwise, the multip...
Removes the `element` from the multiset. If multiplicity is ``None``, all occurrences of the element are removed: >>> ms = Multiset('aab') >>> ms.discard('a') 2 >>> sorted(ms) ['b'] Otherwise, the multiplicity is subtracted from the one in the multiset and the ...
def records(): """Load test data fixture.""" with db.session.begin_nested(): for idx in range(20): # create the record id_ = uuid.uuid4() Record.create({ 'title': 'LHC experiment {}'.format(idx), 'description': 'Data from experiment {}....
Load test data fixture.
def retrieve(self, operation, field=None): """Retrieve a position in this collection. :param operation: Name of an operation :type operation: :class:`Operation` :param field: Name of field for sort order :type field: str :return: The position for this operation :...
Retrieve a position in this collection. :param operation: Name of an operation :type operation: :class:`Operation` :param field: Name of field for sort order :type field: str :return: The position for this operation :rtype: Mark :raises: NoTrackingCollection
def convert_quadratic_to_cubic_path(q0, q1, q2): """ Convert a quadratic Bezier curve through q0, q1, q2 to a cubic one. """ c0 = q0 c1 = (q0[0] + 2. / 3 * (q1[0] - q0[0]), q0[1] + 2. / 3 * (q1[1] - q0[1])) c2 = (c1[0] + 1. / 3 * (q2[0] - q0[0]), c1[1] + 1. / 3 * (q2[1] - q0[1])) c3 = q2 ...
Convert a quadratic Bezier curve through q0, q1, q2 to a cubic one.
def missed_lines(self, filename): """ Return a list of extrapolated uncovered line numbers for the file `filename` according to `Cobertura.line_statuses`. """ statuses = self.line_statuses(filename) statuses = extrapolate_coverage(statuses) return [lno for lno, st...
Return a list of extrapolated uncovered line numbers for the file `filename` according to `Cobertura.line_statuses`.
def register(self): """ Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ user, created = self.Model.create_account(self._json_params) if user.api_key is None: raise JHTTPBadReq...
Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header.
def store_equal(self): """ Takes a tetrad class object and populates array with random quartets sampled equally among splits of the tree so that deep splits are not overrepresented relative to rare splits, like those near the tips. """ with h5py.File(self.database.input, 'a') as io5: ...
Takes a tetrad class object and populates array with random quartets sampled equally among splits of the tree so that deep splits are not overrepresented relative to rare splits, like those near the tips.
def stats(self, indices=None): """ Retrieve the statistic of one or more indices (See :ref:`es-guide-reference-api-admin-indices-stats`) :keyword indices: an index or a list of indices """ path = self.conn._make_path(indices, (), "_stats") return self.conn._send_...
Retrieve the statistic of one or more indices (See :ref:`es-guide-reference-api-admin-indices-stats`) :keyword indices: an index or a list of indices
def open(filename, frame='unspecified'): """Creates a PointCloudImage from a file. Parameters ---------- filename : :obj:`str` The file to load the data from. Must be one of .png, .jpg, .npy, or .npz. frame : :obj:`str` A string representing ...
Creates a PointCloudImage from a file. Parameters ---------- filename : :obj:`str` The file to load the data from. Must be one of .png, .jpg, .npy, or .npz. frame : :obj:`str` A string representing the frame of reference in which the new image ...
def _get_result_constructor(self): """ Returns a function that will be used to instantiate query results """ if not self._values_list: # we want models return lambda rows: self.model._construct_instance(rows) elif self._flat_values_list: # the user has requested flattened list (1 val...
Returns a function that will be used to instantiate query results
def leave_command_mode(self, append_to_history=False): """ Leave the command/prompt mode. """ client_state = self.get_client_state() client_state.command_buffer.reset(append_to_history=append_to_history) client_state.prompt_buffer.reset(append_to_history=True) c...
Leave the command/prompt mode.
def _merge_common_bands(rasters): # type: (List[_Raster]) -> List[_Raster] """Combine the common bands. """ # Compute band order all_bands = IndexedSet([rs.band_names[0] for rs in rasters]) def key(rs): return all_bands.index(rs.band_names[0]) rasters_final = [] # type: List[_Ras...
Combine the common bands.
def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]: """ Load and pre-process the images specified with absolute paths. :param image_paths: List of images specified with paths. :param image_size: Tuple to resize the image to (Channels, Height, Width) :return: A...
Load and pre-process the images specified with absolute paths. :param image_paths: List of images specified with paths. :param image_size: Tuple to resize the image to (Channels, Height, Width) :return: A list of loaded images (numpy arrays).
def filter_single_grain(self): ''' This subroutine is to filter out single grains. It is kind of useless if you have tons of data still in the list. To work on there, you have other filters (filter_desc and filter_data) available! This filter gives an index to every grain, plots...
This subroutine is to filter out single grains. It is kind of useless if you have tons of data still in the list. To work on there, you have other filters (filter_desc and filter_data) available! This filter gives an index to every grain, plots the most important information, and then a...
def mass_3d(self, r, kwargs, bool_list=None): """ computes the mass within a 3d sphere of radius r :param r: radius (in angular units) :param kwargs: list of keyword arguments of lens model parameters matching the lens model classes :param bool_list: list of bools that are part ...
computes the mass within a 3d sphere of radius r :param r: radius (in angular units) :param kwargs: list of keyword arguments of lens model parameters matching the lens model classes :param bool_list: list of bools that are part of the output :return: mass (in angular units, modulo epsi...
def name(self): '''Returns the name of this template (if created from a file) or "string" if not''' if self.mako_template.filename: return os.path.basename(self.mako_template.filename) return 'string'
Returns the name of this template (if created from a file) or "string" if not
def _reconstruct_object(typ, obj, axes, dtype): """Reconstruct an object given its type, raw value, and possibly empty (None) axes. Parameters ---------- typ : object A type obj : object The value to use in the type constructor axes : dict The axes to use to construc...
Reconstruct an object given its type, raw value, and possibly empty (None) axes. Parameters ---------- typ : object A type obj : object The value to use in the type constructor axes : dict The axes to use to construct the resulting pandas object Returns ------- ...
def _parse(self, r, length): """Raises BitReaderError""" def bits_left(): return length * 8 - r.get_position() self.audioObjectType = self._get_audio_object_type(r) self.samplingFrequency = self._get_sampling_freq(r) self.channelConfiguration = r.bits(4) se...
Raises BitReaderError
def version(self): """Return version from installed packages """ if self.find: return self.meta.sp + split_package(self.find)[1] return ""
Return version from installed packages
def _set_logger(self): """change log format.""" self.logger.propagate = False hdl = logging.StreamHandler() fmt_str = '[querier][%(levelname)s] %(message)s' hdl.setFormatter(logging.Formatter(fmt_str)) self.logger.addHandler(hdl)
change log format.
def GetFileObjectByPathSpec(self, path_spec): """Retrieves a file-like object for a path specification. Args: path_spec (PathSpec): a path specification. Returns: FileIO: a file-like object or None if not available. """ file_entry = self.GetFileEntryByPathSpec(path_spec) if not fil...
Retrieves a file-like object for a path specification. Args: path_spec (PathSpec): a path specification. Returns: FileIO: a file-like object or None if not available.
def status(self, job_ids): ''' Get the status of a list of jobs identified by the job identifiers returned from the submit request. Args: - job_ids (list) : A list of job identifiers Returns: - A list of status from ['PENDING', 'RUNNING', 'CANCELLED', 'COMPLET...
Get the status of a list of jobs identified by the job identifiers returned from the submit request. Args: - job_ids (list) : A list of job identifiers Returns: - A list of status from ['PENDING', 'RUNNING', 'CANCELLED', 'COMPLETED', 'FAILED', 'TIMEOUT'...
def get_connected_devices(): """ Return an array of all mbed boards connected """ all_daplinks = [] all_interfaces = _get_interfaces() for interface in all_interfaces: try: new_daplink = DAPAccessCMSISDAP(None, interface=interface) ...
Return an array of all mbed boards connected
def set_app(name, site, settings=None): # pylint: disable=anomalous-backslash-in-string ''' .. versionadded:: 2017.7.0 Set the value of the setting for an IIS web application. .. note:: This function only configures existing app. Params are case sensitive. :param str name: The IIS app...
.. versionadded:: 2017.7.0 Set the value of the setting for an IIS web application. .. note:: This function only configures existing app. Params are case sensitive. :param str name: The IIS application. :param str site: The IIS site name. :param str settings: A dictionary of the setting n...
def get_mock_personalization_dict(): """Get a dict of personalization mock.""" mock_pers = dict() mock_pers['to_list'] = [To("test1@example.com", "Example User"), To("test2@example.com", "Example User")] mo...
Get a dict of personalization mock.
def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # th...
Reimplemented for IPython-style traceback formatting.
def released(self, unit, lock, timestamp): '''Called on the leader when it has released a lock. By default, does nothing but log messages. Override if you need to perform additional housekeeping when a lock is released, for example recording timestamps. ''' interval = _u...
Called on the leader when it has released a lock. By default, does nothing but log messages. Override if you need to perform additional housekeeping when a lock is released, for example recording timestamps.
def p_suffix(self, length=None, elipsis=False): "Return the rest of the input" if length is not None: result = self.input[self.pos:self.pos + length] if elipsis and len(result) == length: result += "..." return result return self.input[self.pos...
Return the rest of the input
def on_message(self, ws, message): """ Todo """ m = json.loads(message) self.logger.debug(m) if m.get("s", 0): self.sequence = m["s"] if m["op"] == self.DISPATCH: if m["t"] == "READY": for channel in m["d"]["private_channels"]: if len(channel["recipients"]) == 1: ...
Todo
def pause_writing(self): '''Transport calls when the send buffer is full.''' if not self.is_closing(): self._can_send.clear() self.transport.pause_reading()
Transport calls when the send buffer is full.
def abs(x, context=None): """ Return abs(x). """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_abs, (BigFloat._implicit_convert(x),), context, )
Return abs(x).
def angular_errors(hyp_axes): """ Minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution. Ordered as [minimum, maximum] angular error. """ # Not quite sure why this is sqrt but it is empirically correct ax = N.sqrt(hyp_axes) return tuple(N.arctan2(a...
Minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution. Ordered as [minimum, maximum] angular error.
def add_on_connection_close_callback(self): """ Add an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ self._logger.debug('Adding connection close callback') self._connection.add_on_close_callback(self....
Add an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly.
def get_bootstrap_from_recipes(cls, recipes, ctx): '''Returns a bootstrap whose recipe requirements do not conflict with the given recipes.''' info('Trying to find a bootstrap that matches the given recipes.') bootstraps = [cls.get_bootstrap(name, ctx) for name in c...
Returns a bootstrap whose recipe requirements do not conflict with the given recipes.
def get_diff_endpoints_from_commit_range(repo, commit_range): """Get endpoints of a diff given a commit range The resulting endpoints can be diffed directly:: a, b = get_diff_endpoints_from_commit_range(repo, commit_range) a.diff(b) For details on specifying git diffs, see ``git diff --he...
Get endpoints of a diff given a commit range The resulting endpoints can be diffed directly:: a, b = get_diff_endpoints_from_commit_range(repo, commit_range) a.diff(b) For details on specifying git diffs, see ``git diff --help``. For details on specifying revisions, see ``git help revisio...
def _subset_by_support(orig_vcf, cmp_calls, data): """Subset orig_vcf to calls also present in any of the comparison callers. """ cmp_vcfs = [x["vrn_file"] for x in cmp_calls] out_file = "%s-inensemble.vcf.gz" % utils.splitext_plus(orig_vcf)[0] if not utils.file_uptodate(out_file, orig_vcf): ...
Subset orig_vcf to calls also present in any of the comparison callers.
def reverse_dependencies(self, ireqs): """ Returns a lookup table of reverse dependencies for all the given ireqs. Since this is all static, it only works if the dependency cache contains the complete data, otherwise you end up with a partial view. This is typically no problem i...
Returns a lookup table of reverse dependencies for all the given ireqs. Since this is all static, it only works if the dependency cache contains the complete data, otherwise you end up with a partial view. This is typically no problem if you use this function after the entire dependency...
def prompt(test_input = None): """ Prompt function that works for Python2 and Python3 :param test_input: Value to be returned when testing :return: Value typed by user (or passed in argument when testing) """ if test_input != None: if type(te...
Prompt function that works for Python2 and Python3 :param test_input: Value to be returned when testing :return: Value typed by user (or passed in argument when testing)
def drop_genes(self, build=None): """Delete the genes collection""" if build: LOG.info("Dropping the hgnc_gene collection, build %s", build) self.hgnc_collection.delete_many({'build': build}) else: LOG.info("Dropping the hgnc_gene collection") self...
Delete the genes collection
def check_array_struct(array): """ Check to ensure arrays are symmetrical, for example: [[1, 2, 3], [1, 2]] is invalid """ #If a list is transformed into a numpy array and the sub elements #of this array are still lists, then numpy failed to fully convert #the list, meaning it is no...
Check to ensure arrays are symmetrical, for example: [[1, 2, 3], [1, 2]] is invalid
def stock2fa(stock): """ convert stockholm to fasta """ seqs = {} for line in stock: if line.startswith('#') is False and line.startswith(' ') is False and len(line) > 3: id, seq = line.strip().split() id = id.rsplit('/', 1)[0] id = re.split('[0-9]\|', id,...
convert stockholm to fasta
def has_edge(self, edge): """ Return whether an edge exists. @type edge: tuple @param edge: Edge. @rtype: boolean @return: Truth-value for edge existence. """ u, v = edge return (u, v) in self.edge_properties
Return whether an edge exists. @type edge: tuple @param edge: Edge. @rtype: boolean @return: Truth-value for edge existence.
def get(self, column_name): """ Retrieve a column from the list with name value :code:`column_name` :param str column_name: The name of the column to get :return: :class:`~giraffez.types.Column` with the specified name, or :code:`None` if it does not exist. """ column_na...
Retrieve a column from the list with name value :code:`column_name` :param str column_name: The name of the column to get :return: :class:`~giraffez.types.Column` with the specified name, or :code:`None` if it does not exist.
def unmount(self): """Unmounts the sftp system if it's currently mounted.""" if not self.mounted: return # Try to unmount properly. cmd = 'fusermount -u %s' % self.mount_point_local shell_exec(cmd) # The filesystem is probably still in use. # kill ss...
Unmounts the sftp system if it's currently mounted.
def kitchen_merge(backend, source_kitchen, target_kitchen): """ Merge two Kitchens """ click.secho('%s - Merging Kitchen %s into Kitchen %s' % (get_datetime(), source_kitchen, target_kitchen), fg='green') check_and_print(DKCloudCommandRunner.merge_kitchens_improved(backend.dki, source_kitchen, targe...
Merge two Kitchens
def remove_overlap(self, begin, end=None): """ Removes all intervals overlapping the given point or range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range (this is 1 for a point) """ ...
Removes all intervals overlapping the given point or range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range (this is 1 for a point)
def LookupChain(lookup_func_list): """Returns a *function* suitable for passing as the more_formatters argument to Template. NOTE: In Java, this would be implemented using the 'Composite' pattern. A *list* of formatter lookup function behaves the same as a *single* formatter lookup funcion. Note the dist...
Returns a *function* suitable for passing as the more_formatters argument to Template. NOTE: In Java, this would be implemented using the 'Composite' pattern. A *list* of formatter lookup function behaves the same as a *single* formatter lookup funcion. Note the distinction between formatter *lookup* funct...
def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.bbio_gpio.wait_for_edge(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge])
Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH.
def attachviewers(self, profiles): """Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate""" if self.metadata: template = None for profile in profiles: if isinstance(self, CLAMInputFile): ...
Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate
def write_crc32(fo, bytes): """A 4-byte, big-endian CRC32 checksum""" data = crc32(bytes) & 0xFFFFFFFF fo.write(pack('>I', data))
A 4-byte, big-endian CRC32 checksum
def generate_entry_label(entry): """ Generates a label for the pourbaix plotter Args: entry (PourbaixEntry or MultiEntry): entry to get a label for """ if isinstance(entry, MultiEntry): return " + ".join([latexify_ion(e.name) for e in entry.entry_list]) else: return late...
Generates a label for the pourbaix plotter Args: entry (PourbaixEntry or MultiEntry): entry to get a label for
def get_atoms(structure, **kwargs): """ Returns ASE Atoms object from pymatgen structure. Args: structure: pymatgen.core.structure.Structure **kwargs: other keyword args to pass into the ASE Atoms constructor Returns: ASE Atoms object """ ...
Returns ASE Atoms object from pymatgen structure. Args: structure: pymatgen.core.structure.Structure **kwargs: other keyword args to pass into the ASE Atoms constructor Returns: ASE Atoms object
def _parse_acl_config(self, acl_config): """Parse configured ACLs and rules ACLs are returned as a dict of rule sets: {<eos_acl1_name>: set([<eos_acl1_rules>]), <eos_acl2_name>: set([<eos_acl2_rules>]), ..., } """ parsed_acls = dict() for acl in...
Parse configured ACLs and rules ACLs are returned as a dict of rule sets: {<eos_acl1_name>: set([<eos_acl1_rules>]), <eos_acl2_name>: set([<eos_acl2_rules>]), ..., }
def _gen_last_current_relation(self, post_id): ''' Generate the relation for the post and last post viewed. ''' last_post_id = self.get_secure_cookie('last_post_uid') if last_post_id: last_post_id = last_post_id.decode('utf-8') self.set_secure_cookie('last_pos...
Generate the relation for the post and last post viewed.
def update_attributes(self, updates): """Update attributes.""" if not isinstance(updates, dict): updates = updates.to_dict() for sdk_key, spec_key in self._get_attributes_map().items(): attr = '_%s' % sdk_key if spec_key in updates and not hasattr(self, attr):...
Update attributes.
def deaccent(text): """ Remove accentuation from the given string. """ norm = unicodedata.normalize("NFD", text) result = "".join(ch for ch in norm if unicodedata.category(ch) != 'Mn') return unicodedata.normalize("NFC", result)
Remove accentuation from the given string.
def _handle_aui(self, data): """ Handle AUI messages. :param data: RF message to parse :type data: string :returns: :py:class`~alarmdecoder.messages.AUIMessage` """ msg = AUIMessage(data) self.on_aui_message(message=msg) return msg
Handle AUI messages. :param data: RF message to parse :type data: string :returns: :py:class`~alarmdecoder.messages.AUIMessage`
def clear(self): """ Clear the internal (private) variables of the class. """ self.filename = '' self.filehandler = 0 # Station name, identification and revision year: self.station_name = '' self.rec_dev_id = '' self.rev_year = 0000 # Numbe...
Clear the internal (private) variables of the class.
def process_function(self, call_node, definition): """Processes a user defined function when it is called. Increments self.function_call_index each time it is called, we can refer to it as N in the comments. Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode. (save_local_scope) ...
Processes a user defined function when it is called. Increments self.function_call_index each time it is called, we can refer to it as N in the comments. Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode. (save_local_scope) Create e.g. temp_N_def_arg1 = call_arg1_label_visitor.resul...
def _ge_from_lt(self, other): """Return a >= b. Computed by @total_ordering from (not a < b).""" op_result = self.__lt__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Return a >= b. Computed by @total_ordering from (not a < b).
def find_egg_entry_point(self, object_type, name=None): """ Returns the (entry_point, protocol) for the with the given ``name``. """ if name is None: name = 'main' possible = [] for protocol_options in object_type.egg_protocols: for protoco...
Returns the (entry_point, protocol) for the with the given ``name``.
def trim_args(kwds): """Gets rid of args with value of None, as well as select keys.""" reject_key = ("type", "types", "configure") reject_val = (None, ()) kwargs = { k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val } for k, v in kwargs.items(): if k i...
Gets rid of args with value of None, as well as select keys.
def find(self, group=None, element=None, name=None, VR=None): """ Searches for data elements in the DICOM file given the filters supplied to this method. :param group: Hex decimal for the group of a DICOM element e.g. 0x002 :param element: Hex decimal for the element value of a DICOM el...
Searches for data elements in the DICOM file given the filters supplied to this method. :param group: Hex decimal for the group of a DICOM element e.g. 0x002 :param element: Hex decimal for the element value of a DICOM element e.g. 0x0010 :param name: Name of the DICOM element, e.g. "Mo...
def get_snippet_by_name(cls, name): """name is in dotted format, e.g. topsnippet.something.wantedsnippet""" name_with_dir_separators = name.replace('.', os.path.sep) loaded = yaml_loader.YamlLoader.load_yaml_by_relpath(cls.snippets_dirs, ...
name is in dotted format, e.g. topsnippet.something.wantedsnippet
def _check_inputs(z, m): """Check inputs are arrays of same length or array and a scalar.""" try: nz = len(z) z = np.array(z) except TypeError: z = np.array([z]) nz = len(z) try: nm = len(m) m = np.array(m) except TypeError: m = np.array([m]) ...
Check inputs are arrays of same length or array and a scalar.
def parse(self, data): """ Converts a NetJSON 'NetworkGraph' object to a NetworkX Graph object,which is then returned. Additionally checks for protocol version, revision and metric. """ graph = self._init_graph() # ensure is NetJSON NetworkGraph object if ...
Converts a NetJSON 'NetworkGraph' object to a NetworkX Graph object,which is then returned. Additionally checks for protocol version, revision and metric.
def get_smart_contract_event_by_height(self, height: int, is_full: bool = False) -> List[dict]: """ This interface is used to get the corresponding smart contract event based on the height of block. :param height: a decimal height value. :param is_full: :return: the information ...
This interface is used to get the corresponding smart contract event based on the height of block. :param height: a decimal height value. :param is_full: :return: the information of smart contract event in dictionary form.
def _kp2(A, B): """Special case Kronecker tensor product of A[i] and B[i] at each time interval i for i = 0 .. N-1 Specialized for the case A and B rank 3 with A.shape[0]==B.shape[0] """ N = A.shape[0] if B.shape[0] != N: raise(ValueError) newshape1 = A.shape[1]*B.shape[1] return...
Special case Kronecker tensor product of A[i] and B[i] at each time interval i for i = 0 .. N-1 Specialized for the case A and B rank 3 with A.shape[0]==B.shape[0]
def create_storage_account(access_token, subscription_id, rgname, account_name, location, storage_type='Standard_LRS'): '''Create a new storage account in the named resource group, with the named location. Args: access_token (str): A valid Azure authentication token. ...
Create a new storage account in the named resource group, with the named location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account...
def add_event( request, template='swingtime/add_event.html', event_form_class=forms.EventForm, recurrence_form_class=forms.MultipleOccurrenceForm ): ''' Add a new ``Event`` instance and 1 or more associated ``Occurrence``s. Context parameters: ``dtstart`` a datetime.datetime ob...
Add a new ``Event`` instance and 1 or more associated ``Occurrence``s. Context parameters: ``dtstart`` a datetime.datetime object representing the GET request value if present, otherwise None ``event_form`` a form object for updating the event ``recurrence_form`` a fo...
def tai_jd(self, jd): """Build a `Time` from a TAI Julian date. Supply the International Atomic Time (TAI) as a Julian date: >>> t = ts.tai_jd(2456675.56640625) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5) """ tai =...
Build a `Time` from a TAI Julian date. Supply the International Atomic Time (TAI) as a Julian date: >>> t = ts.tai_jd(2456675.56640625) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5)
def reset_calibrators(self, parameter): """ Reset all calibrators for the specified parameter to their original MDB value. """ req = mdb_pb2.ChangeParameterRequest() req.action = mdb_pb2.ChangeParameterRequest.RESET_CALIBRATORS calib_info = req.defaultCa...
Reset all calibrators for the specified parameter to their original MDB value.
def download_image(self, device_label, image_id, file_name): """ Download image taken by a smartcam Args: device_label (str): device label of camera image_id (str): image id from image series file_name (str): path to file """ response = None t...
Download image taken by a smartcam Args: device_label (str): device label of camera image_id (str): image id from image series file_name (str): path to file
def _create(self, title, heads, refresh=None, path_start=None): """ Internal create method, uses yattag to generate a html document with result data. :param title: Title of report :param heads: Headers for report :param refresh: If set to True, adds a HTTP-EQUIV="refresh" to the...
Internal create method, uses yattag to generate a html document with result data. :param title: Title of report :param heads: Headers for report :param refresh: If set to True, adds a HTTP-EQUIV="refresh" to the report :param path_start: path to file where this is report is to be stored...
def upload_file_and_send_file_offer(self, file_name, user_id, data=None, input_file_path=None, content_type='application/octet-stream', auto_open=False, prevent_share=False, scope='content/send'): """ Upload a file of any ty...
Upload a file of any type to store and return a FileId once file offer has been sent. No user authentication required
def run(self, host, port, **options): """For debugging purposes, you can run this as a standalone server. .. WARNING:: **Security vulnerability** This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use this in production, you should run :class:`Ser...
For debugging purposes, you can run this as a standalone server. .. WARNING:: **Security vulnerability** This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use this in production, you should run :class:`Server` as a standard WSGI app with `uWS...
def get_aws_s3_handle(config_map): """Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3 """ url = 'https://' + config_map['s3_b...
Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3
def object_formatter(v, c, m, p): """Format object view link.""" endpoint = current_app.config['PIDSTORE_OBJECT_ENDPOINTS'].get( m.object_type) if endpoint and m.object_uuid: return Markup('<a href="{0}">{1}</a>'.format( url_for(endpoint, id=m.object_uuid), _('View')...
Format object view link.
def _assert_is_color(value): """ Assert that the given value is a valid brightness. :param value: The value to check. """ if not isinstance(value, tuple) or len(value) != 3: raise ValueError("Color must be a RGB tuple.") if not all(0 <= x <= 255 for x in val...
Assert that the given value is a valid brightness. :param value: The value to check.
def plot_cost(scores=np.random.rand(100), thresh=0.5, noise=0): """Plot the cost function topology (contours for each of several targets)""" c = pd.DataFrame(index=np.arange(0, 1, 0.01)) if isinstance(thresh, (int, float)): thresh = [thresh] elif not isinstance(thresh, (pd.Series, np.ndarray, li...
Plot the cost function topology (contours for each of several targets)