code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def inet_ntoa(address): """Convert a network format IPv6 address into text. @param address: the binary address @type address: string @rtype: string @raises ValueError: the address isn't 16 bytes long """ if len(address) != 16: raise ValueError("IPv6 addresses are 16 bytes long") ...
Convert a network format IPv6 address into text. @param address: the binary address @type address: string @rtype: string @raises ValueError: the address isn't 16 bytes long
def initialize_sentry_integration(): # pragma: no cover """\ Used to optionally initialize the Sentry service with this app. See https://docs.sentry.io/platforms/python/pyramid/ """ # This function is not under coverage because it is boilerplate # from the Sentry documentation. try: ...
\ Used to optionally initialize the Sentry service with this app. See https://docs.sentry.io/platforms/python/pyramid/
def _parse_effects(self, effects_json=None): # type: (dict) -> Any """Parse multiple effects from an effects(list) json.""" if isinstance(effects_json, list): return [ValidatorEffect.parse(effect) for effect in effects_json] elif isinstance(effects_json, dict): re...
Parse multiple effects from an effects(list) json.
def query_invitations(cls, user, eager=False): """Get all invitations for given user.""" if eager: eager = [Membership.group] return cls.query_by_user(user, state=MembershipState.PENDING_USER, eager=eager)
Get all invitations for given user.
def _erase_vm_info(name): ''' erase the information for a VM the we are destroying. some sdb drivers (such as the SQLite driver we expect to use) do not have a `delete` method, so if the delete fails, we have to replace the with a blank entry. ''' try: # delete the machine record ...
erase the information for a VM the we are destroying. some sdb drivers (such as the SQLite driver we expect to use) do not have a `delete` method, so if the delete fails, we have to replace the with a blank entry.
def _baseplot(cls, session, type, *args, **kwargs): """ Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all pl...
Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all plot-type specific positional and keyword arguments, which will be...
def read_list_from_csv(filepath, dict_form=False, headers=None, **kwargs): # type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]] """Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of mu...
Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line headers) to be considered as headers (rows start counting at 1), or the actual headers defined a list of strings. If not set, all rows will be treated as c...
def _mkpda(self, nonterms, productions, productions_struct, terminals, splitstring=1): """ This function generates a PDA from a CNF grammar as described in: - http://www.oit.edu/faculty/sherry.yang/CST229/Lectures/7_pda.pdf - http://www.eng.utah.edu/~cs3100/lectures/l18/pda-notes.p...
This function generates a PDA from a CNF grammar as described in: - http://www.oit.edu/faculty/sherry.yang/CST229/Lectures/7_pda.pdf - http://www.eng.utah.edu/~cs3100/lectures/l18/pda-notes.pdf If all of the grammar productions are in the Chomsky Normal Form, then follow the templ...
def early_create_objects(self, raw_objects): """Create the objects needed for the post configuration file initialization :param raw_objects: dict with all object with str values :type raw_objects: dict :return: None """ types_creations = self.__class__.types_creations ...
Create the objects needed for the post configuration file initialization :param raw_objects: dict with all object with str values :type raw_objects: dict :return: None
def _attach(self, instruction, qargs, cargs): """DEPRECATED after 0.8""" self.append(instruction, qargs, cargs)
DEPRECATED after 0.8
def pitch(self, shift, use_tree=False, segment=82, search=14.68, overlap=12): """pitch takes 4 parameters: user_tree (True or False), segment, search and overlap.""" self.command.append("pitch") if use_tree: self.command...
pitch takes 4 parameters: user_tree (True or False), segment, search and overlap.
def p_property_decl(self, p): """ property_decl : prop_open style_list t_semicolon | prop_open style_list css_important t_semicolon | prop_open empty t_semicolon """ l = len(p) p[0] = Property(list(p)[1:-1]...
property_decl : prop_open style_list t_semicolon | prop_open style_list css_important t_semicolon | prop_open empty t_semicolon
def emboss_pepstats_on_fasta(infile, outfile='', outdir='', outext='.pepstats', force_rerun=False): """Run EMBOSS pepstats on a FASTA file. Args: infile: Path to FASTA file outfile: Name of output file without extension outdir: Path to output directory outext: Extension of resul...
Run EMBOSS pepstats on a FASTA file. Args: infile: Path to FASTA file outfile: Name of output file without extension outdir: Path to output directory outext: Extension of results file, default is ".pepstats" force_rerun: Flag to rerun pepstats Returns: str: Path...
def query_by_post(postid): ''' Query records by post. ''' return TabPost2Tag.select().where( TabPost2Tag.post_id == postid ).order_by(TabPost2Tag.order)
Query records by post.
def prepare(self, engine, mode, items) -> None: """ Create a unique transaction id and dumps the items into a cached request object. """ self.tx_id = str(uuid.uuid4()).replace("-", "") self.engine = engine self.mode = mode self.items = items self._prepare_...
Create a unique transaction id and dumps the items into a cached request object.
def user_order_by(self, field): """ Queryset method ordering objects by user ordering field. """ # Get ordering model. model_label = order.utils.resolve_labels('.'.join(\ [self.model._meta.app_label, self.model._meta.object_name])) orderitem_set = getattr(self.model, \ or...
Queryset method ordering objects by user ordering field.
def get_total_DOS(self): """Return frequency points and total DOS as a tuple. Returns ------- A tuple with (frequency_points, total_dos). frequency_points: ndarray shape=(frequency_sampling_points, ), dtype='double' total_dos: shape=(frequency_sa...
Return frequency points and total DOS as a tuple. Returns ------- A tuple with (frequency_points, total_dos). frequency_points: ndarray shape=(frequency_sampling_points, ), dtype='double' total_dos: shape=(frequency_sampling_points, ), dtype='double'
def suspendMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_suspendMember(clusterId, memberId) return self.recv_suspendMember()
Parameters: - clusterId - memberId
def error(self): """ Class property: Sum of the squared errors, :math:`E = \sum_i (D_i - M_i(\\theta))^2` """ r = self.residuals.ravel() return np.dot(r,r)
Class property: Sum of the squared errors, :math:`E = \sum_i (D_i - M_i(\\theta))^2`
def _transform_index(index, func, level=None): """ Apply function to all values found in index. This includes transforming multiindex entries separately. Only apply function to one level of the MultiIndex if level is specified. """ if isinstance(index, MultiIndex): if level is not None...
Apply function to all values found in index. This includes transforming multiindex entries separately. Only apply function to one level of the MultiIndex if level is specified.
def teardown(self): """Cleanup cache tables.""" for table_spec in reversed(self._table_specs): with self._conn: table_spec.teardown(self._conn)
Cleanup cache tables.
def get_ssh_client(ip, ssh_private_key_file, ssh_user='root', port=22, timeout=600, wait_period=10): """Attempt to establish and test ssh connection.""" if ip in CLIENT_CACHE: return CLIENT_CACHE[ip] star...
Attempt to establish and test ssh connection.
def list_extmods(): ''' .. versionadded:: 2017.7.0 List Salt modules which have been synced externally CLI Examples: .. code-block:: bash salt '*' saltutil.list_extmods ''' ret = {} ext_dir = os.path.join(__opts__['cachedir'], 'extmods') mod_types = os.listdir(ext_dir) ...
.. versionadded:: 2017.7.0 List Salt modules which have been synced externally CLI Examples: .. code-block:: bash salt '*' saltutil.list_extmods
def get_magnitude_scaling_term(self, C, mag): """ Returns the magnitude scaling term (equation 1) """ mval = mag - 3.0 return C['b1'] + C['b2'] * mval + C['b3'] * (mval ** 2.0) +\ C['b4'] * (mval ** 3.0)
Returns the magnitude scaling term (equation 1)
def get_scope_names(self) -> list: """ Return the list of all contained scope from global to local """ # allow global scope to have an None string instance lscope = [] for scope in reversed(self.get_scope_list()): if scope.name is not None: # h...
Return the list of all contained scope from global to local
def reads_overlapping_variant( samfile, variant, chromosome=None, use_duplicate_reads=USE_DUPLICATE_READS, use_secondary_alignments=USE_SECONDARY_ALIGNMENTS, min_mapping_quality=MIN_READ_MAPPING_QUALITY): """ Find reads in the given SAM/BAM file which overlap the ...
Find reads in the given SAM/BAM file which overlap the given variant and return them as a list of AlleleRead objects. Parameters ---------- samfile : pysam.AlignmentFile variant : varcode.Variant chromosome : str use_duplicate_reads : bool Should we use reads that have been marke...
def exec_python(*args, **kwargs): """ Wrap running python script in a subprocess. Return stdout of the invoked command. """ cmdargs, kwargs = __wrap_python(args, kwargs) return exec_command(*cmdargs, **kwargs)
Wrap running python script in a subprocess. Return stdout of the invoked command.
def frameAndSave(abf,tag="",dataType="plot",saveAsFname=False,closeWhenDone=True): """ frame the current matplotlib plot with ABF info, and optionally save it. Note that this is entirely independent of the ABFplot class object. if saveImage is False, show it instead. Datatype should be: * p...
frame the current matplotlib plot with ABF info, and optionally save it. Note that this is entirely independent of the ABFplot class object. if saveImage is False, show it instead. Datatype should be: * plot * experiment
def run_command(cmd, debug=False): """ Execute the given command and return None. :param cmd: A `sh.Command` object to execute. :param debug: An optional bool to toggle debug output. :return: None """ if debug: msg = ' PWD: {}'.format(os.getcwd()) print_warn(msg) ms...
Execute the given command and return None. :param cmd: A `sh.Command` object to execute. :param debug: An optional bool to toggle debug output. :return: None
def GetScripts(self, dest_dir): """Retrieve the scripts to execute. Args: dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping set metadata keys with associated scripts. """ metadata_dict = self.watcher.GetMetadata() or {} try...
Retrieve the scripts to execute. Args: dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping set metadata keys with associated scripts.
def get_variant_phenotypes_with_suggested_changes(variant_id_list): '''for each variant, yields evidence and associated phenotypes, both current and suggested''' variants = civic.get_variants_by_ids(variant_id_list) evidence = list() for variant in variants: evidence.extend(variant.evidence) ...
for each variant, yields evidence and associated phenotypes, both current and suggested
def load_edgegrid_client_settings(): '''Load Akamai EdgeGrid configuration returns a (hostname, EdgeGridAuth) tuple from the following locations: 1. Values specified directly in the Django settings:: AKAMAI_CCU_CLIENT_SECRET AKAMAI_CCU_HOST AKAMAI_CCU_ACCESS_TOKEN AKAMAI_CC...
Load Akamai EdgeGrid configuration returns a (hostname, EdgeGridAuth) tuple from the following locations: 1. Values specified directly in the Django settings:: AKAMAI_CCU_CLIENT_SECRET AKAMAI_CCU_HOST AKAMAI_CCU_ACCESS_TOKEN AKAMAI_CCU_CLIENT_TOKEN 2. An edgerc file specifi...
def _restart_target(self): """ Restart our Target. """ if self._server: if self._server.returncode is None: self._server.kill() time.sleep(0.2) self._server = subprocess.Popen("python session_server.py", stdout=subprocess.PIPE, stderr=s...
Restart our Target.
def end_task(self): ''' Remove the current task from the stack. ''' self.progress(self.task_stack[-1].size) self.task_stack.pop()
Remove the current task from the stack.
def get_navigation(request): """ Returns the rendered navigation block. Requires that the `navigation.html` template exists. Two context variables are passed to it: * sections (see :func:`get_breadcrumb_sections`) * trail (see :func:`get_breadcrumb_trail`) """ sections = _get_sections(request)...
Returns the rendered navigation block. Requires that the `navigation.html` template exists. Two context variables are passed to it: * sections (see :func:`get_breadcrumb_sections`) * trail (see :func:`get_breadcrumb_trail`)
def _wait_for_job_done(self, project_id, job_id, interval=30): """ Waits for the Job to reach a terminal state. This method will periodically check the job state until the job reach a terminal state. Raises: googleapiclient.errors.HttpError: if HTTP error is returne...
Waits for the Job to reach a terminal state. This method will periodically check the job state until the job reach a terminal state. Raises: googleapiclient.errors.HttpError: if HTTP error is returned when getting the job
def freeze(self, progressbar=None): """ Convert :class:`dtoolcore.ProtoDataSet` to :class:`dtoolcore.DataSet`. """ # Call the storage broker pre_freeze hook. self._storage_broker.pre_freeze_hook() if progressbar: progressbar.label = "Freezing dataset" ...
Convert :class:`dtoolcore.ProtoDataSet` to :class:`dtoolcore.DataSet`.
def has_hlu(self, lun_or_snap, cg_member=None): """Returns True if `lun_or_snap` is attached to the host. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: True - if `lu...
Returns True if `lun_or_snap` is attached to the host. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: True - if `lun_or_snap` is attached, otherwise False.
def initialize_workflow(self, workflow): """ Create a workflow workflow - a workflow class """ self.workflow = workflow() self.workflow.tasks = self.tasks self.workflow.input_file = self.input_file self.workflow.input_format = self.input_format se...
Create a workflow workflow - a workflow class
def acm_certificate_arn(self, lookup, default=None): """ Args: lookup: region/domain on the certificate to be looked up default: the optional value to return if lookup failed; returns None if not set Returns: ARN of a certificate with status "Issued" for the region/domain, if found, or def...
Args: lookup: region/domain on the certificate to be looked up default: the optional value to return if lookup failed; returns None if not set Returns: ARN of a certificate with status "Issued" for the region/domain, if found, or default/None if no match If more than one "Issued" certificate...
def safe_popen(*args, **kwargs): '''This wrapper works around two major deadlock issues to do with pipes. The first is that, before Python 3.2 on POSIX systems, os.pipe() creates inheritable file descriptors, which leak to all child processes and prevent reads from reaching EOF. The workaround for this ...
This wrapper works around two major deadlock issues to do with pipes. The first is that, before Python 3.2 on POSIX systems, os.pipe() creates inheritable file descriptors, which leak to all child processes and prevent reads from reaching EOF. The workaround for this is to set close_fds=True on POSIX, w...
def minter(record_uuid, data, pid_type, key): """Mint PIDs for a record.""" pid = PersistentIdentifier.create( pid_type, data[key], object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED ) for scheme, identifier in data['identifiers'].items(): ...
Mint PIDs for a record.
def from_context(cls): """Retrieve this class' instance from the current Click context. :return: Instance of this class. :rtype: Config """ try: ctx = click.get_current_context() except RuntimeError: return cls() return ctx.find_object(cls...
Retrieve this class' instance from the current Click context. :return: Instance of this class. :rtype: Config
def _add_timeout_handler(self, handler): """Add a `TimeoutHandler` to the main loop.""" # pylint: disable-msg=W0212 now = time.time() for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue se...
Add a `TimeoutHandler` to the main loop.
def list_not_state(subset=None, show_ip=False, show_ipv4=None): ''' .. versionadded:: 2015.8.0 .. versionchanged:: 2019.2.0 The 'show_ipv4' argument has been renamed to 'show_ip' as it now includes IPv6 addresses for IPv6-connected minions. Print a list of all minions that are NOT up ac...
.. versionadded:: 2015.8.0 .. versionchanged:: 2019.2.0 The 'show_ipv4' argument has been renamed to 'show_ip' as it now includes IPv6 addresses for IPv6-connected minions. Print a list of all minions that are NOT up according to Salt's presence detection (no commands will be sent to minion...
def all(self, value, pos=None): """Return True if one or many bits are all set to value. value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way...
Return True if one or many bits are all set to value. value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the whole bi...
def pack_bytes(self, obj_dict, encoding=None): """Pack a dictionary into a byte stream.""" assert self.dict_to_bytes or self.dict_to_string encoding = encoding or self.default_encoding or 'utf-8' LOGGER.debug('%r encoding dict with encoding %s', self, encoding) if self.dict_to_by...
Pack a dictionary into a byte stream.
def has(*permissions, **kwargs): """ Checks if the passed bearer has the passed permissions (optionally on the passed target). """ target = kwargs['target'] kwargs['target'] = type_for(target) # TODO: Predicate evaluation? return target in filter_(*permissions, **kwargs)
Checks if the passed bearer has the passed permissions (optionally on the passed target).
def validate_base_url(base_url): """Verify that base_url specifies a protocol and network location.""" parsed_url = urllib.parse.urlparse(base_url) if parsed_url.scheme and parsed_url.netloc: return parsed_url.geturl() else: error_message = "base_url must contain a valid scheme (protocol...
Verify that base_url specifies a protocol and network location.
def convert_datetime(obj): """Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values ar...
Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values are returned as None: >>> dat...
def translate_basic(usercode): """ Translate a basic color name to color with explanation. """ codenum = get_code_num(codes['fore'][usercode]) colorcode = codeformat(codenum) msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format( usercode, codenum, colorcode ) if d...
Translate a basic color name to color with explanation.
def copy(self, sleep=_unset, stop=_unset, wait=_unset, retry=_unset, before=_unset, after=_unset, before_sleep=_unset, reraise=_unset): """Copy this object with some parameters changed if needed.""" if before_sleep is _unset: before_sleep = self.before_sleep ...
Copy this object with some parameters changed if needed.
def writeRecord(self, infile): """Writes to _infile_ the original contents of the Record. This is intended for use by [RecordCollections](./RecordCollection.html#metaknowledge.RecordCollection) to write to file. What is written to _infile_ is bit for bit identical to the original record file (if utf-8 is used)....
Writes to _infile_ the original contents of the Record. This is intended for use by [RecordCollections](./RecordCollection.html#metaknowledge.RecordCollection) to write to file. What is written to _infile_ is bit for bit identical to the original record file (if utf-8 is used). No newline is inserted above the write bu...
def patch_all(): """ Runs all patches. This function ensures that a second invocation has no effect. """ global _patched if _patched: return _patched = True patch_default_retcodes() patch_worker_run_task() patch_worker_factory() patch_keepalive_run() patch_cmdline_p...
Runs all patches. This function ensures that a second invocation has no effect.
def UpdateManifestResourcesFromXML(dstpath, xmlstr, names=None, languages=None): """ Update or add manifest XML as resource in dstpath """ logger.info("Updating manifest in %s", dstpath) if dstpath.lower().endswith(".exe"): name = 1 else: name = 2 ...
Update or add manifest XML as resource in dstpath
def assert_requirements(self): """"Asserts PEP 508 specifiers.""" # Support for 508's implementation_version. if hasattr(sys, 'implementation'): implementation_version = format_full_version(sys.implementation.version) else: implementation_version = "0" #...
Asserts PEP 508 specifiers.
def redata(self, *args): """Make my data represent what's in my rulebook right now""" if self.rulesview is None: Clock.schedule_once(self.redata, 0) return data = [ {'rulesview': self.rulesview, 'rule': rule, 'index': i, 'ruleslist': self} for i, r...
Make my data represent what's in my rulebook right now
def do_plot_and_bestfit(self): """ Create plot """ # Plot fmt = str(self.kwargs.get("fmt", "k.")) if "errors" in self.kwargs: errors = self.kwargs["errors"] if isinstance(errors, dict): self.subplot.errorbar(self.x, self.y, fmt=fmt,...
Create plot
def get_process_path(tshark_path=None, process_name="tshark"): """ Finds the path of the tshark executable. If the user has provided a path or specified a location in config.ini it will be used. Otherwise default locations will be searched. :param tshark_path: Path of the tshark binary :raises ...
Finds the path of the tshark executable. If the user has provided a path or specified a location in config.ini it will be used. Otherwise default locations will be searched. :param tshark_path: Path of the tshark binary :raises TSharkNotFoundException in case TShark is not found in any location.
def rank_path(graph, path, edge_ranking=None): """Takes in a path (a list of nodes in the graph) and calculates a score :param pybel.BELGraph graph: A BEL graph :param list[tuple] path: A list of nodes in the path (includes terminal nodes) :param dict edge_ranking: A dictionary of {relationship: score}...
Takes in a path (a list of nodes in the graph) and calculates a score :param pybel.BELGraph graph: A BEL graph :param list[tuple] path: A list of nodes in the path (includes terminal nodes) :param dict edge_ranking: A dictionary of {relationship: score} :return: The score for the edge :rtype: int
def _static_folder_path(static_url, static_folder, static_asset): """ Returns a path to a file based on the static folder, and not on the filesystem holding the file. Returns a path relative to static_url for static_asset """ # first get the asset path relative to the static folder. # stati...
Returns a path to a file based on the static folder, and not on the filesystem holding the file. Returns a path relative to static_url for static_asset
async def can(self, identity, permission) -> bool: """ Check user permissions. :return: ``True`` if the identity is allowed the permission, else return ``False``. """ assert isinstance(permission, (str, enum.Enum)), permission assert permission identify = await s...
Check user permissions. :return: ``True`` if the identity is allowed the permission, else return ``False``.
def enable_broadcasting(self): """Begin accumulating broadcast reports received from all devices. This method will allocate a queue to receive broadcast reports that will be filled asynchronously as broadcast reports are received. Returns: queue.Queue: A queue that will be ...
Begin accumulating broadcast reports received from all devices. This method will allocate a queue to receive broadcast reports that will be filled asynchronously as broadcast reports are received. Returns: queue.Queue: A queue that will be filled with braodcast reports.
def get_user_info(self, access_token): """Function to get the information about the user using the access code obtained from the OP Note: Refer to the /.well-known/openid-configuration URL of your OP for the complete list of the claims for different scopes. Para...
Function to get the information about the user using the access code obtained from the OP Note: Refer to the /.well-known/openid-configuration URL of your OP for the complete list of the claims for different scopes. Parameters: * **access_token (string):** a...
def set_states(self, states=None, value=None): """Sets value for states. Only one of states & values can be specified. Parameters ---------- states : list of list of NDArrays Source states arrays formatted like ``[[state1_dev1, state1_dev2], [state2_dev1, state2_...
Sets value for states. Only one of states & values can be specified. Parameters ---------- states : list of list of NDArrays Source states arrays formatted like ``[[state1_dev1, state1_dev2], [state2_dev1, state2_dev2]]``. value : number A single scal...
def get_or_set_default(self, section, option, value): """ Base method to fetch values and to set defaults in case they don't exist. """ try: ret = self.get(section, option) except MissingSetting: self.set(section, option, value) ret = v...
Base method to fetch values and to set defaults in case they don't exist.
def update(self, forecasts, observations): """ Update the statistics with forecasts and observations. Args: forecasts: The discrete Cumulative Distribution Functions of observations: """ if len(observations.shape) == 1: obs_cdfs = np.zeros((ob...
Update the statistics with forecasts and observations. Args: forecasts: The discrete Cumulative Distribution Functions of observations:
def find_magic(self, magic_name, magic_kind='line'): """Find and return a magic of the given type by name. Returns None if the magic isn't found.""" return self.magics_manager.magics[magic_kind].get(magic_name)
Find and return a magic of the given type by name. Returns None if the magic isn't found.
def create(self, parameters): """ Create a new item (if supported) :param parameters: dict :return: dict|str """ response = self._client.session.post( '{url}/new'.format(url=self.endpoint_url), data=parameters ) return self.process_response(re...
Create a new item (if supported) :param parameters: dict :return: dict|str
def __applytns(self, root): """Make sure included schema has the same target namespace.""" TNS = "targetNamespace" tns = root.get(TNS) if tns is None: tns = self.schema.tns[1] root.set(TNS, tns) else: if self.schema.tns[1] != tns: ...
Make sure included schema has the same target namespace.
def _node_type(st): """ return a string indicating the type of special node represented by the stat buffer st (block, character, fifo, socket). """ _types = [ (stat.S_ISBLK, "block device"), (stat.S_ISCHR, "character device"), (stat.S_ISFIFO, "named pipe"), (stat.S_ISSOCK...
return a string indicating the type of special node represented by the stat buffer st (block, character, fifo, socket).
def _add_onchain_locksroot_to_snapshot( raiden: RaidenService, storage: SQLiteStorage, snapshot_record: StateChangeRecord, ) -> str: """ Add `onchain_locksroot` to each NettingChannelEndState """ snapshot = json.loads(snapshot_record.data) for payment_network in snapshot.get...
Add `onchain_locksroot` to each NettingChannelEndState
def date_range_for_webtrends(cls, start_at=None, end_at=None): """ Get the day dates in between start and end formatted for query. This returns dates inclusive e.g. final day is (end_at, end_at+1 day) """ if start_at and end_at: start_date = cls.parse_standard_date_st...
Get the day dates in between start and end formatted for query. This returns dates inclusive e.g. final day is (end_at, end_at+1 day)
def put(self, key, value): """ >>> c = MemSizeLRUCache(maxmem=24*4) >>> c.put(1, 1) >>> c.mem() # 24-bytes per integer 24 >>> c.put(2, 2) >>> c.put(3, 3) >>> c.put(4, 4) >>> c.get(1) 1 >>> c.mem() 96 >>> c.size() ...
>>> c = MemSizeLRUCache(maxmem=24*4) >>> c.put(1, 1) >>> c.mem() # 24-bytes per integer 24 >>> c.put(2, 2) >>> c.put(3, 3) >>> c.put(4, 4) >>> c.get(1) 1 >>> c.mem() 96 >>> c.size() 4 >>> c.put(5, 5) >>> c.si...
def json_query(data, expr): ''' Query data using JMESPath language (http://jmespath.org). ''' if jmespath is None: err = 'json_query requires jmespath module installed' log.error(err) raise RuntimeError(err) return jmespath.search(expr, data)
Query data using JMESPath language (http://jmespath.org).
def intrusion_sets(self, name, owner=None, **kwargs): """ Create the Intrustion Set TI object. Args: owner: name: **kwargs: Return: """ return IntrusionSet(self.tcex, name, owner=owner, **kwargs)
Create the Intrustion Set TI object. Args: owner: name: **kwargs: Return:
def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0....
Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authent...
def convert_dedent(self): """Convert a dedent into an indent""" # Dedent means go back to last indentation if self.indent_amounts: self.indent_amounts.pop() # Change the token tokenum = INDENT # Get last indent amount last_indent = 0 if self....
Convert a dedent into an indent
def fetch(cls, id, api_key=None, endpoint=None, add_headers=None, **kwargs): """ Fetch a single entity from the API endpoint. Used when you know the exact ID that must be queried. """ if endpoint is None: endpoint = cls.get_endpoint() inst = cl...
Fetch a single entity from the API endpoint. Used when you know the exact ID that must be queried.
def single_row_or_col_df_to_dict(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\ -> Dict[str, str]: """ Helper method to convert a dataframe with one row or one or two columns into a dictionary :param desired_type: :param single_rowcol_df: :param logger: ...
Helper method to convert a dataframe with one row or one or two columns into a dictionary :param desired_type: :param single_rowcol_df: :param logger: :param kwargs: :return:
def _stmt_list(self, stmts, indent=True): """return a list of nodes to string""" stmts = "\n".join(nstr for nstr in [n.accept(self) for n in stmts] if nstr) if indent: return self.indent + stmts.replace("\n", "\n" + self.indent) return stmts
return a list of nodes to string
def _render_content_list(self, content, depth, dstack, **settings): """ Render the list. """ result = [] i = 0 size = len(content) for value in content: ds = [(depth, i, size)] ds = dstack + ds if isinstance(value, dict): ...
Render the list.
def dt_str_to_posix(dt_str): """format str to posix. datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ, e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator between date and time when they are on the same line. Z indicates UTC (zero meridian). A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-...
format str to posix. datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ, e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator between date and time when they are on the same line. Z indicates UTC (zero meridian). A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-time.html This is used to parse...
def getCoords(self): ''' Gets the coords of the View @return: A tuple containing the View's coordinates ((L, T), (R, B)) ''' if DEBUG_COORDS: print >>sys.stderr, "getCoords(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId()) (x, y) = self.ge...
Gets the coords of the View @return: A tuple containing the View's coordinates ((L, T), (R, B))
def cmd_queue_peaks(self): """Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which pe...
Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which peak can be ignored. Currently ...
def get_spider_stats(self): ''' Gather spider based stats ''' self.logger.debug("Gathering spider stats") the_dict = {} spider_set = set() total_spider_count = 0 keys = self.redis_conn.keys('stats:crawler:*:*:*') for key in keys: # we ...
Gather spider based stats
def _get_id2gos(self, associations, **kws): """Return given associations in a dict, id2gos""" options = AnnoOptions(self.evobj, **kws) # Default reduction is to remove. For all options, see goatools/anno/opts.py: # * Evidence_Code == ND -> No biological data No biological Data availabl...
Return given associations in a dict, id2gos
def do_build(self): """ We need this hack, else 'self' would be replaced by __iter__.next(). """ tmp = self.explicit self.explicit = True b = super(KeyShareEntry, self).do_build() self.explicit = tmp return b
We need this hack, else 'self' would be replaced by __iter__.next().
def get_elements(self, json_string, expr): """ Get list of elements from _json_string_, matching [http://goessner.net/articles/JsonPath/|JSONPath] expression. *Args:*\n _json_string_ - JSON string;\n _expr_ - JSONPath expression; *Returns:*\n List of found eleme...
Get list of elements from _json_string_, matching [http://goessner.net/articles/JsonPath/|JSONPath] expression. *Args:*\n _json_string_ - JSON string;\n _expr_ - JSONPath expression; *Returns:*\n List of found elements or ``None`` if no elements were found *Example:*\n...
def order_by_json_path(self, json_path, language_code=None, order='asc'): """ Orders a queryset by the value of the specified `json_path`. More about the `#>>` operator and the `json_path` arg syntax: https://www.postgresql.org/docs/current/static/functions-json.html More about...
Orders a queryset by the value of the specified `json_path`. More about the `#>>` operator and the `json_path` arg syntax: https://www.postgresql.org/docs/current/static/functions-json.html More about Raw SQL expressions: https://docs.djangoproject.com/en/dev/ref/models/expressions/#ra...
def renderThumbnail(self, relpath=""): """renderThumbnail() is called to render a thumbnail of the DP (e.g. in Data Product tables).""" # no thumbnail -- return empty string if self.thumbnail is None: return "" # else thumbnail is same as full image (because image was small e...
renderThumbnail() is called to render a thumbnail of the DP (e.g. in Data Product tables).
def remote_command(function, self, *args, **kwargs): ''' Catch `RuntimeError` exceptions raised by remote control board firmware commands and re-raise as more specific `FirmwareError` exception type, which includes command code and return code. ''' try: return function(self, *args, **kwa...
Catch `RuntimeError` exceptions raised by remote control board firmware commands and re-raise as more specific `FirmwareError` exception type, which includes command code and return code.
def _eval_target_brutal(state, ip, limit): """ The traditional way of evaluating symbolic jump targets. :param state: A SimState instance. :param ip: The AST of the instruction pointer to evaluate. :param limit: The maximum number of concrete IPs. :return: ...
The traditional way of evaluating symbolic jump targets. :param state: A SimState instance. :param ip: The AST of the instruction pointer to evaluate. :param limit: The maximum number of concrete IPs. :return: A list of conditions and the corresponding concrete IPs. ...
def pop(self, key, default=NONE): """ If *key* is in the dictionary, remove it and return its value, else return *default*. If *default* is not given and *key* is not in the dictionary, a KeyError is raised. """ if key in self: self._list_remove(key) ...
If *key* is in the dictionary, remove it and return its value, else return *default*. If *default* is not given and *key* is not in the dictionary, a KeyError is raised.
def _default_transform_fn(self, model, content, content_type, accept): """Make predictions against the model and return a serialized response. This serves as the default implementation of transform_fn, used when the user has not implemented one themselves. Args: model (obj)...
Make predictions against the model and return a serialized response. This serves as the default implementation of transform_fn, used when the user has not implemented one themselves. Args: model (obj): model loaded by model_fn. content: request content. cont...
def render_name(self, template_name, *context, **kwargs): """ Render the template with the given name using the given context. See the render() docstring for more information. """ loader = self._make_loader() template = loader.load_name(template_name) return sel...
Render the template with the given name using the given context. See the render() docstring for more information.
def eol_distance_last(self, offset=0): """Return the ammount of characters until the last newline.""" distance = 0 for char in reversed(self.string[:self.pos + offset]): if char == '\n': break else: distance += 1 return distance
Return the ammount of characters until the last newline.
def _parse_package(cls, package_string): """ Helper method for parsing package string. Args: package_string (str): dash separated package string such as 'bash-4.2.39-3.el7' Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys ...
Helper method for parsing package string. Args: package_string (str): dash separated package string such as 'bash-4.2.39-3.el7' Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys
def to_str(obj): """ convert a object to string """ if isinstance(obj, str): return obj if isinstance(obj, unicode): return obj.encode('utf-8') return str(obj)
convert a object to string
def get_site(self, *args): """ Returns a sharepoint site :param args: It accepts multiple ways of retrieving a site: get_site(host_name): the host_name: host_name ej. 'contoso.sharepoint.com' or 'root' get_site(site_id): the site_id: a comma separated string of (ho...
Returns a sharepoint site :param args: It accepts multiple ways of retrieving a site: get_site(host_name): the host_name: host_name ej. 'contoso.sharepoint.com' or 'root' get_site(site_id): the site_id: a comma separated string of (host_name, site_collection_id, site_id) ...