code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def add_colorbar(self, **kwargs): """Draw a colorbar """ kwargs = kwargs.copy() if self._cmap_extend is not None: kwargs.setdefault('extend', self._cmap_extend) if 'label' not in kwargs: kwargs.setdefault('label', label_from_attrs(self.data)) self....
Draw a colorbar
def _execute(self, session=None): """ Initializes all components required to run a dag for a specified date range and calls helper method to execute the tasks. """ ti_status = BackfillJob._DagRunTaskStatus() start_date = self.bf_start_date # Get intervals betwee...
Initializes all components required to run a dag for a specified date range and calls helper method to execute the tasks.
def selectedLogs(self): '''Return selected log books by type.''' mcclogs = [] physlogs = [] for i in range(len(self.logMenus)): logType = self.logMenus[i].selectedType() log = self.logMenus[i].selectedProgram() if logType == "MCC": if l...
Return selected log books by type.
def smart_search_vrf(self, auth, query_str, search_options=None, extra_query=None): """ Perform a smart search on VRF list. * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] ...
Perform a smart search on VRF list. * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] Search options. See :func:`search_vrf`. * `extra_query` [dict_to_sql] ...
def delete(self, endpoint: str, **kwargs) -> dict: """HTTP DELETE operation to API endpoint.""" return self._request('DELETE', endpoint, **kwargs)
HTTP DELETE operation to API endpoint.
def substitute(progression, substitute_index, depth=0): """Give a list of possible substitutions for progression[substitute_index]. If depth > 0 the substitutions of each result will be recursively added as well. Example: >>> substitute(['I', 'IV', 'V', 'I'], 0) ['III', 'III7', 'VI', 'VI7', 'I...
Give a list of possible substitutions for progression[substitute_index]. If depth > 0 the substitutions of each result will be recursively added as well. Example: >>> substitute(['I', 'IV', 'V', 'I'], 0) ['III', 'III7', 'VI', 'VI7', 'I7']
def photos(self, query, page=1, per_page=10): """ Get a single page of photo results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: ...
Get a single page of photo results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [dict]: {u'total': 0, u'total_pages': 0, u're...
def _get_result_paths(self,data): """Return dict of {key: ResultPath} """ #clustalw .aln is used when no or unkown output type specified _treeinfo_formats = {'nj':'.nj', 'dist':'.dst', 'nexus':'.tre'} result = {} p...
Return dict of {key: ResultPath}
def _handle_redirect(self, redirect, preload, query, page): """ handle redirect """ if redirect: redirects = query["redirects"][0] if "normalized" in query: normalized = query["normalized"][0] if normalized["from"] != self.title: ...
handle redirect
def build_keys(request, database_name, collection_name): """Perform the map/reduce to refresh the keys form. The display the custom report screen""" build_keys_with_mapreduce(database_name, collection_name) messages.success(request, _( "Successfully completed MapReduce operation. " "K...
Perform the map/reduce to refresh the keys form. The display the custom report screen
def abort(err): """Abort everything, everywhere.""" if _debug: abort._debug("abort %r", err) global local_controllers # tell all the local controllers to abort for controller in local_controllers.values(): controller.abort(err)
Abort everything, everywhere.
def pwm(host, seq, m1, m2, m3, m4): """ Sends control values directly to the engines, overriding control loops. Parameters: seq -- sequence number m1 -- Integer: front left command m2 -- Integer: front right command m3 -- Integer: back right command m4 -- Integer: back left command ...
Sends control values directly to the engines, overriding control loops. Parameters: seq -- sequence number m1 -- Integer: front left command m2 -- Integer: front right command m3 -- Integer: back right command m4 -- Integer: back left command
def get_varied_cfg_lbls(cfg_list, default_cfg=None, mainkey='_cfgname', checkname=False): r""" Args: cfg_list (list): default_cfg (None): (default = None) checkname (bool): if True removes names if they are all the same. Returns: list: cfglbl_list ...
r""" Args: cfg_list (list): default_cfg (None): (default = None) checkname (bool): if True removes names if they are all the same. Returns: list: cfglbl_list CommandLine: python -m utool.util_gridsearch --exec-get_varied_cfg_lbls Example: >>> # ENABLE_D...
def set_color(fg=None, bg=None): """Set the current colors. If no arguments are given, sets default colors. """ if fg or bg: _color_manager.set_color(fg, bg) else: _color_manager.set_defaults()
Set the current colors. If no arguments are given, sets default colors.
def write_directory(self, directory: str) -> bool: """Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory.""" current_md5_hash = self.get_namespace_hash() md5_hash_path = os.path.join(directory, f'{self.module_name}.belns.md5') if not os.path.exi...
Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory.
def clean_perms(self): """ FAB leaves faulty permissions that need to be cleaned up """ self.log.debug('Cleaning faulty perms') sesh = self.get_session pvms = ( sesh.query(sqla_models.PermissionView) .filter(or_( sqla_models.Permiss...
FAB leaves faulty permissions that need to be cleaned up
def post(self, data, request, id): """ Create a new resource using POST """ if id: # can't post to individual user raise errors.MethodNotAllowed() user = self._dict_to_model(data) user.save() # according to REST, return 201 and Location header retu...
Create a new resource using POST
def force_log_type_flags(self, logType, stdoutFlag, fileFlag): """ Force a logtype logging flags. :Parameters: #. logType (string): A defined logging type. #. stdoutFlag (None, boolean): The standard output logging flag. If None, logtype stdoutFlag forcing is...
Force a logtype logging flags. :Parameters: #. logType (string): A defined logging type. #. stdoutFlag (None, boolean): The standard output logging flag. If None, logtype stdoutFlag forcing is released. #. fileFlag (None, boolean): The file logging flag. ...
def action_notify(self, action): """ Notify all subscribers of an action status change. action -- the action whose status changed """ message = json.dumps({ 'messageType': 'actionStatus', 'data': action.as_action_description(), }) for sub...
Notify all subscribers of an action status change. action -- the action whose status changed
def get_drive_api_from_client_secrets(path, reset_creds=False): """ Reads the local client secrets file if available (otherwise, opens a browser tab to walk through the OAuth 2.0 process, and stores the client secrets for future use) and then authorizes those credentials. Returns a Google Drive API ...
Reads the local client secrets file if available (otherwise, opens a browser tab to walk through the OAuth 2.0 process, and stores the client secrets for future use) and then authorizes those credentials. Returns a Google Drive API service object.
def draw_texture(tex): """Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw. """ from .program import Program program = Program(vert_draw, frag_draw) program['u_texture'] = tex program['a_position'] = [[-1., -1.],...
Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw.
def read_string_table(xml_source): """Read in all shared strings in the table""" strings = [] src = _get_xml_iter(xml_source) for _, node in iterparse(src): if node.tag == '{%s}si' % SHEET_MAIN_NS: text = Text.from_tree(node).content text = text.replace('x005F_', '') ...
Read in all shared strings in the table
def incr(self, conn, key, increment=1): """Command is used to change data for some item in-place, incrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change ...
Command is used to change data for some item in-place, incrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param increment: ``int``, is the amount by ...
def printTPRegionParams(tpregion): """ Note: assumes we are using TemporalMemory/TPShim in the TPRegion """ tm = tpregion.getSelf()._tfdr print "------------PY TemporalMemory Parameters ------------------" print "numberOfCols =", tm.getColumnDimensions() print "cellsPerColumn =", tm...
Note: assumes we are using TemporalMemory/TPShim in the TPRegion
def get_json_lines(annotation: ResourceAnnotation, field: str, route: str, request: bool = False) -> List: """Generate documentation lines for the given annotation. This only documents schemas of type "object", or type "list" where each "item" is an object. Other types are ignored (but a...
Generate documentation lines for the given annotation. This only documents schemas of type "object", or type "list" where each "item" is an object. Other types are ignored (but a warning is logged). :param doctor.resource.ResourceAnnotation annotation: Annotation object for the associated handler ...
def get_bank_query_session(self): """Gets the OsidSession associated with the bank query service. return: (osid.assessment.BankQuerySession) - a ``BankQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_query() is f...
Gets the OsidSession associated with the bank query service. return: (osid.assessment.BankQuerySession) - a ``BankQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_query() is false`` *compliance: optional -- This ...
def _marker_line(self): # type: () -> str """Generate a correctly sized marker line. e.g. '+------------------+---------+----------+---------+' :return: str """ output = '' for col in sorted(self.col_widths): line = self.COLUMN_MARK + (self....
Generate a correctly sized marker line. e.g. '+------------------+---------+----------+---------+' :return: str
def dimensions_unit(self, dimensions_unit): """Sets the dimensions_unit of this MeasurementSettings. :param dimensions_unit: The dimensions_unit of this MeasurementSettings. :type: str """ allowed_values = ["inch", "cm", "foot", "meter"] # noqa: E501 if dimensions_unit...
Sets the dimensions_unit of this MeasurementSettings. :param dimensions_unit: The dimensions_unit of this MeasurementSettings. :type: str
def evaluated_variants(self, case_id): """Returns variants that has been evaluated Return all variants, snvs/indels and svs from case case_id which have a entry for 'acmg_classification', 'manual_rank', 'dismiss_variant' or if they are commented. Args: case_id(str) ...
Returns variants that has been evaluated Return all variants, snvs/indels and svs from case case_id which have a entry for 'acmg_classification', 'manual_rank', 'dismiss_variant' or if they are commented. Args: case_id(str) Returns: variants(iterable(Va...
def merge_strings_files(old_strings_file, new_strings_file): """ Merges the old strings file with the new one. Args: old_strings_file (str): The path to the old strings file (previously produced, and possibly altered) new_strings_file (str): The path to the new strings file (newly produced). ...
Merges the old strings file with the new one. Args: old_strings_file (str): The path to the old strings file (previously produced, and possibly altered) new_strings_file (str): The path to the new strings file (newly produced).
def Get(self): """Return a GrrMessage instance from the transaction log or None.""" try: with io.open(self.logfile, "rb") as fd: data = fd.read(self.max_log_size) except (IOError, OSError): return try: if data: return rdf_flows.GrrMessage.FromSerializedString(data) ...
Return a GrrMessage instance from the transaction log or None.
def needle(reference, query, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Do a Needleman-Wunsch alignment. :param reference: Reference sequence. :type reference: coral.DNA :param query: Sequence to align against the reference. :type query: coral.DNA :param gapopen: Penal...
Do a Needleman-Wunsch alignment. :param reference: Reference sequence. :type reference: coral.DNA :param query: Sequence to align against the reference. :type query: coral.DNA :param gapopen: Penalty for opening a gap. :type gapopen: float :param gapextend: Penalty for extending a gap. ...
def getExtensionList(self,extensions): """ This is an internal method that transforms the comma-separated extensions string into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3']. If MapConstants.placeholderNoExtensionFilter is part of the string, th...
This is an internal method that transforms the comma-separated extensions string into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3']. If MapConstants.placeholderNoExtensionFilter is part of the string, the resulting list will also contain '', i.e., files ...
def execute_shell(self, shell=None, parent_environ=None, rcfile=None, norc=False, stdin=False, command=None, quiet=False, block=None, actions_callback=None, post_actions_callback=None, context_filepath=None, start_new_session=False, detached=False, ...
Spawn a possibly-interactive shell. Args: shell: Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ: Environment to run the shell process in, if None then the current environment is used. rcfile: Specify a file ...
def _expand_dims(x, input_shape, output_shape): """Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor """ verify_no_new_dims([output_shape], input_sha...
Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor
def _parse_kraken_output(out_dir, db, data): """Parse kraken stat info comming from stderr, generating report with kraken-report """ in_file = os.path.join(out_dir, "kraken_out") stat_file = os.path.join(out_dir, "kraken_stats") out_file = os.path.join(out_dir, "kraken_summary") kraken_cm...
Parse kraken stat info comming from stderr, generating report with kraken-report
def modify_agent_property(self, agent_id, key, value): ''' modify_agent_property(self, agent_id, key, value) Modifies a single single property of an agent. If the property does not exists then it is created as a custom property. :Parameters: * *agent_id* (`string`) -- Identifie...
modify_agent_property(self, agent_id, key, value) Modifies a single single property of an agent. If the property does not exists then it is created as a custom property. :Parameters: * *agent_id* (`string`) -- Identifier of an existing agent * *key* (`string`) -- Key of a property to c...
def q(self, val): """ Setter method for q. """ self._q = np.asarray(val) self.Q = cumsum(val)
Setter method for q.
def npinterpn(*args, **kw): """Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ... """ method = kw.pop('method', 'cubic') if kw: raise ValueErro...
Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ...
def register(): """Register DDO of a new asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@context" ...
Register DDO of a new asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@context" - id ...
def connect_ssh(*args, **kwds): """ Initialize a :class:`Manager` over the SSH transport. For documentation of arguments see :meth:`ncclient.transport.SSHSession.connect`. The underlying :class:`ncclient.transport.SSHSession` is created with :data:`CAPABILITIES`. It is first instructed to ...
Initialize a :class:`Manager` over the SSH transport. For documentation of arguments see :meth:`ncclient.transport.SSHSession.connect`. The underlying :class:`ncclient.transport.SSHSession` is created with :data:`CAPABILITIES`. It is first instructed to :meth:`~ncclient.transport.SSHSession.loa...
def close(self, destroy=False, sync=False, timeout=None): """Close PV, disconnecting any clients. :param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open(). :param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies)....
Close PV, disconnecting any clients. :param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open(). :param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies). :param float timeout: Applies only when sync=True. None for...
def output(self, args): ''' Print the output message. ''' print("SensuPlugin: {}".format(' '.join(str(a) for a in args)))
Print the output message.
def verify_request(self, query, binding): """ :param query: The SAML query, transport encoded :param binding: Which binding the query came in over """ resp_args = {} if not query: logger.info("Missing QUERY") resp = Unauthorized("Unknown user") ...
:param query: The SAML query, transport encoded :param binding: Which binding the query came in over
def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, bro...
Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address.
def check_reachable(self, forced=False, test=False): # pylint: disable=too-many-branches """Check all daemons state (reachable or not) If test parameter is True, do not really send but simulate only for testing purpose... The update_infos function returns None when no ping has been exe...
Check all daemons state (reachable or not) If test parameter is True, do not really send but simulate only for testing purpose... The update_infos function returns None when no ping has been executed (too early...), or True / False according to the real ping and get managed configurati...
def make_code_obsolete(code): """ Moves folders associated with PDB code to obsolete folder in global_settings["database_dir"] Parameters ---------- code : str PDB accession code Returns ------- None """ fs = FileSystem(code=code) if os.path.exists(fs.parent_dir): ...
Moves folders associated with PDB code to obsolete folder in global_settings["database_dir"] Parameters ---------- code : str PDB accession code Returns ------- None
def delta_ps(prev, curr, counters): """ calculate the delta per second of one counter formula: (curr - prev) / delta_time :param prev: previous resource :param curr: current resource :param counters: the counter to do delta and per second, one only :return: value, NaN if invalid. """ co...
calculate the delta per second of one counter formula: (curr - prev) / delta_time :param prev: previous resource :param curr: current resource :param counters: the counter to do delta and per second, one only :return: value, NaN if invalid.
def load_swagger_config(name, base_url, config): """ Load a restful service specified by some YAML file at config_path. :param config_path: A pathlib Path object that points to the yaml config :returns: A python module containing a Client class, call factory, and the definition of each of the...
Load a restful service specified by some YAML file at config_path. :param config_path: A pathlib Path object that points to the yaml config :returns: A python module containing a Client class, call factory, and the definition of each of the APIs defined by the config.
def merge(self, dest, *others): """ Merge one or more :py:class:`HyperLogLog` instances. :param dest: Key to store merged result. :param others: One or more ``HyperLogLog`` instances. """ items = [self.key] items.extend([other.key for other in others]) se...
Merge one or more :py:class:`HyperLogLog` instances. :param dest: Key to store merged result. :param others: One or more ``HyperLogLog`` instances.
def validate(self, data): """ Runs all field validators. """ for v in self.validators: v(self, data) return data
Runs all field validators.
def update(self, byts): ''' Update all the hashes in the set with the given bytes. ''' self.size += len(byts) [h[1].update(byts) for h in self.hashes]
Update all the hashes in the set with the given bytes.
def get(self, index, n_cols=70): """ Grab the `i`th submission, with the title field formatted to fit inside of a window of width `n_cols` """ if index < 0: raise IndexError nsfw_count = 0 while index >= len(self._submission_data): try: ...
Grab the `i`th submission, with the title field formatted to fit inside of a window of width `n_cols`
def _api_path(self, item): """Get the API path for the current cursor position.""" if self.base_url is None: raise NotImplementedError("base_url not set") path = "/".join([x.blob["id"] for x in item.path]) return "/".join([self.base_url, path])
Get the API path for the current cursor position.
def send_notifications(self, notification_data): """SendNotifications. [Preview API] Send Notification :param :class:`<NotificationsData> <azure.devops.v5_1.gallery.models.NotificationsData>` notification_data: Denoting the data needed to send notification """ content = self._ser...
SendNotifications. [Preview API] Send Notification :param :class:`<NotificationsData> <azure.devops.v5_1.gallery.models.NotificationsData>` notification_data: Denoting the data needed to send notification
def mark_failed_exc(self, e_val=None, e_ty=None): '''Marks the tracer as failed with the given exception :code:`e_val` of type :code:`e_ty` (defaults to the current exception). May only be called in the started state and only if the tracer is not already marked as failed. Note that this...
Marks the tracer as failed with the given exception :code:`e_val` of type :code:`e_ty` (defaults to the current exception). May only be called in the started state and only if the tracer is not already marked as failed. Note that this does not end the tracer! Once a tracer is marked as ...
def load_template(template_name=None, template_source=None, context=None, defaults=None, template_engine='jinja', saltenv='base', template_hash=None, template_hash_name=None, s...
Renders a configuration template (default: Jinja) and loads the result on the device. By default this function will commit the changes. If there are no changes, it does not commit, discards he config and the flag ``already_configured`` will be set as ``True`` to point this out. To avoid committing the...
def get_line(self, text, on_unicode_error='strict'): """ Split a line of text into words and labels. Labels must start with the prefix used to create the model (__label__ by default). """ def check(entry): if entry.find('\n') != -1: raise ValueError( ...
Split a line of text into words and labels. Labels must start with the prefix used to create the model (__label__ by default).
def json_safe(string, content_type='application/octet-stream'): """Returns JSON-safe version of `string`. If `string` is a Unicode string or a valid UTF-8, it is returned unmodified, as it can safely be encoded to JSON string. If `string` contains raw/binary data, it is Base64-encoded, formatted and ...
Returns JSON-safe version of `string`. If `string` is a Unicode string or a valid UTF-8, it is returned unmodified, as it can safely be encoded to JSON string. If `string` contains raw/binary data, it is Base64-encoded, formatted and returned according to "data" URL scheme (RFC2397). Since JSON is not...
def run_command(command, capture=None, check=False, encoding='utf-8', shell=False, env=None): """This function provides a convenient API wrapping subprocess.Popen. Captured output is guaranteed not to deadlock, but will still reside in memory in the end. :param command: The command to run in a subprocess. ...
This function provides a convenient API wrapping subprocess.Popen. Captured output is guaranteed not to deadlock, but will still reside in memory in the end. :param command: The command to run in a subprocess. :type command: ``str`` or ``list`` of ``str`` :param capture: The method of output capture: ...
def transform(images, out_dir, fname): """ Combines a list of images into a single sprite returning meta information """ from PIL import Image as PILImage base = os.path.join(out_dir, "media", "images") width, height = images[0].image.size num_images_to_log = len(...
Combines a list of images into a single sprite returning meta information
def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False): """ Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. ...
Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. addr: a ZMQ socket endpoint. hwm (int): ZMQ high-water mark (buffe...
def draw_circle(ctx, x, y, radius, cairo_color): """ Draw a circle. :param radius: radius in pixels :param cairo_color: normalized rgb color """ ctx.new_path() ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue) ctx.arc(x, y, radius, 0, 2 * pi) ctx.fill()
Draw a circle. :param radius: radius in pixels :param cairo_color: normalized rgb color
def run_simulation(projectname: str, xmlfile: str): """Perform a HydPy workflow in agreement with the given XML configuration file available in the directory of the given project. ToDo Function |run_simulation| is a "script function" and is normally used as explained in the main documentation on module...
Perform a HydPy workflow in agreement with the given XML configuration file available in the directory of the given project. ToDo Function |run_simulation| is a "script function" and is normally used as explained in the main documentation on module |xmltools|.
def _neg(node): """Return the inverse of *node*.""" if node is BDDNODEZERO: return BDDNODEONE elif node is BDDNODEONE: return BDDNODEZERO else: return _bddnode(node.root, _neg(node.lo), _neg(node.hi))
Return the inverse of *node*.
def collect(self): """ Overrides the Collector.collect method """ metrics = {} if 'scan' in self.config: for ld in os.listdir(self.config['owfs']): if '.' in ld: self.read_values(ld, self.config['scan'], metrics) for oid,...
Overrides the Collector.collect method
def double(window, config): """Double theme ================== = Header = ================== = items = ================== = footer = ================== """ cordx = round(config.get('cordx', 0)) color = config.get('color', red) icon = config.get('...
Double theme ================== = Header = ================== = items = ================== = footer = ==================
def remove_lower_overlapping(current, higher): """ >>> remove_lower_overlapping([], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 0, 4)], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 5, 6)], [('a', 0, 5)]) [('z', 5, 6), ('a', 0, 5)] """ for (mat...
>>> remove_lower_overlapping([], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 0, 4)], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 5, 6)], [('a', 0, 5)]) [('z', 5, 6), ('a', 0, 5)]
def get_config(name='root'): ''' Retrieves all values from a given configuration CLI example: .. code-block:: bash salt '*' snapper.get_config ''' try: config = snapper.GetConfig(name) return config except dbus.DBusException as exc: raise CommandExecutionErro...
Retrieves all values from a given configuration CLI example: .. code-block:: bash salt '*' snapper.get_config
def _inv_sqrtm(x): '''Computes x^(-1/2)''' vals, vecs = np.linalg.eigh(x) return (vecs / np.sqrt(vals)).dot(vecs.T)
Computes x^(-1/2)
def is_timestamp_valid(self, timestamp): """Timestamp must be string in %Y-%m-%dT%H:%M:%S. format """ try: timestamp_server = datetime.utcnow() timestamp_client = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S") d1_ts = time.mktime(timestamp_client.timetuple()) ...
Timestamp must be string in %Y-%m-%dT%H:%M:%S. format
def get_caller_name(N=0, strict=True): """ Standalone version of get_caller_name """ if isinstance(N, (list, tuple)): name_list = [] for N_ in N: try: name_list.append(get_caller_name(N_)) except AssertionError: name_list.append('X') ...
Standalone version of get_caller_name
def multikey_sort(items, columns): """Source: https://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys """ comparers = [ ((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in columns ] def cmp(...
Source: https://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys
def choose_coord_units(header): """Return the appropriate key code for the units value for the axes by examining the FITS header. """ cunit = header['CUNIT1'] match = re.match(r'^deg\s*$', cunit) if match: return 'degree' # raise WCSError("Don't understand units '%s'" % (cunit)) ...
Return the appropriate key code for the units value for the axes by examining the FITS header.
def text_index(self): '''Returns the one-based index of the current text node.''' # This is the number of text nodes we've seen so far. # If we are currently in a text node, great; if not then add # one for the text node that's about to begin. i = self.tags.get(TextElement, 0) ...
Returns the one-based index of the current text node.
def follow(self): """ Follow a user." """ data = json.dumps({"action": "follow"}) r = requests.post( "https://kippt.com/api/users/%s/relationship" % (self.id), headers=self.kippt.header, data=data ) return (r.json())
Follow a user."
def add_physical_item(self, instance, item): """ Add a physical item e.g router, cloud etc :param instance: Hypervisor instance :param item: Item to add """ (name, dev_type) = self.device_typename(item) self.topology['devices'][name] = {} self.topology['d...
Add a physical item e.g router, cloud etc :param instance: Hypervisor instance :param item: Item to add
def pl (listoflists): """ Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None """ for row in listoflists: if row[-1] == '\n': print(row, end=' ') else: print(row) return None
Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None
def branches(self): """ #TODO: description """ for branch in self._grid.graph_edges(): if branch['branch'].ring == self: yield branch
#TODO: description
def createProduct(self, powerups): """ Create a new L{Product} instance which confers the given powerups. @type powerups: C{list} of powerup item types @rtype: L{Product} @return: The new product instance. """ types = [qual(powerup).decode('ascii') ...
Create a new L{Product} instance which confers the given powerups. @type powerups: C{list} of powerup item types @rtype: L{Product} @return: The new product instance.
def _rel(self, copy=False): """ Get descriptive kwargs of the container (e.g. name, description, meta). """ rel = {} for key, obj in vars(self).items(): if not isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)) and not key.startswith('_'):...
Get descriptive kwargs of the container (e.g. name, description, meta).
def relative_symlink(target, link_name): """Make a symlink to target using the shortest possible relative path.""" link_name = os.path.abspath(link_name) abs_target = os.path.abspath(target) rel_target = os.path.relpath(target, os.path.dirname(link_name)) if os.path.exists(link_name): os.re...
Make a symlink to target using the shortest possible relative path.
def verify_client(endpoint_context, request, authorization_info): """ Initiated Guessing ! :param endpoint_context: SrvInfo instance :param request: The request :param authorization_info: Client authentication information :return: dictionary containing client id, client authentication method an...
Initiated Guessing ! :param endpoint_context: SrvInfo instance :param request: The request :param authorization_info: Client authentication information :return: dictionary containing client id, client authentication method and possibly access token.
def RequestPacket(self): """Create a ready-to-transmit authentication request packet. Return a RADIUS packet which can be directly transmitted to a RADIUS server. :return: raw packet :rtype: string """ attr = self._PktEncodeAttributes() if self.authenti...
Create a ready-to-transmit authentication request packet. Return a RADIUS packet which can be directly transmitted to a RADIUS server. :return: raw packet :rtype: string
def _populate_ha_information(self, context, router): """To be called when router information, including router interface list, (for the l3_cfg_agent) has been collected so it is extended with ha information. """ r_r_b = self._get_redundancy_router_bindings( context, r...
To be called when router information, including router interface list, (for the l3_cfg_agent) has been collected so it is extended with ha information.
def add_app_template_filter(self, f, name=None): """Register a custom template filter, available application wide. Like :meth:`Flask.add_template_filter` but for a blueprint. Works exactly like the :meth:`app_template_filter` decorator. :param name: the optional name of the filter, ot...
Register a custom template filter, available application wide. Like :meth:`Flask.add_template_filter` but for a blueprint. Works exactly like the :meth:`app_template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used.
def identify_and_tag_URLs(line): """Given a reference line, identify URLs in the line, record the information about them, and replace them with a "<cds.URL />" tag. URLs are identified in 2 forms: + Raw: http://invenio-software.org/ + HTML marked-up: <a href="http://invenio-software.or...
Given a reference line, identify URLs in the line, record the information about them, and replace them with a "<cds.URL />" tag. URLs are identified in 2 forms: + Raw: http://invenio-software.org/ + HTML marked-up: <a href="http://invenio-software.org/">CERN Document Server Softw...
def is_suspicious( pe ): """ unusual locations of import tables non recognized section names presence of long ASCII strings """ relocations_overlap_entry_point = False sequential_relocs = 0 # If relocation data is found and the entries go over the entry point, and also are very # c...
unusual locations of import tables non recognized section names presence of long ASCII strings
def diff_values(value_a, value_b, raw=False): """Returns a human-readable diff between two values :param value_a: First value to compare :param value_b: Second value to compare :param raw: True to compare the raw values, e.g. UIDs :returns a list of diff tuples """ if not raw: valu...
Returns a human-readable diff between two values :param value_a: First value to compare :param value_b: Second value to compare :param raw: True to compare the raw values, e.g. UIDs :returns a list of diff tuples
def dSbr_dV(Yf, Yt, V, buses, branches): """ Computes the branch power flow vector and the partial derivative of branch power flow w.r.t voltage. """ nl = len(branches) nb = len(V) f = matrix([l.from_bus._i for l in branches]) t = matrix([l.to_bus._i for l in branches]) # Compute c...
Computes the branch power flow vector and the partial derivative of branch power flow w.r.t voltage.
def plot_resp_slow(signal, rect_signal, sample_rate): """ ----- Brief ----- Figure intended to represent the acquired RIP signal together with a rectangular signal defining inhalation and exhalation periods. ----------- Description ----------- Function design to generate a Bokeh...
----- Brief ----- Figure intended to represent the acquired RIP signal together with a rectangular signal defining inhalation and exhalation periods. ----------- Description ----------- Function design to generate a Bokeh figure containing the evolution of RIP signal, when slow resp...
def _compute_mean(self, C, A1, A2, A3, A4, A5, A6, mag, hypo_depth, rrup, mean, idx): """ Compute mean for subduction interface events, as explained in table 2, page 67. """ mean[idx] = (A1 + A2 * mag + C['C1'] + C['C2'] * (A3 - mag) ** 3 + ...
Compute mean for subduction interface events, as explained in table 2, page 67.
def do_get_page(parser, token): """Retrieve a page and insert into the template's context. Example:: {% get_page "news" as news_page %} :param page: the page object, slug or id :param name: name of the context variable to store the page in """ bits = token.split_contents() if 4 !=...
Retrieve a page and insert into the template's context. Example:: {% get_page "news" as news_page %} :param page: the page object, slug or id :param name: name of the context variable to store the page in
async def login(self, user=DEFAULT_USER, password=DEFAULT_PASSWORD, account=DEFAULT_ACCOUNT): """ :py:func:`asyncio.coroutine` Server authentication. :param user: username :type user: :py:class:`str` :param password: password :type password:...
:py:func:`asyncio.coroutine` Server authentication. :param user: username :type user: :py:class:`str` :param password: password :type password: :py:class:`str` :param account: account (almost always blank) :type account: :py:class:`str` :raises aioftp...
def search(cls, args): """Search for NApps in NApps server matching a pattern.""" safe_shell_pat = re.escape(args['<pattern>']).replace(r'\*', '.*') pat_str = '.*{}.*'.format(safe_shell_pat) pattern = re.compile(pat_str, re.IGNORECASE) remote_json = NAppsManager.search(pattern) ...
Search for NApps in NApps server matching a pattern.
def logger(self): """:class:`logging.Logger` of this instance""" if not self.is_main: return self.main.logger try: return self._logger except AttributeError: name = '%s.%s.%s' % (self.__module__, self.__class__.__name__, ...
:class:`logging.Logger` of this instance
def downloadarchive(self, project, targetfile, archiveformat = 'zip'): """Download all output files as a single archive: * *targetfile* - path for the new local file to be written * *archiveformat* - the format of the archive, can be 'zip','gz','bz2' Example:: client.downl...
Download all output files as a single archive: * *targetfile* - path for the new local file to be written * *archiveformat* - the format of the archive, can be 'zip','gz','bz2' Example:: client.downloadarchive("myproject","allresults.zip","zip")
def _timestep_cull(self, timestep): """Cull out values that do not fit a timestep.""" new_values = [] new_datetimes = [] mins_per_step = int(60 / timestep) for i, date_t in enumerate(self.datetimes): if date_t.moy % mins_per_step == 0: new_datetimes.ap...
Cull out values that do not fit a timestep.
def set_session_data(self, session_data): ''' Set session data in the container enclosed fields :param session_data: dictionary of session data ''' if session_data: for field in self._fields: if isinstance(field, (Container, Dynamic)): ...
Set session data in the container enclosed fields :param session_data: dictionary of session data
def signal(*args, **kwargs): from .core import Signal """A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signa...
A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signal(SignalOptions.EXEC_CONCURRENT) def validation_function(ar...